From fa06d77df8272afb13814aa500366a6ea45e0e8a Mon Sep 17 00:00:00 2001 From: Vladyslav Chernov Date: Mon, 24 Jul 2023 13:17:40 -0700 Subject: [PATCH 001/233] BAEL-5852: What does the Holder do in Java? --- .../main/java/com/baeldung/holder/Holder.java | 9 ++++++ .../com/baeldung/holder/SupplierService.java | 13 ++++++++ .../holder/SupplierServiceUnitTest.java | 31 +++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/Holder.java create mode 100644 core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java create mode 100644 core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/holder/SupplierServiceUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/Holder.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/Holder.java new file mode 100644 index 0000000000..da066ee5c6 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/Holder.java @@ -0,0 +1,9 @@ +package com.baeldung.holder; + +public class Holder { + public T value; + + public Holder(T value) { + this.value = value; + } +} diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java new file mode 100644 index 0000000000..473a4de423 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java @@ -0,0 +1,13 @@ +package com.baeldung.holder; + +public class SupplierService { + public void getSupplierByZipCode(String zip, Holder resultHolder) { + // Let's pretend we did some work here to get the supplier + // And let's say all zip codes starting with "9" are valid, just for this example + if (zip.startsWith("9")) { + resultHolder.value = true; + } else { + resultHolder.value = false; + } + } +} diff --git a/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/holder/SupplierServiceUnitTest.java b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/holder/SupplierServiceUnitTest.java new file mode 100644 index 0000000000..e1446fc229 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/holder/SupplierServiceUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.holder; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +public class SupplierServiceUnitTest { + + @Test + public void givenValidZipCode_whenGetSupplierByZipCode_thenTrue() { + SupplierService service = new SupplierService(); + Holder resultHolder = new Holder<>(false); + String zipCode = "98682"; + + service.getSupplierByZipCode(zipCode, resultHolder); + + assertTrue(resultHolder.value); + } + + @Test + public void givenInvalidZipCode_whenGetSupplierByZipCode_thenFalse() { + SupplierService service = new SupplierService(); + Holder resultHolder = new Holder<>(true); + String zipCode = "12345"; + + service.getSupplierByZipCode(zipCode, resultHolder); + + assertFalse(resultHolder.value); + } +} From 0bb7a8db27e93e108459f1c9baa340a898a23176 Mon Sep 17 00:00:00 2001 From: Vladyslav Chernov Date: Sun, 17 Sep 2023 21:57:35 -0700 Subject: [PATCH 002/233] BAEL-5755: Convert an XML file to CSV file --- .../baeldung/xml/xml2csv/Xml2CsvExample.java | 113 +++++++++++++ xml/src/main/resources/xml2csv/data.xml | 26 +++ xml/src/main/resources/xml2csv/style.xsl | 21 +++ .../xml/xml2csv/Xml2CsvExampleUnitTest.java | 155 ++++++++++++++++++ 4 files changed, 315 insertions(+) create mode 100644 xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java create mode 100644 xml/src/main/resources/xml2csv/data.xml create mode 100644 xml/src/main/resources/xml2csv/style.xsl create mode 100644 xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java diff --git a/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java b/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java new file mode 100644 index 0000000000..d2acafc881 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java @@ -0,0 +1,113 @@ +package com.baeldung.xml.xml2csv; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +public class Xml2CsvExample { + + private static final String BASE_PATH = "xml/src/main/resources/xml2csv/"; + + private static final String STYLE_XSL = BASE_PATH + "style.xsl"; + private static final String DATA_XML = BASE_PATH + "data.xml"; + private static final String OUTPUT_CSV_XSTL = BASE_PATH + "output_xstl.csv"; + private static final String OUTPUT_CSV_STAX = BASE_PATH + "output_stax.csv"; + + public static void main(String[] args) { + try { + convertXml2CsvXslt(STYLE_XSL, DATA_XML, OUTPUT_CSV_XSTL); + convertXml2CsvStax(DATA_XML, OUTPUT_CSV_STAX); + } catch (IOException | TransformerException e) { + e.printStackTrace(); + } + } + + 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); + Source source = new StreamSource(new File(xmlPath)); + Result outputTarget = new StreamResult(new File(csvPath)); + transformer.transform(source, outputTarget); + } + + protected static void convertXml2CsvStax(String xmlFilePath, String csvFilePath) throws IOException, TransformerException { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + + try (InputStream in = Files.newInputStream(Paths.get(xmlFilePath)); BufferedWriter writer = new BufferedWriter(new FileWriter(csvFilePath))) { + + // Write header to CSV + writer.write("bookstore_id,book_id,category,title,author_id,author_name,price\n"); + + XMLStreamReader reader = inputFactory.createXMLStreamReader(in); + + String currentElement; + StringBuilder csvRow = new StringBuilder(); + StringBuilder bookstoreInfo = new StringBuilder(); + + while (reader.hasNext()) { + int eventType = reader.next(); + + switch (eventType) { + case XMLStreamConstants.START_ELEMENT: + currentElement = reader.getLocalName(); + if ("Bookstore".equals(currentElement)) { + bookstoreInfo.setLength(0); // clear previous bookstore info + bookstoreInfo.append(reader.getAttributeValue(null, "id")) + .append(","); + } + if ("Book".equals(currentElement)) { + csvRow.append(bookstoreInfo) + .append(reader.getAttributeValue(null, "id")) + .append(",") + .append(reader.getAttributeValue(null, "category")) + .append(","); + } + if ("Author".equals(currentElement)) { + csvRow.append(reader.getAttributeValue(null, "id")) + .append(","); + } + break; + + case XMLStreamConstants.CHARACTERS: + if (!reader.isWhiteSpace()) { + csvRow.append(reader.getText() + .trim()) + .append(","); + } + break; + + case XMLStreamConstants.END_ELEMENT: + if ("Book".equals(reader.getLocalName())) { + // remove the last comma and add a newline + csvRow.setLength(csvRow.length() - 1); + csvRow.append("\n"); + writer.write(csvRow.toString()); + + // Reset the StringBuilder for the next row + csvRow.setLength(0); + } + break; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/xml/src/main/resources/xml2csv/data.xml b/xml/src/main/resources/xml2csv/data.xml new file mode 100644 index 0000000000..385fcf661c --- /dev/null +++ b/xml/src/main/resources/xml2csv/data.xml @@ -0,0 +1,26 @@ + + + + + + Death and the Penguin + Andrey Kurkov + 10.99 + + + Kobzar + Taras Shevchenko + 8.50 + + + + + + + Voroshilovgrad + Serhiy Zhadan + 12.99 + + + + diff --git a/xml/src/main/resources/xml2csv/style.xsl b/xml/src/main/resources/xml2csv/style.xsl new file mode 100644 index 0000000000..ea23880092 --- /dev/null +++ b/xml/src/main/resources/xml2csv/style.xsl @@ -0,0 +1,21 @@ + + + + + bookstore_id,book_id,category,title,author_id,author_name,price + + + + + + + + + + + + + + + + diff --git a/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java b/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java new file mode 100644 index 0000000000..3fa44b427c --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java @@ -0,0 +1,155 @@ +package com.baeldung.xml.xml2csv; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.xml.transform.TransformerException; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +public class Xml2CsvExampleUnitTest { + + private static final String BASE_PATH = "src/main/resources/xml2csv/"; + + private static final String STYLE_XSL = BASE_PATH + "style.xsl"; + private static final String DATA_XML = BASE_PATH + "data.xml"; + private static final String TEMP_OUTPUT_CSV = BASE_PATH + "tempOutput.xml"; + + @AfterEach + public void teardown() { + new File(TEMP_OUTPUT_CSV).delete(); + } + + @Test + public void whenConvertXml2CsvXslt_thenCsvFileIsCreated() throws IOException, TransformerException { + Xml2CsvExample.convertXml2CsvXslt(STYLE_XSL, DATA_XML, TEMP_OUTPUT_CSV); + + File csvFile = new File(TEMP_OUTPUT_CSV); + assertTrue(csvFile.exists()); + } + + @Test + public void whenConvertXml2CsvStax_thenCsvFileIsCreated() throws IOException, TransformerException { + Xml2CsvExample.convertXml2CsvStax(DATA_XML, TEMP_OUTPUT_CSV); + + File csvFile = new File(TEMP_OUTPUT_CSV); + assertTrue(csvFile.exists()); + } + + @Test + public void whenConvertXml2CsvXslt_thenCsvFileIsNotEmpty() throws IOException, TransformerException { + Xml2CsvExample.convertXml2CsvXslt(STYLE_XSL, DATA_XML, TEMP_OUTPUT_CSV); + + File csvFile = new File(TEMP_OUTPUT_CSV); + BufferedReader reader = new BufferedReader(new FileReader(csvFile)); + String firstLine = reader.readLine(); + assertNotNull(firstLine); + assertFalse(firstLine.isEmpty()); + + reader.close(); + } + + @Test + public void whenConvertXml2CsvStax_thenCsvFileIsNotEmpty() throws IOException, TransformerException { + Xml2CsvExample.convertXml2CsvStax(DATA_XML, TEMP_OUTPUT_CSV); + + File csvFile = new File(TEMP_OUTPUT_CSV); + BufferedReader reader = new BufferedReader(new FileReader(csvFile)); + String firstLine = reader.readLine(); + assertNotNull(firstLine); + assertFalse(firstLine.isEmpty()); + + reader.close(); + } + + @Test + public void whenConvertXml2CsvXsltWithWrongXSL_thenThrowsException() { + String xslWrongPath = BASE_PATH + "wrongFile.xsl"; + + assertThrows(TransformerException.class, () -> Xml2CsvExample.convertXml2CsvXslt(xslWrongPath, DATA_XML, TEMP_OUTPUT_CSV)); + } + + @Test + public void whenConvertXml2CsvXslt_thenCsvMatchesPattern() throws IOException, TransformerException { + String headerPattern = "^bookstore_id,book_id,category,title,author_id,author_name,price$"; + String dataPattern = "^[A-Z0-9]+,[A-Z0-9]+,[a-zA-Z]+,[a-zA-Z0-9\\s]+,[A-Z0-9]+,[a-zA-Z\\s]+,\\d+(\\.\\d{2})?$"; + + Xml2CsvExample.convertXml2CsvXslt(STYLE_XSL, DATA_XML, TEMP_OUTPUT_CSV); + + File csvFile = new File(TEMP_OUTPUT_CSV); + try(BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { + String line; + boolean isFirstLine = true; + while ((line = reader.readLine()) != null) { + if (isFirstLine) { + assertTrue(line.matches(headerPattern), "Header does not match pattern"); + isFirstLine = false; + } else { + assertTrue(line.matches(dataPattern), "Data line does not match pattern"); + } + } + } + } + + @Test + public void whenConvertXml2Stax_thenCsvMatchesPattern() throws IOException, TransformerException { + String headerPattern = "^bookstore_id,book_id,category,title,author_id,author_name,price$"; + String dataPattern = "^[A-Z0-9]+,[A-Z0-9]+,[a-zA-Z]+,[a-zA-Z0-9\\s]+,[A-Z0-9]+,[a-zA-Z\\s]+,\\d+(\\.\\d{2})?$"; + + Xml2CsvExample.convertXml2CsvStax(DATA_XML, TEMP_OUTPUT_CSV); + + File csvFile = new File(TEMP_OUTPUT_CSV); + try(BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { + String line; + boolean isFirstLine = true; + while ((line = reader.readLine()) != null) { + if (isFirstLine) { + assertTrue(line.matches(headerPattern), "Header does not match pattern"); + isFirstLine = false; + } else { + assertTrue(line.matches(dataPattern), "Data line does not match pattern"); + } + } + } + } + + @Test + public void whenConcurrentConversion_thenNoErrors() throws InterruptedException { + int numThreads = 10; + ExecutorService service = Executors.newFixedThreadPool(numThreads); + CountDownLatch latch = new CountDownLatch(numThreads); + + for (int i = 0; i < numThreads; i++) { + final int threadId = i; + service.execute(() -> { + String threadSpecificOutputCsv = BASE_PATH + "tempOutput" + threadId + ".csv"; + try { + Xml2CsvExample.convertXml2CsvXslt(STYLE_XSL, DATA_XML, threadSpecificOutputCsv); + assertTrue(Files.exists(Paths.get(threadSpecificOutputCsv)), "File should exist"); + } catch (IOException | TransformerException e) { + fail("Exception should not be thrown: " + e.getMessage()); + } finally { + new File(threadSpecificOutputCsv).delete(); + latch.countDown(); + } + }); + } + + latch.await(); + } + +} From 5c8a1373498a1eed20a14085863c63327fa8a3c9 Mon Sep 17 00:00:00 2001 From: Bipinkumar27 Date: Fri, 6 Oct 2023 17:48:47 +0530 Subject: [PATCH 003/233] JAVA-18764: Chnages made for applcation.yml file --- .../src/main/resources/application.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/security-modules/cas/cas-server/src/main/resources/application.yml b/security-modules/cas/cas-server/src/main/resources/application.yml index 0c4e4ffde2..0fd72c539d 100644 --- a/security-modules/cas/cas-server/src/main/resources/application.yml +++ b/security-modules/cas/cas-server/src/main/resources/application.yml @@ -8,3 +8,19 @@ server: spring: main: allow-bean-definition-overriding: true +cas: + authn: + accept: + users: + jdbc: + query[0]: + sql: SELECT * FROM users WHERE email = ? + url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC + dialect: org.hibernate.dialect.MySQLDialect + user: root + password: root1234 + ddlAuto: none + driverClass: com.mysql.cj.jdbc.Driver + fieldPassword: password + passwordEncoder: + type: NONE From c8bc9634d5ca7f92fe65193ff6ddec6b8682ebfd Mon Sep 17 00:00:00 2001 From: Bipinkumar27 Date: Mon, 9 Oct 2023 21:00:52 +0530 Subject: [PATCH 004/233] JAVA-18764: Update article "CAS SSO with Spring Security" --- security-modules/cas/cas-secured-app/pom.xml | 9 ++++ .../cassecuredapp/CasSecuredApplication.java | 11 ++++- .../cassecuredapp/MyUserDetailsService.java | 34 +++++++++++++++ .../cassecuredapp/UserRepository.java | 15 +++++++ .../com/baeldung/cassecuredapp/Users.java | 41 +++++++++++++++++++ .../src/main/resources/application.properties | 8 +++- 6 files changed, 115 insertions(+), 3 deletions(-) create mode 100644 security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/MyUserDetailsService.java create mode 100644 security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/UserRepository.java create mode 100644 security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/Users.java diff --git a/security-modules/cas/cas-secured-app/pom.xml b/security-modules/cas/cas-secured-app/pom.xml index 6f1ec22cb5..6e1b878354 100644 --- a/security-modules/cas/cas-secured-app/pom.xml +++ b/security-modules/cas/cas-secured-app/pom.xml @@ -36,6 +36,15 @@ spring-boot-devtools runtime + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime + org.springframework.boot spring-boot-starter-test diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java index 62da9cf725..9293a3e00f 100644 --- a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java @@ -6,6 +6,7 @@ import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; import org.jasig.cas.client.validation.TicketValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @@ -34,6 +35,7 @@ public class CasSecuredApplication { SpringApplication.run(CasSecuredApplication.class, args); } + @Bean public CasAuthenticationFilter casAuthenticationFilter( AuthenticationManager authenticationManager, @@ -58,6 +60,10 @@ public class CasSecuredApplication { return new Cas30ServiceTicketValidator("https://localhost:8443/cas"); } + @Bean + public MyUserDetailsService getUser(){ + return new MyUserDetailsService(); + } @Bean public CasAuthenticationProvider casAuthenticationProvider( TicketValidator ticketValidator, @@ -65,9 +71,10 @@ public class CasSecuredApplication { CasAuthenticationProvider provider = new CasAuthenticationProvider(); provider.setServiceProperties(serviceProperties); provider.setTicketValidator(ticketValidator); - provider.setUserDetailsService( + /* provider.setUserDetailsService( s -> new User("casuser", "Mellon", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); + AuthorityUtils.createAuthorityList("ROLE_ADMIN")));*/ + provider.setUserDetailsService(getUser()); provider.setKey("CAS_PROVIDER_LOCALHOST_8900"); return provider; } diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/MyUserDetailsService.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/MyUserDetailsService.java new file mode 100644 index 0000000000..35c83bfd75 --- /dev/null +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/MyUserDetailsService.java @@ -0,0 +1,34 @@ +package com.baeldung.cassecuredapp; + +import java.util.Collections; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; + +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + // Get the user from the database. + Users users = getUserFromDatabase(username); + + // Create a UserDetails object. + UserDetails userDetails = new User( + users.getEmail(), + users.getPassword(), + Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"))); + + return userDetails; + } + + private Users getUserFromDatabase(String username) { + return userRepository.findByEmail(username); + } +} diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/UserRepository.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/UserRepository.java new file mode 100644 index 0000000000..366329a3fb --- /dev/null +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/UserRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.cassecuredapp; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends CrudRepository { + + Users findByEmail(@Param("email") String email); + +} diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/Users.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/Users.java new file mode 100644 index 0000000000..4e775e80e3 --- /dev/null +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/Users.java @@ -0,0 +1,41 @@ +package com.baeldung.cassecuredapp; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Users { + @Id + private Long id; + + @Column(nullable = false, unique = true) + private String email; + + private String password; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/security-modules/cas/cas-secured-app/src/main/resources/application.properties b/security-modules/cas/cas-secured-app/src/main/resources/application.properties index f8789997d5..fa13527982 100644 --- a/security-modules/cas/cas-secured-app/src/main/resources/application.properties +++ b/security-modules/cas/cas-secured-app/src/main/resources/application.properties @@ -1,2 +1,8 @@ server.port=8900 -spring.freemarker.suffix=.ftl \ No newline at end of file +spring.freemarker.suffix=.ftl + +spring.jpa.generate-ddl=false +spring.datasource.url= jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC +spring.datasource.username=root +spring.datasource.password=root1234 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver \ No newline at end of file From 307d0f5e409b29c6bced2310206ba093b34769e7 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Tue, 10 Oct 2023 22:39:14 -0400 Subject: [PATCH 005/233] Message Ordering - First Draft. --- apache-kafka-2/pom.xml | 5 ++ .../ordering/ConsumerConfigurations.java | 32 ++++++++++++ .../ExtSeqWithTimeWindowConsumer.java | 49 +++++++++++++++++++ .../ExtSeqWithTimeWindowProducer.java | 29 +++++++++++ .../ordering/MultiPartitionConsumer.java | 34 +++++++++++++ .../ordering/MultiPartitionProducer.java | 27 ++++++++++ .../ordering/ProducerConfigurations.java | 27 ++++++++++ .../ordering/SinglePartitionConsumer.java | 35 +++++++++++++ .../ordering/SinglePartitionProducer.java | 29 +++++++++++ .../message/ordering/payload/Message.java | 36 ++++++++++++++ .../serialization/JacksonDeserializer.java | 36 ++++++++++++++ .../serialization/JacksonSerializer.java | 20 ++++++++ 12 files changed, 359 insertions(+) create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java diff --git a/apache-kafka-2/pom.xml b/apache-kafka-2/pom.xml index 067dedef8a..45b31004b7 100644 --- a/apache-kafka-2/pom.xml +++ b/apache-kafka-2/pom.xml @@ -57,6 +57,11 @@ ${lombok.version} provided + + com.fasterxml.jackson.core + jackson-databind + 2.15.2 + diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java new file mode 100644 index 0000000000..b18db3ef24 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java @@ -0,0 +1,32 @@ +package com.baeldung.kafka.message.ordering; + +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; + +import java.time.Duration; +import java.util.Collections; +import java.util.Properties; + +public class ConsumerConfigurations { + public static void main(String[] args) { + Properties props = new Properties(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + props.put("max.poll.records", "500"); + props.put("fetch.min.bytes", "1"); + props.put("fetch.max.wait.ms", "500"); + Consumer consumer = new KafkaConsumer<>(props); + consumer.subscribe(Collections.singletonList("multi_partition_topic")); + + while (true) { + ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); + records.forEach(record -> { + System.out.println("Partition: " + record.partition() + ", Message: " + record.value()); + }); + } + } +} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java new file mode 100644 index 0000000000..5b01a86e39 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java @@ -0,0 +1,49 @@ +package com.baeldung.kafka.message.ordering; + +import com.baeldung.kafka.message.ordering.payload.Message; +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; + +import java.time.Duration; +import java.util.*; + +public class ExtSeqWithTimeWindowConsumer { + private static final long BUFFER_PERIOD_MS = 5000; + private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(100); + + public static void main(String[] args) { + Properties props = new Properties(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + props.put("value.deserializer.serializedClass", Message.class); + Consumer consumer = new KafkaConsumer<>(props); + consumer.subscribe(Collections.singletonList("multi_partition_topic")); + List buffer = new ArrayList<>(); + long lastProcessedTime = System.nanoTime(); + while (true) { + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + records.forEach(record -> { + if (record != null && record.value() != null) { + buffer.add(record.value()); + } + }); + if (System.nanoTime() - lastProcessedTime > BUFFER_PERIOD_MS) { + processBuffer(buffer); + lastProcessedTime = System.nanoTime(); + } + } + } + + private static void processBuffer(List buffer) { + Collections.sort(buffer); + buffer.forEach(message -> { + System.out.println("Processing message with Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + }); + buffer.clear(); + } +} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java new file mode 100644 index 0000000000..91c5af716f --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -0,0 +1,29 @@ +package com.baeldung.kafka.message.ordering; + +import com.baeldung.kafka.message.ordering.payload.Message; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerRecord; + +import java.util.Properties; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class ExtSeqWithTimeWindowProducer { + public static void main(String[] args) { + Properties props = new Properties(); + props.put("bootstrap.servers", "localhost:9092"); + props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + + KafkaProducer producer = new KafkaProducer<>(props); + for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { + long messageId = Message.getRandomMessageId(); + String key = "Key-" + insertPosition; + Message message = new Message(insertPosition, messageId); + producer.send(new ProducerRecord<>("multi_partition_topic", key, message)); + System.out.println("Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + } + producer.close(); + System.out.println("ExternalSequencingProducer Completed."); + } +} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java new file mode 100644 index 0000000000..f9b0b3b040 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java @@ -0,0 +1,34 @@ +package com.baeldung.kafka.message.ordering; + +import com.baeldung.kafka.message.ordering.payload.Message; +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; + +import java.time.Duration; +import java.util.Collections; +import java.util.Properties; + +public class MultiPartitionConsumer { + private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(100); + public static void main(String[] args) { + Properties props = new Properties(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + props.put("value.deserializer.serializedClass", Message.class); + Consumer consumer = new KafkaConsumer<>(props); + consumer.subscribe(Collections.singletonList("multi_partition_topic")); + while (true) { + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + records.forEach(record -> { + Message message = record.value(); + System.out.println("Process message with Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + }); + } + } +} + diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java new file mode 100644 index 0000000000..8b2a49b2b5 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java @@ -0,0 +1,27 @@ +package com.baeldung.kafka.message.ordering; + +import com.baeldung.kafka.message.ordering.payload.Message; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerRecord; + +import java.util.Properties; + +public class MultiPartitionProducer { + public static void main(String[] args) { + Properties props = new Properties(); + props.put("bootstrap.servers", "localhost:9092"); + props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + + KafkaProducer producer = new KafkaProducer<>(props); + for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { + long messageId = Message.getRandomMessageId(); + String key = "Key-" + insertPosition; + Message message = new Message(insertPosition, messageId); + producer.send(new ProducerRecord<>("multi_partition_topic", key, message)); + System.out.println("Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + } + producer.close(); + System.out.println("SinglePartitionProducer Completed."); + } +} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java new file mode 100644 index 0000000000..bcdf6ceb32 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -0,0 +1,27 @@ +package com.baeldung.kafka.message.ordering; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerRecord; + +import java.util.Properties; + +public class ProducerConfigurations { + public static void main(String[] args) { + Properties props = new Properties(); + props.put("bootstrap.servers", "localhost:9092"); + props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put("max.in.flight.requests.per.connection", "1"); + props.put("batch.size", "16384"); + props.put("linger.ms", "5"); + KafkaProducer producer = new KafkaProducer<>(props); + + for (int i = 0; i < 10; i++) { + String key = "Key-" + (i % 3); // Assuming 3 partitions + producer.send(new ProducerRecord<>("multi_partition_topic", key, "Message-" + i)); + } + + producer.close(); + System.out.println("MultiPartitionProducer Completed."); + } +} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java new file mode 100644 index 0000000000..932a29c394 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java @@ -0,0 +1,35 @@ +package com.baeldung.kafka.message.ordering; + +import com.baeldung.kafka.message.ordering.payload.Message; +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; + +import java.time.Duration; +import java.util.Collections; +import java.util.Properties; + +public class SinglePartitionConsumer { + private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(100); + + public static void main(String[] args) { + Properties props = new Properties(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + props.put("value.deserializer.serializedClass", Message.class); + Consumer consumer = new KafkaConsumer<>(props); + consumer.subscribe(Collections.singletonList("single_partition_topic")); + while (true) { + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + records.forEach(record -> { + Message message = record.value(); + System.out.println("Process message with Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + }); + } + } +} + diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java new file mode 100644 index 0000000000..b5366819c5 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java @@ -0,0 +1,29 @@ +package com.baeldung.kafka.message.ordering; + +import com.baeldung.kafka.message.ordering.payload.Message; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerRecord; + +import java.util.Properties; +import java.util.Random; + +public class SinglePartitionProducer { + public static void main(String[] args) { + Properties props = new Properties(); + props.put("bootstrap.servers", "localhost:9092"); + props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + + KafkaProducer producer = new KafkaProducer<>(props); + for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { + long messageId = Message.getRandomMessageId(); + String key = "Key-" + insertPosition; + Message message = new Message(insertPosition, messageId); + producer.send(new ProducerRecord<>("single_partition_topic", key, message)); + System.out.println("Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + } + producer.close(); + System.out.println("SinglePartitionProducer Completed."); + } + +} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java new file mode 100644 index 0000000000..b185d663d4 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java @@ -0,0 +1,36 @@ +package com.baeldung.kafka.message.ordering.payload; + +import java.util.Random; + +public class Message implements Comparable { + private long insertPosition; + private long messageId; + + public Message(){ + + } + + public Message(long insertPosition, long messageId) { + this.insertPosition = insertPosition; + this.messageId = messageId; + } + + public long getInsertPosition() { + return insertPosition; + } + + public long getMessageId() { + return messageId; + } + + @Override + public int compareTo(Message other) { + return Long.compare(this.messageId, other.messageId); + } + + public static long getRandomMessageId() { + Random rand = new Random(); + return rand.nextInt(1000); + } +} + diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java new file mode 100644 index 0000000000..34aa181fcb --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java @@ -0,0 +1,36 @@ +package com.baeldung.kafka.message.ordering.serialization; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.kafka.common.serialization.Deserializer; + +import java.util.Map; + +public class JacksonDeserializer implements Deserializer { + private final ObjectMapper objectMapper = new ObjectMapper(); + private Class tClass; + + public JacksonDeserializer(Class tClass) { + this.tClass = tClass; + } + + public JacksonDeserializer() { + + } + + @Override + public void configure(Map configs, boolean isKey) { + this.tClass = (Class) configs.get("value.deserializer.serializedClass"); + } + + @Override + public T deserialize(String topic, byte[] bytes) { + if (bytes == null) { + return null; + } + try { + return objectMapper.readValue(bytes, tClass); + } catch (Exception e) { + throw new RuntimeException("Error deserializing value", e); + } + } +} + diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java new file mode 100644 index 0000000000..fa9d25dd85 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java @@ -0,0 +1,20 @@ +package com.baeldung.kafka.message.ordering.serialization; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.kafka.common.serialization.Serializer; + +public class JacksonSerializer implements Serializer { + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public byte[] serialize(String topic, T data) { + if (data == null) { + return null; + } + try { + return objectMapper.writeValueAsBytes(data); + } catch (Exception e) { + throw new RuntimeException("Error serializing value", e); + } + } +} From 23124ab6f81536cb1a7e242d9caad1aead3fdf14 Mon Sep 17 00:00:00 2001 From: Vinay Mhatre <90505086+SamsterZero@users.noreply.github.com> Date: Wed, 11 Oct 2023 18:26:22 +0530 Subject: [PATCH 006/233] To change default redirect Previously after logging in we used to get the desired index page, but the address bar still had the "/login" in the address bar, this code fixes that --- .../com/baeldung/customuserdetails/SecurityConfiguration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/customuserdetails/SecurityConfiguration.java b/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/customuserdetails/SecurityConfiguration.java index cfec910ce9..d438aefcdc 100644 --- a/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/customuserdetails/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/customuserdetails/SecurityConfiguration.java @@ -28,7 +28,7 @@ public class SecurityConfiguration { .formLogin() .loginPage("/login") .permitAll() - .successForwardUrl("/index") + .defaultSuccessUrl("/index") .and() .logout() .permitAll() From 8772eaa67351c29e44db9c391225bb9602af2469 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 15:28:15 -0400 Subject: [PATCH 007/233] Single and Multiple Partition test. --- apache-kafka-2/pom.xml | 3 +- .../message/ordering/payload/Message.java | 14 +++ .../ordering/MultiplePartitionTest.java | 114 +++++++++++++++++ .../message/ordering/SinglePartitionTest.java | 115 ++++++++++++++++++ 4 files changed, 245 insertions(+), 1 deletion(-) create mode 100644 apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java create mode 100644 apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java diff --git a/apache-kafka-2/pom.xml b/apache-kafka-2/pom.xml index 45b31004b7..d0838a386e 100644 --- a/apache-kafka-2/pom.xml +++ b/apache-kafka-2/pom.xml @@ -60,7 +60,7 @@ com.fasterxml.jackson.core jackson-databind - 2.15.2 + ${jackson.databind.version} @@ -69,6 +69,7 @@ 2.8.0 1.15.3 1.15.3 + 2.15.2 \ No newline at end of file diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java index b185d663d4..317aec699e 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java @@ -1,5 +1,6 @@ package com.baeldung.kafka.message.ordering.payload; +import javax.swing.*; import java.util.Random; public class Message implements Comparable { @@ -10,6 +11,7 @@ public class Message implements Comparable { } + //Required for Kafka Serialization and Deserialization public Message(long insertPosition, long messageId) { this.insertPosition = insertPosition; this.messageId = messageId; @@ -28,6 +30,18 @@ public class Message implements Comparable { return Long.compare(this.messageId, other.messageId); } + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof Message)) { + return false; + } + Message message = (Message) obj; + return this.messageId == message.getMessageId() && this.insertPosition == message.getInsertPosition(); + } + public static long getRandomMessageId() { Random rand = new Random(); return rand.nextInt(1000); diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java new file mode 100644 index 0000000000..586c328f79 --- /dev/null +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java @@ -0,0 +1,114 @@ +package com.baeldung.kafka.message.ordering; + +import com.baeldung.kafka.message.ordering.payload.Message; +import lombok.var; +import org.apache.kafka.clients.admin.*; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; +import org.apache.kafka.common.KafkaFuture; +import org.apache.kafka.common.PartitionInfo; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.KafkaContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; +import java.time.Duration; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import static org.junit.jupiter.api.Assertions.*; + +@Testcontainers +public class MultiplePartitionTest { + private static String TOPIC = "multi_partition_topic"; + private static int PARTITIONS = 5; + private static short REPLICATION_FACTOR = 1; + private static Admin admin; + private static KafkaProducer producer; + private static KafkaConsumer consumer; + private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); + @Container + private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + + @BeforeAll + static void setup() throws ExecutionException, InterruptedException { + KAFKA_CONTAINER.addExposedPort(9092); + + Properties adminProperties = new Properties(); + adminProperties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + + Properties producerProperties = new Properties(); + producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + producerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + producerProperties.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + + Properties consumerProperties = new Properties(); + consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + consumerProperties.put("value.deserializer.serializedClass", Message.class); + consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); + admin = Admin.create(adminProperties); + producer = new KafkaProducer<>(producerProperties); + consumer = new KafkaConsumer<>(consumerProperties); + List topicList = new ArrayList<>(); + NewTopic newTopic = new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR); + topicList.add(newTopic); + CreateTopicsResult result = admin.createTopics(topicList); + KafkaFuture future = result.values().get(TOPIC); + future.whenComplete((voidResult, exception) -> { + if (exception != null) { + System.err.println("Error creating the topic: " + exception.getMessage()); + } else { + System.out.println("Topic created successfully!"); + } + }).get(); + } + + @AfterAll + static void destroy() { + KAFKA_CONTAINER.stop(); + } + + @Test + void givenMultiplePartitions_whenPublishedToKafkaAndConsumed_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { + List sentMessageList = new ArrayList<>(); + List receivedMessageList = new ArrayList<>(); + for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { + long messageId = Message.getRandomMessageId(); + String key = "Key-" + insertPosition; + Message message = new Message(insertPosition, messageId); + Future future = producer.send(new ProducerRecord<>(TOPIC, key, message)); + sentMessageList.add(message); + RecordMetadata metadata = future.get(); + System.out.println("Partition : " + metadata.partition()); + } + + boolean isOrderMaintained = true; + consumer.subscribe(Collections.singletonList(TOPIC)); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + records.forEach(record -> { + Message message = record.value(); + receivedMessageList.add(message); + }); + for (int insertPosition = 0; insertPosition <= receivedMessageList.size() - 1; insertPosition++) { + if (isOrderMaintained){ + Message sentMessage = sentMessageList.get(insertPosition); + Message receivedMessage = receivedMessageList.get(insertPosition); + if (!sentMessage.equals(receivedMessage)) { + isOrderMaintained = false; + } + } + } + assertFalse(isOrderMaintained); + } +} diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java new file mode 100644 index 0000000000..afffbcc28e --- /dev/null +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java @@ -0,0 +1,115 @@ +package com.baeldung.kafka.message.ordering; + +import com.baeldung.kafka.message.ordering.payload.Message; +import org.apache.kafka.clients.admin.Admin; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.CreateTopicsResult; +import org.apache.kafka.clients.admin.NewTopic; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; +import org.apache.kafka.common.KafkaFuture; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.KafkaContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; +import java.time.Duration; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Testcontainers +public class SinglePartitionTest { + private static String TOPIC = "single_partition_topic"; + private static int PARTITIONS = 1; + private static short REPLICATION_FACTOR = 1; + private static Admin admin; + private static KafkaProducer producer; + private static KafkaConsumer consumer; + + private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); + + @Container + private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + + @BeforeAll + static void setup() throws ExecutionException, InterruptedException { + KAFKA_CONTAINER.addExposedPort(9092); + + Properties adminProperties = new Properties(); + adminProperties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + + Properties producerProperties = new Properties(); + producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + producerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + producerProperties.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + + Properties consumerProperties = new Properties(); + consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + consumerProperties.put("value.deserializer.serializedClass", Message.class); + consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); + admin = Admin.create(adminProperties); + producer = new KafkaProducer<>(producerProperties); + consumer = new KafkaConsumer<>(consumerProperties); + List topicList = new ArrayList<>(); + NewTopic newTopic = new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR); + topicList.add(newTopic); + CreateTopicsResult result = admin.createTopics(topicList); + KafkaFuture future = result.values().get(TOPIC); + future.whenComplete((voidResult, exception) -> { + if (exception != null) { + System.err.println("Error creating the topic: " + exception.getMessage()); + } else { + System.out.println("Topic created successfully!"); + } + }).get(); + } + + @AfterAll + static void destroy() { + KAFKA_CONTAINER.stop(); + } + + @Test + void givenASinglePartition_whenPublishedToKafkaAndConsumed_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { + List sentMessageList = new ArrayList<>(); + List receivedMessageList = new ArrayList<>(); + for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { + long messageId = Message.getRandomMessageId(); + String key = "Key-" + insertPosition; + Message message = new Message(insertPosition, messageId); + ProducerRecord producerRecord = new ProducerRecord<>(TOPIC, key, message); + Future future = producer.send(producerRecord); + sentMessageList.add(message); + RecordMetadata metadata = future.get(); + System.out.println("Partition : " + metadata.partition()); + } + + consumer.subscribe(Collections.singletonList(TOPIC)); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + records.forEach(record -> { + Message message = record.value(); + receivedMessageList.add(message); + }); + boolean result = true; + for (int count = 0; count <= 9 ; count++) { + Message sentMessage = sentMessageList.get(count); + Message receivedMessage = receivedMessageList.get(count); + if (!sentMessage.equals(receivedMessage) && result){ + result = false; + } + } + assertTrue(result); + } +} From c4aac70277435d53363e2e99f8a26de8d2729585 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 15:46:35 -0400 Subject: [PATCH 008/233] User Constants instead od repeatative strings --- .../baeldung/kafka/message/ordering/Config.java | 5 +++++ .../message/ordering/MultiplePartitionTest.java | 14 +++++++++----- .../message/ordering/SinglePartitionTest.java | 14 +++++++++----- 3 files changed, 23 insertions(+), 10 deletions(-) create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java new file mode 100644 index 0000000000..2635e72431 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java @@ -0,0 +1,5 @@ +package com.baeldung.kafka.message.ordering; + +public class Config { + public static final String CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS = "value.deserializer.serializedClass"; +} diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java index 586c328f79..5b68544f95 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java @@ -1,6 +1,8 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; +import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import lombok.var; import org.apache.kafka.clients.admin.*; import org.apache.kafka.clients.consumer.ConsumerConfig; @@ -12,6 +14,8 @@ import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.KafkaFuture; import org.apache.kafka.common.PartitionInfo; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -47,15 +51,15 @@ public class MultiplePartitionTest { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); - producerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - producerProperties.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); Properties consumerProperties = new Properties(); consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); - consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); - consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - consumerProperties.put("value.deserializer.serializedClass", Message.class); + consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java index afffbcc28e..807e21bfa8 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java @@ -1,6 +1,8 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; +import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.admin.Admin; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.CreateTopicsResult; @@ -13,6 +15,8 @@ import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.KafkaFuture; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -49,15 +53,15 @@ public class SinglePartitionTest { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); - producerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - producerProperties.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); Properties consumerProperties = new Properties(); consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); - consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); - consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - consumerProperties.put("value.deserializer.serializedClass", Message.class); + consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); From 1d1aaeedb6eea4201a8a92eade16f2ec62ef588c Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 15:57:42 -0400 Subject: [PATCH 009/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/ProducerConfigurations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index bcdf6ceb32..60ae5fc2f8 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -13,7 +13,7 @@ public class ProducerConfigurations { props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("max.in.flight.requests.per.connection", "1"); props.put("batch.size", "16384"); - props.put("linger.ms", "5"); + props.put(ProducerConfig.LINGER_MS_CONFIG, "5"); KafkaProducer producer = new KafkaProducer<>(props); for (int i = 0; i < 10; i++) { From f8ea1db5ccd727c2e06912a04eac3b9de4088341 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 15:58:27 -0400 Subject: [PATCH 010/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/ProducerConfigurations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index 60ae5fc2f8..566605973c 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -12,7 +12,7 @@ public class ProducerConfigurations { props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("max.in.flight.requests.per.connection", "1"); - props.put("batch.size", "16384"); + props.put(ProducerConfig.BATCH_SIZE_CONFIG, "16384"); props.put(ProducerConfig.LINGER_MS_CONFIG, "5"); KafkaProducer producer = new KafkaProducer<>(props); From 463e45d025682fbd4eecbb73165c460ef9f7ea03 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 15:58:33 -0400 Subject: [PATCH 011/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/ProducerConfigurations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index 566605973c..c9cef04bbc 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -11,7 +11,7 @@ public class ProducerConfigurations { props.put("bootstrap.servers", "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - props.put("max.in.flight.requests.per.connection", "1"); + props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1"); props.put(ProducerConfig.BATCH_SIZE_CONFIG, "16384"); props.put(ProducerConfig.LINGER_MS_CONFIG, "5"); KafkaProducer producer = new KafkaProducer<>(props); From 836c977fdea79eda47f2e5989709d73f40e5f593 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 15:58:43 -0400 Subject: [PATCH 012/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/ProducerConfigurations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index c9cef04bbc..81d91693fe 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -8,7 +8,7 @@ import java.util.Properties; public class ProducerConfigurations { public static void main(String[] args) { Properties props = new Properties(); - props.put("bootstrap.servers", "localhost:9092"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1"); From 540da8c7795ac450793347b927e6c6a800c06c25 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 15:58:57 -0400 Subject: [PATCH 013/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java Co-authored-by: Liam Williams --- .../message/ordering/serialization/JacksonSerializer.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java index fa9d25dd85..2d7432cc7b 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java @@ -3,6 +3,10 @@ package com.baeldung.kafka.message.ordering.serialization; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.kafka.common.serialization.Serializer; +/** + * Configured via {@link org.apache.kafka.clients.producer.ProducerConfig#VALUE_SERIALIZER_CLASS_CONFIG} + */ +@SuppressWarnings("unused") public class JacksonSerializer implements Serializer { private final ObjectMapper objectMapper = new ObjectMapper(); From c3af2facae6cdc5b3a27607eec2d079f1a670d9f Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 15:59:07 -0400 Subject: [PATCH 014/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java Co-authored-by: Liam Williams --- .../message/ordering/serialization/JacksonDeserializer.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java index 34aa181fcb..f3c8aaf60f 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java @@ -4,6 +4,10 @@ import org.apache.kafka.common.serialization.Deserializer; import java.util.Map; +/** + * Configured via {@link org.apache.kafka.clients.consumer.ConsumerConfig#VALUE_DESERIALIZER_CLASS_CONFIG} + */ +@SuppressWarnings("unused") public class JacksonDeserializer implements Deserializer { private final ObjectMapper objectMapper = new ObjectMapper(); private Class tClass; From d31cf69b4d5d2ca8d88cbebf6aee72b84dba96b3 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 15:59:38 -0400 Subject: [PATCH 015/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/MultiPartitionProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java index 8b2a49b2b5..0fd20c2ab1 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java @@ -11,7 +11,7 @@ public class MultiPartitionProducer { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - props.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); KafkaProducer producer = new KafkaProducer<>(props); for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { From 857da48e742306babf0579436aa2baf0c3ea5a0c Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:00:04 -0400 Subject: [PATCH 016/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/ProducerConfigurations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index 81d91693fe..ae3f2839c8 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -10,7 +10,7 @@ public class ProducerConfigurations { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1"); props.put(ProducerConfig.BATCH_SIZE_CONFIG, "16384"); props.put(ProducerConfig.LINGER_MS_CONFIG, "5"); From e35327cade00d1be3bedc513e416dc9de28f177a Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:00:49 -0400 Subject: [PATCH 017/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/MultiPartitionProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java index 0fd20c2ab1..04ffdd3336 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java @@ -10,7 +10,7 @@ public class MultiPartitionProducer { public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); - props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); KafkaProducer producer = new KafkaProducer<>(props); From 2dd76f7e78bad11206916195f15a81c0f79f9aad Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:01:50 -0400 Subject: [PATCH 018/233] Review comment incorporation --- .../kafka/message/ordering/ProducerConfigurations.java | 1 + .../kafka/message/ordering/payload/Message.java | 3 ++- .../ordering/serialization/JacksonDeserializer.java | 10 +++++----- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index 60ae5fc2f8..2c885b7caa 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -1,6 +1,7 @@ package com.baeldung.kafka.message.ordering; import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import java.util.Properties; diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java index 317aec699e..095aeef89a 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java @@ -2,6 +2,7 @@ package com.baeldung.kafka.message.ordering.payload; import javax.swing.*; import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; public class Message implements Comparable { private long insertPosition; @@ -44,7 +45,7 @@ public class Message implements Comparable { public static long getRandomMessageId() { Random rand = new Random(); - return rand.nextInt(1000); + return ThreadLocalRandom.current().nextInt(1000); } } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java index 34aa181fcb..cb0b77e4c0 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java @@ -6,10 +6,10 @@ import java.util.Map; public class JacksonDeserializer implements Deserializer { private final ObjectMapper objectMapper = new ObjectMapper(); - private Class tClass; + private Class type; - public JacksonDeserializer(Class tClass) { - this.tClass = tClass; + public JacksonDeserializer(Class type) { + this.type = type; } public JacksonDeserializer() { @@ -18,7 +18,7 @@ public class JacksonDeserializer implements Deserializer { @Override public void configure(Map configs, boolean isKey) { - this.tClass = (Class) configs.get("value.deserializer.serializedClass"); + this.type = (Class) configs.get("value.deserializer.serializedClass"); } @Override @@ -27,7 +27,7 @@ public class JacksonDeserializer implements Deserializer { return null; } try { - return objectMapper.readValue(bytes, tClass); + return objectMapper.readValue(bytes, type); } catch (Exception e) { throw new RuntimeException("Error deserializing value", e); } From 51cf5cee5fe1ec871163291a4e97071c024dcb1d Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:02:15 -0400 Subject: [PATCH 019/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/MultiPartitionProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java index 04ffdd3336..b565941fa5 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java @@ -9,7 +9,7 @@ import java.util.Properties; public class MultiPartitionProducer { public static void main(String[] args) { Properties props = new Properties(); - props.put("bootstrap.servers", "localhost:9092"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); From 9eed20e483f00dde53393c3d0ae541a107a7696c Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:03:11 -0400 Subject: [PATCH 020/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java Co-authored-by: Liam Williams --- .../kafka/message/ordering/ExtSeqWithTimeWindowProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java index 91c5af716f..59bfb397ec 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -13,7 +13,7 @@ public class ExtSeqWithTimeWindowProducer { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - props.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); KafkaProducer producer = new KafkaProducer<>(props); for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { From 6da6a92a797d02ac0086c6591d949a58fc148f3b Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:03:28 -0400 Subject: [PATCH 021/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java Co-authored-by: Liam Williams --- .../kafka/message/ordering/ExtSeqWithTimeWindowProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java index 59bfb397ec..b4b890ffe7 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -12,7 +12,7 @@ public class ExtSeqWithTimeWindowProducer { public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); - props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); KafkaProducer producer = new KafkaProducer<>(props); From 576b08076f59695d7286afcdf25145630de2ab1a Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:03:53 -0400 Subject: [PATCH 022/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java Co-authored-by: Liam Williams --- .../kafka/message/ordering/ExtSeqWithTimeWindowProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java index b4b890ffe7..69f50352ad 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -11,7 +11,7 @@ import java.util.concurrent.atomic.AtomicLong; public class ExtSeqWithTimeWindowProducer { public static void main(String[] args) { Properties props = new Properties(); - props.put("bootstrap.servers", "localhost:9092"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092") props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); From 3c716605b90ddf32311a5459aacab1cf41a55566 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:04:07 -0400 Subject: [PATCH 023/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java Co-authored-by: Liam Williams --- .../kafka/message/ordering/SinglePartitionProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java index b5366819c5..1610df746c 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java @@ -10,7 +10,7 @@ import java.util.Random; public class SinglePartitionProducer { public static void main(String[] args) { Properties props = new Properties(); - props.put("bootstrap.servers", "localhost:9092"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092") props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); From d408db30f209eda244bb505055b09935822e4ad9 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:05:27 -0400 Subject: [PATCH 024/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java Co-authored-by: Liam Williams --- .../kafka/message/ordering/SinglePartitionProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java index 1610df746c..03f89b9a55 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java @@ -12,7 +12,7 @@ public class SinglePartitionProducer { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092") props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - props.put("value.serializer", "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); KafkaProducer producer = new KafkaProducer<>(props); for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { From f2a69a8bb11a482237230c7261bcebdb1c87af97 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:07:42 -0400 Subject: [PATCH 025/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/ConsumerConfigurations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java index b18db3ef24..8af4e576ce 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java @@ -18,7 +18,7 @@ public class ConsumerConfigurations { props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put("max.poll.records", "500"); props.put("fetch.min.bytes", "1"); - props.put("fetch.max.wait.ms", "500"); + props.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, "500"); Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("multi_partition_topic")); From 89eed31dbd38d7bcc784dfbe99ea13bf1e136788 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:08:05 -0400 Subject: [PATCH 026/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/ConsumerConfigurations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java index 8af4e576ce..9f3d8b9d5c 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java @@ -17,7 +17,7 @@ public class ConsumerConfigurations { props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put("max.poll.records", "500"); - props.put("fetch.min.bytes", "1"); + props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, "1"); props.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, "500"); Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("multi_partition_topic")); From d850d6c30cbad40b5245b58f06ac0173ecfb3546 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:08:27 -0400 Subject: [PATCH 027/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/ProducerConfigurations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index 5dc917e308..af06fa04de 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -10,7 +10,7 @@ public class ProducerConfigurations { public static void main(String[] args) { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1"); props.put(ProducerConfig.BATCH_SIZE_CONFIG, "16384"); From d85a01e524432d27f146d89609d6935d81aef091 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:08:54 -0400 Subject: [PATCH 028/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java Co-authored-by: Liam Williams --- .../kafka/message/ordering/SinglePartitionProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java index 03f89b9a55..869a260da6 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java @@ -11,7 +11,7 @@ public class SinglePartitionProducer { public static void main(String[] args) { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092") - props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); KafkaProducer producer = new KafkaProducer<>(props); From 29096686cc7de507162dc4c468a574ce5932a538 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:09:36 -0400 Subject: [PATCH 029/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/ConsumerConfigurations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java index 9f3d8b9d5c..b3faceaa44 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java @@ -16,7 +16,7 @@ public class ConsumerConfigurations { props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); - props.put("max.poll.records", "500"); + props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "500"); props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, "1"); props.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, "500"); Consumer consumer = new KafkaConsumer<>(props); From b94d5a1f8a8e2ce146b1d60d96f3ad3319c2976e Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 16:36:33 -0400 Subject: [PATCH 030/233] Incorporated Review Comments --- .../message/ordering/ConsumerConfigurations.java | 8 ++++++-- .../ordering/ExtSeqWithTimeWindowConsumer.java | 12 ++++++------ .../ordering/ExtSeqWithTimeWindowProducer.java | 9 ++++++--- .../message/ordering/MultiPartitionConsumer.java | 12 ++++++++---- .../message/ordering/MultiPartitionProducer.java | 7 +++++-- .../message/ordering/ProducerConfigurations.java | 5 +++-- .../message/ordering/SinglePartitionConsumer.java | 9 ++++++--- .../message/ordering/SinglePartitionProducer.java | 9 ++++++--- .../ordering/serialization/JacksonDeserializer.java | 6 ++++-- 9 files changed, 50 insertions(+), 27 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java index b3faceaa44..15562cfcef 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java @@ -1,9 +1,13 @@ package com.baeldung.kafka.message.ordering; +import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; import java.time.Duration; import java.util.Collections; @@ -14,8 +18,8 @@ public class ConsumerConfigurations { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "500"); props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, "1"); props.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, "500"); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java index 5b01a86e39..f5a0dbd640 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java @@ -1,10 +1,12 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; import java.util.*; @@ -17,10 +19,10 @@ public class ExtSeqWithTimeWindowConsumer { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put("value.deserializer.serializedClass", Message.class); + props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("multi_partition_topic")); List buffer = new ArrayList<>(); @@ -28,9 +30,7 @@ public class ExtSeqWithTimeWindowConsumer { while (true) { ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { - if (record != null && record.value() != null) { - buffer.add(record.value()); - } + buffer.add(record.value()); }); if (System.nanoTime() - lastProcessedTime > BUFFER_PERIOD_MS) { processBuffer(buffer); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java index 69f50352ad..110015de25 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -1,8 +1,11 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.serialization.StringSerializer; import java.util.Properties; import java.util.Random; @@ -11,9 +14,9 @@ import java.util.concurrent.atomic.AtomicLong; public class ExtSeqWithTimeWindowProducer { public static void main(String[] args) { Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092") - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); KafkaProducer producer = new KafkaProducer<>(props); for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java index f9b0b3b040..542a664745 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java @@ -1,10 +1,12 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; import java.util.Collections; @@ -16,17 +18,19 @@ public class MultiPartitionConsumer { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put("value.deserializer.serializedClass", Message.class); + props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("multi_partition_topic")); while (true) { ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { Message message = record.value(); - System.out.println("Process message with Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + if (message != null) { + System.out.println("Process message with Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + } }); } } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java index b565941fa5..bf9db58392 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java @@ -1,8 +1,11 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.serialization.StringSerializer; import java.util.Properties; @@ -10,8 +13,8 @@ public class MultiPartitionProducer { public static void main(String[] args) { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); KafkaProducer producer = new KafkaProducer<>(props); for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index af06fa04de..0eb563910e 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -3,6 +3,7 @@ package com.baeldung.kafka.message.ordering; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.serialization.StringSerializer; import java.util.Properties; @@ -10,8 +11,8 @@ public class ProducerConfigurations { public static void main(String[] args) { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1"); props.put(ProducerConfig.BATCH_SIZE_CONFIG, "16384"); props.put(ProducerConfig.LINGER_MS_CONFIG, "5"); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java index 932a29c394..e1a449055e 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java @@ -1,10 +1,13 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; import java.time.Duration; import java.util.Collections; @@ -17,10 +20,10 @@ public class SinglePartitionConsumer { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put("value.deserializer.serializedClass", Message.class); + props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("single_partition_topic")); while (true) { diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java index 869a260da6..c986089841 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java @@ -1,8 +1,11 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.serialization.StringSerializer; import java.util.Properties; import java.util.Random; @@ -10,9 +13,9 @@ import java.util.Random; public class SinglePartitionProducer { public static void main(String[] args) { Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092") - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.message.ordering.serialization.JacksonSerializer"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); KafkaProducer producer = new KafkaProducer<>(props); for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java index 2def07f987..be2b104761 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java @@ -1,4 +1,5 @@ package com.baeldung.kafka.message.ordering.serialization; +import com.baeldung.kafka.message.ordering.Config; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.kafka.common.serialization.Deserializer; @@ -22,7 +23,7 @@ public class JacksonDeserializer implements Deserializer { @Override public void configure(Map configs, boolean isKey) { - this.type = (Class) configs.get("value.deserializer.serializedClass"); + this.type = (Class) configs.get(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS); } @Override @@ -33,8 +34,9 @@ public class JacksonDeserializer implements Deserializer { try { return objectMapper.readValue(bytes, type); } catch (Exception e) { - throw new RuntimeException("Error deserializing value", e); + //throw new RuntimeException("Error deserializing value", e); } + return null; } } From 6d4e6886b311ffe28794033bc555e80b274fe40b Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 18:42:20 -0400 Subject: [PATCH 031/233] Renamed Inser position to patition key --- .../ordering/ExtSeqWithTimeWindowConsumer.java | 2 +- .../ordering/ExtSeqWithTimeWindowProducer.java | 6 ++---- .../message/ordering/MultiPartitionConsumer.java | 2 +- .../message/ordering/MultiPartitionProducer.java | 4 ++-- .../message/ordering/SinglePartitionConsumer.java | 3 +-- .../message/ordering/SinglePartitionProducer.java | 5 ++--- .../kafka/message/ordering/payload/Message.java | 14 +++++++------- .../message/ordering/MultiplePartitionTest.java | 2 +- .../message/ordering/SinglePartitionTest.java | 2 +- 9 files changed, 18 insertions(+), 22 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java index f5a0dbd640..d342c1a950 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java @@ -42,7 +42,7 @@ public class ExtSeqWithTimeWindowConsumer { private static void processBuffer(List buffer) { Collections.sort(buffer); buffer.forEach(message -> { - System.out.println("Processing message with Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + System.out.println("Processing message with Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); }); buffer.clear(); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java index 110015de25..d1480522e5 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -8,8 +8,6 @@ import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; import java.util.Properties; -import java.util.Random; -import java.util.concurrent.atomic.AtomicLong; public class ExtSeqWithTimeWindowProducer { public static void main(String[] args) { @@ -22,9 +20,9 @@ public class ExtSeqWithTimeWindowProducer { for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { long messageId = Message.getRandomMessageId(); String key = "Key-" + insertPosition; - Message message = new Message(insertPosition, messageId); + Message message = new Message(key, messageId); producer.send(new ProducerRecord<>("multi_partition_topic", key, message)); - System.out.println("Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + System.out.println("Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); } producer.close(); System.out.println("ExternalSequencingProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java index 542a664745..4471070f0f 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java @@ -29,7 +29,7 @@ public class MultiPartitionConsumer { records.forEach(record -> { Message message = record.value(); if (message != null) { - System.out.println("Process message with Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + System.out.println("Process message with Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); } }); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java index bf9db58392..04e3dcce0a 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java @@ -20,9 +20,9 @@ public class MultiPartitionProducer { for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { long messageId = Message.getRandomMessageId(); String key = "Key-" + insertPosition; - Message message = new Message(insertPosition, messageId); + Message message = new Message(key, messageId); producer.send(new ProducerRecord<>("multi_partition_topic", key, message)); - System.out.println("Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + System.out.println("Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); } producer.close(); System.out.println("SinglePartitionProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java index e1a449055e..b47e4ca3b0 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java @@ -7,7 +7,6 @@ import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.StringDeserializer; -import org.apache.kafka.common.serialization.StringSerializer; import java.time.Duration; import java.util.Collections; @@ -30,7 +29,7 @@ public class SinglePartitionConsumer { ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { Message message = record.value(); - System.out.println("Process message with Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + System.out.println("Process message with Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); }); } } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java index c986089841..d669a0fd69 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java @@ -8,7 +8,6 @@ import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; import java.util.Properties; -import java.util.Random; public class SinglePartitionProducer { public static void main(String[] args) { @@ -21,9 +20,9 @@ public class SinglePartitionProducer { for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { long messageId = Message.getRandomMessageId(); String key = "Key-" + insertPosition; - Message message = new Message(insertPosition, messageId); + Message message = new Message(key, messageId); producer.send(new ProducerRecord<>("single_partition_topic", key, message)); - System.out.println("Insert Position: " + message.getInsertPosition() + ", Message Id: " + message.getMessageId()); + System.out.println("Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); } producer.close(); System.out.println("SinglePartitionProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java index 095aeef89a..de1e5135da 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java @@ -1,11 +1,11 @@ package com.baeldung.kafka.message.ordering.payload; -import javax.swing.*; +import java.util.Objects; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class Message implements Comparable { - private long insertPosition; + private String partitionKey; private long messageId; public Message(){ @@ -13,13 +13,13 @@ public class Message implements Comparable { } //Required for Kafka Serialization and Deserialization - public Message(long insertPosition, long messageId) { - this.insertPosition = insertPosition; + public Message(String partitionKey, long messageId) { + this.partitionKey = partitionKey; this.messageId = messageId; } - public long getInsertPosition() { - return insertPosition; + public String getPartitionKey() { + return partitionKey; } public long getMessageId() { @@ -40,7 +40,7 @@ public class Message implements Comparable { return false; } Message message = (Message) obj; - return this.messageId == message.getMessageId() && this.insertPosition == message.getInsertPosition(); + return this.messageId == message.getMessageId() && Objects.equals(this.partitionKey, message.getPartitionKey()); } public static long getRandomMessageId() { diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java index 5b68544f95..aed5f30e9d 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java @@ -90,7 +90,7 @@ public class MultiplePartitionTest { for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { long messageId = Message.getRandomMessageId(); String key = "Key-" + insertPosition; - Message message = new Message(insertPosition, messageId); + Message message = new Message(key, messageId); Future future = producer.send(new ProducerRecord<>(TOPIC, key, message)); sentMessageList.add(message); RecordMetadata metadata = future.get(); diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java index 807e21bfa8..5751c8d0e0 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java @@ -92,7 +92,7 @@ public class SinglePartitionTest { for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { long messageId = Message.getRandomMessageId(); String key = "Key-" + insertPosition; - Message message = new Message(insertPosition, messageId); + Message message = new Message(key, messageId); ProducerRecord producerRecord = new ProducerRecord<>(TOPIC, key, message); Future future = producer.send(producerRecord); sentMessageList.add(message); From d1d456e59a6ba378c84021b26e09f05a134be131 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 19:19:01 -0400 Subject: [PATCH 032/233] Removed insertPosition, renamed messageId to applicationIdentifier --- .../ExtSeqWithTimeWindowConsumer.java | 9 ++++--- .../ExtSeqWithTimeWindowProducer.java | 18 ++++++------- .../ordering/MultiPartitionConsumer.java | 5 ++-- .../ordering/MultiPartitionProducer.java | 18 ++++++------- .../ordering/SinglePartitionConsumer.java | 9 ++++--- .../ordering/SinglePartitionProducer.java | 18 ++++++------- .../message/ordering/payload/Message.java | 20 +++++++-------- .../ordering/MultiplePartitionTest.java | 25 ++++++++----------- .../message/ordering/SinglePartitionTest.java | 23 ++++++++--------- 9 files changed, 69 insertions(+), 76 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java index d342c1a950..19595d9e95 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java @@ -6,20 +6,21 @@ import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.LongDeserializer; import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; import java.util.*; public class ExtSeqWithTimeWindowConsumer { - private static final long BUFFER_PERIOD_MS = 5000; + private static final long BUFFER_PERIOD_NS = 5000L * 1000000; // 5000 milliseconds converted to nanoseconds private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(100); public static void main(String[] args) { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); @@ -32,7 +33,7 @@ public class ExtSeqWithTimeWindowConsumer { records.forEach(record -> { buffer.add(record.value()); }); - if (System.nanoTime() - lastProcessedTime > BUFFER_PERIOD_MS) { + if (System.nanoTime() - lastProcessedTime > BUFFER_PERIOD_NS) { processBuffer(buffer); lastProcessedTime = System.nanoTime(); } @@ -42,7 +43,7 @@ public class ExtSeqWithTimeWindowConsumer { private static void processBuffer(List buffer) { Collections.sort(buffer); buffer.forEach(message -> { - System.out.println("Processing message with Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); + System.out.println("Processing message with Partition key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); }); buffer.clear(); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java index d1480522e5..a20c569159 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -5,7 +5,7 @@ import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; +import org.apache.kafka.common.serialization.LongSerializer; import java.util.Properties; @@ -13,16 +13,14 @@ public class ExtSeqWithTimeWindowProducer { public static void main(String[] args) { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - - KafkaProducer producer = new KafkaProducer<>(props); - for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { - long messageId = Message.getRandomMessageId(); - String key = "Key-" + insertPosition; - Message message = new Message(key, messageId); - producer.send(new ProducerRecord<>("multi_partition_topic", key, message)); - System.out.println("Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); + KafkaProducer producer = new KafkaProducer<>(props); + for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { + long applicationIdentifier = Message.getRandomApplicationIdentifier(); + Message message = new Message(partitionKey, applicationIdentifier); + producer.send(new ProducerRecord<>("multi_partition_topic", partitionKey, message)); + System.out.println("Partition key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); } producer.close(); System.out.println("ExternalSequencingProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java index 4471070f0f..c37c645d31 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java @@ -6,6 +6,7 @@ import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.LongDeserializer; import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; @@ -18,7 +19,7 @@ public class MultiPartitionConsumer { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); @@ -29,7 +30,7 @@ public class MultiPartitionConsumer { records.forEach(record -> { Message message = record.value(); if (message != null) { - System.out.println("Process message with Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); + System.out.println("Process message with Partition key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); } }); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java index 04e3dcce0a..81cc5c6af0 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java @@ -5,7 +5,7 @@ import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; +import org.apache.kafka.common.serialization.LongSerializer; import java.util.Properties; @@ -13,16 +13,14 @@ public class MultiPartitionProducer { public static void main(String[] args) { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - - KafkaProducer producer = new KafkaProducer<>(props); - for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { - long messageId = Message.getRandomMessageId(); - String key = "Key-" + insertPosition; - Message message = new Message(key, messageId); - producer.send(new ProducerRecord<>("multi_partition_topic", key, message)); - System.out.println("Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); + KafkaProducer producer = new KafkaProducer<>(props); + for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { + long applicationIdentifier = Message.getRandomApplicationIdentifier(); + Message message = new Message(partitionKey, applicationIdentifier); + producer.send(new ProducerRecord<>("multi_partition_topic", partitionKey, message)); + System.out.println("Partition Key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); } producer.close(); System.out.println("SinglePartitionProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java index b47e4ca3b0..9f44cd78c6 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java @@ -6,6 +6,7 @@ import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.LongDeserializer; import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; @@ -19,17 +20,17 @@ public class SinglePartitionConsumer { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); - Consumer consumer = new KafkaConsumer<>(props); + Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("single_partition_topic")); while (true) { - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { Message message = record.value(); - System.out.println("Process message with Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); + System.out.println("Process message with Partition Key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); }); } } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java index d669a0fd69..efa6e5b93d 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java @@ -5,7 +5,7 @@ import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; +import org.apache.kafka.common.serialization.LongSerializer; import java.util.Properties; @@ -13,16 +13,14 @@ public class SinglePartitionProducer { public static void main(String[] args) { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - - KafkaProducer producer = new KafkaProducer<>(props); - for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { - long messageId = Message.getRandomMessageId(); - String key = "Key-" + insertPosition; - Message message = new Message(key, messageId); - producer.send(new ProducerRecord<>("single_partition_topic", key, message)); - System.out.println("Insert Position: " + message.getPartitionKey() + ", Message Id: " + message.getMessageId()); + KafkaProducer producer = new KafkaProducer<>(props); + for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { + long applicationIdentifier = Message.getRandomApplicationIdentifier(); + Message message = new Message(partitionKey, applicationIdentifier); + producer.send(new ProducerRecord<>("single_partition_topic", partitionKey, message)); + System.out.println("Partition key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); } producer.close(); System.out.println("SinglePartitionProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java index de1e5135da..734ecba53d 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java @@ -5,30 +5,30 @@ import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class Message implements Comparable { - private String partitionKey; - private long messageId; + private long partitionKey; + private long applicationIdentifier; public Message(){ } //Required for Kafka Serialization and Deserialization - public Message(String partitionKey, long messageId) { + public Message(long partitionKey, long applicationIdentifier) { this.partitionKey = partitionKey; - this.messageId = messageId; + this.applicationIdentifier = applicationIdentifier; } - public String getPartitionKey() { + public long getPartitionKey() { return partitionKey; } - public long getMessageId() { - return messageId; + public long getApplicationIdentifier() { + return applicationIdentifier; } @Override public int compareTo(Message other) { - return Long.compare(this.messageId, other.messageId); + return Long.compare(this.partitionKey, other.partitionKey); } @Override @@ -40,10 +40,10 @@ public class Message implements Comparable { return false; } Message message = (Message) obj; - return this.messageId == message.getMessageId() && Objects.equals(this.partitionKey, message.getPartitionKey()); + return this.applicationIdentifier == message.getApplicationIdentifier() && Objects.equals(this.partitionKey, message.getPartitionKey()); } - public static long getRandomMessageId() { + public static long getRandomApplicationIdentifier() { Random rand = new Random(); return ThreadLocalRandom.current().nextInt(1000); } diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java index aed5f30e9d..ef0a881999 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java @@ -3,7 +3,6 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.Message; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; -import lombok.var; import org.apache.kafka.clients.admin.*; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; @@ -13,9 +12,8 @@ import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.KafkaFuture; -import org.apache.kafka.common.PartitionInfo; -import org.apache.kafka.common.serialization.StringDeserializer; -import org.apache.kafka.common.serialization.StringSerializer; +import org.apache.kafka.common.serialization.LongDeserializer; +import org.apache.kafka.common.serialization.LongSerializer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -36,8 +34,8 @@ public class MultiplePartitionTest { private static int PARTITIONS = 5; private static short REPLICATION_FACTOR = 1; private static Admin admin; - private static KafkaProducer producer; - private static KafkaConsumer consumer; + private static KafkaProducer producer; + private static KafkaConsumer consumer; private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); @@ -51,12 +49,12 @@ public class MultiplePartitionTest { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); - producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); Properties consumerProperties = new Properties(); consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); - consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); @@ -87,11 +85,10 @@ public class MultiplePartitionTest { void givenMultiplePartitions_whenPublishedToKafkaAndConsumed_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { List sentMessageList = new ArrayList<>(); List receivedMessageList = new ArrayList<>(); - for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { - long messageId = Message.getRandomMessageId(); - String key = "Key-" + insertPosition; - Message message = new Message(key, messageId); - Future future = producer.send(new ProducerRecord<>(TOPIC, key, message)); + for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { + long applicationIdentifier = Message.getRandomApplicationIdentifier(); + Message message = new Message(partitionKey, applicationIdentifier); + Future future = producer.send(new ProducerRecord<>(TOPIC, partitionKey, message)); sentMessageList.add(message); RecordMetadata metadata = future.get(); System.out.println("Partition : " + metadata.partition()); @@ -99,7 +96,7 @@ public class MultiplePartitionTest { boolean isOrderMaintained = true; consumer.subscribe(Collections.singletonList(TOPIC)); - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { Message message = record.value(); receivedMessageList.add(message); diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java index 5751c8d0e0..350a28e7c1 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java @@ -15,8 +15,8 @@ import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.KafkaFuture; -import org.apache.kafka.common.serialization.StringDeserializer; -import org.apache.kafka.common.serialization.StringSerializer; +import org.apache.kafka.common.serialization.LongDeserializer; +import org.apache.kafka.common.serialization.LongSerializer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -36,8 +36,8 @@ public class SinglePartitionTest { private static int PARTITIONS = 1; private static short REPLICATION_FACTOR = 1; private static Admin admin; - private static KafkaProducer producer; - private static KafkaConsumer consumer; + private static KafkaProducer producer; + private static KafkaConsumer consumer; private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); @@ -53,12 +53,12 @@ public class SinglePartitionTest { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); - producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); Properties consumerProperties = new Properties(); consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); - consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); @@ -89,11 +89,10 @@ public class SinglePartitionTest { void givenASinglePartition_whenPublishedToKafkaAndConsumed_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { List sentMessageList = new ArrayList<>(); List receivedMessageList = new ArrayList<>(); - for (long insertPosition = 1; insertPosition <= 10 ; insertPosition++) { - long messageId = Message.getRandomMessageId(); - String key = "Key-" + insertPosition; - Message message = new Message(key, messageId); - ProducerRecord producerRecord = new ProducerRecord<>(TOPIC, key, message); + for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { + long applicationIdentifier = Message.getRandomApplicationIdentifier(); + Message message = new Message(partitionKey, applicationIdentifier); + ProducerRecord producerRecord = new ProducerRecord<>(TOPIC, partitionKey, message); Future future = producer.send(producerRecord); sentMessageList.add(message); RecordMetadata metadata = future.get(); @@ -101,7 +100,7 @@ public class SinglePartitionTest { } consumer.subscribe(Collections.singletonList(TOPIC)); - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { Message message = record.value(); receivedMessageList.add(message); From 7c40b82bf9fb27130ff0c8b97a0092616054fe7d Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 15 Oct 2023 19:30:29 -0400 Subject: [PATCH 033/233] Build Failure - Priority:3 Unit test class names need to end in UnitTest, integration tests with IntegrationTest, etc. --- ...PartitionTest.java => MultiplePartitionIntegrationTest.java} | 2 +- ...lePartitionTest.java => SinglePartitionIntegrationTest.java} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/{MultiplePartitionTest.java => MultiplePartitionIntegrationTest.java} (99%) rename apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/{SinglePartitionTest.java => SinglePartitionIntegrationTest.java} (99%) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java similarity index 99% rename from apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java rename to apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index ef0a881999..c948effd70 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -29,7 +29,7 @@ import java.util.concurrent.Future; import static org.junit.jupiter.api.Assertions.*; @Testcontainers -public class MultiplePartitionTest { +public class MultiplePartitionIntegrationTest { private static String TOPIC = "multi_partition_topic"; private static int PARTITIONS = 5; private static short REPLICATION_FACTOR = 1; diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java similarity index 99% rename from apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java rename to apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index 350a28e7c1..87b7d07431 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -31,7 +31,7 @@ import java.util.concurrent.Future; import static org.junit.jupiter.api.Assertions.assertTrue; @Testcontainers -public class SinglePartitionTest { +public class SinglePartitionIntegrationTest { private static String TOPIC = "single_partition_topic"; private static int PARTITIONS = 1; private static short REPLICATION_FACTOR = 1; From baaef6bcf3599c79d90cf8e6fc9f96df59c47e4d Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Mon, 16 Oct 2023 19:50:02 -0400 Subject: [PATCH 034/233] Added tests for External Sequence number with Time Window --- .../ExtSeqWithTimeWindowConsumer.java | 6 +- .../ExtSeqWithTimeWindowProducer.java | 1 + .../message/ordering/payload/Message.java | 12 +- .../ExtSeqWithTimeWindowIntegrationTest.java | 138 ++++++++++++++++++ 4 files changed, 153 insertions(+), 4 deletions(-) create mode 100644 apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java index 19595d9e95..cd424178ae 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java @@ -24,12 +24,12 @@ public class ExtSeqWithTimeWindowConsumer { props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); - Consumer consumer = new KafkaConsumer<>(props); + Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("multi_partition_topic")); List buffer = new ArrayList<>(); long lastProcessedTime = System.nanoTime(); while (true) { - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { buffer.add(record.value()); }); @@ -43,7 +43,7 @@ public class ExtSeqWithTimeWindowConsumer { private static void processBuffer(List buffer) { Collections.sort(buffer); buffer.forEach(message -> { - System.out.println("Processing message with Partition key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); + System.out.println("Processing message with Global Sequence number: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); }); buffer.clear(); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java index a20c569159..99e05990cb 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -19,6 +19,7 @@ public class ExtSeqWithTimeWindowProducer { for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { long applicationIdentifier = Message.getRandomApplicationIdentifier(); Message message = new Message(partitionKey, applicationIdentifier); + message.setGlobalSequenceNumber(partitionKey); producer.send(new ProducerRecord<>("multi_partition_topic", partitionKey, message)); System.out.println("Partition key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java index 734ecba53d..694d84f9d8 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java @@ -8,6 +8,8 @@ public class Message implements Comparable { private long partitionKey; private long applicationIdentifier; + private long globalSequenceNumber; + public Message(){ } @@ -26,9 +28,17 @@ public class Message implements Comparable { return applicationIdentifier; } + public long getGlobalSequenceNumber() { + return globalSequenceNumber; + } + + public void setGlobalSequenceNumber(long globalSequenceNumber) { + this.globalSequenceNumber = globalSequenceNumber; + } + @Override public int compareTo(Message other) { - return Long.compare(this.partitionKey, other.partitionKey); + return Long.compare(this.globalSequenceNumber, other.globalSequenceNumber); } @Override diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java new file mode 100644 index 0000000000..a01c230026 --- /dev/null +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -0,0 +1,138 @@ +package com.baeldung.kafka.message.ordering; + +import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; +import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; +import org.apache.kafka.clients.admin.*; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; +import org.apache.kafka.common.KafkaFuture; +import org.apache.kafka.common.serialization.LongDeserializer; +import org.apache.kafka.common.serialization.LongSerializer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.KafkaContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; +import java.time.Duration; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import static org.junit.jupiter.api.Assertions.*; + +@Testcontainers +public class ExtSeqWithTimeWindowIntegrationTest { + private static String TOPIC = "multi_partition_topic"; + private static int PARTITIONS = 5; + private static short REPLICATION_FACTOR = 1; + private static Admin admin; + private static KafkaProducer producer; + private static KafkaConsumer consumer; + private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); + + private static final long BUFFER_PERIOD_NS = 5000L * 1000000; // 5000 milliseconds converted to nanoseconds + @Container + private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + + @BeforeAll + static void setup() throws ExecutionException, InterruptedException { + KAFKA_CONTAINER.addExposedPort(9092); + + Properties adminProperties = new Properties(); + adminProperties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + + Properties producerProperties = new Properties(); + producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); + producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); + + Properties consumerProperties = new Properties(); + consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); + consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); + admin = Admin.create(adminProperties); + producer = new KafkaProducer<>(producerProperties); + consumer = new KafkaConsumer<>(consumerProperties); + List topicList = new ArrayList<>(); + NewTopic newTopic = new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR); + topicList.add(newTopic); + CreateTopicsResult result = admin.createTopics(topicList); + KafkaFuture future = result.values().get(TOPIC); + future.whenComplete((voidResult, exception) -> { + if (exception != null) { + System.err.println("Error creating the topic: " + exception.getMessage()); + } else { + System.out.println("Topic created successfully!"); + } + }).get(); + } + + @AfterAll + static void destroy() { + KAFKA_CONTAINER.stop(); + } + + @Test + void givenMultiplePartitions_whenPublishedToKafkaAndConsumedWithExtSeqNumberAndTimeWindow_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { + List sentMessageList = new ArrayList<>(); + List receivedMessageList = new ArrayList<>(); + for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { + long applicationIdentifier = Message.getRandomApplicationIdentifier(); + Message message = new Message(partitionKey, applicationIdentifier); + message.setGlobalSequenceNumber(partitionKey); + Future future = producer.send(new ProducerRecord<>(TOPIC, partitionKey, message)); + sentMessageList.add(message); + RecordMetadata metadata = future.get(); + System.out.println("Partition : " + metadata.partition()); + } + + boolean isOrderMaintained = true; + consumer.subscribe(Collections.singletonList(TOPIC)); + List buffer = new ArrayList<>(); + long lastProcessedTime = System.nanoTime(); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + records.forEach(record -> { + buffer.add(record.value()); + }); + while (buffer.size() > 0) { + if (System.nanoTime() - lastProcessedTime > BUFFER_PERIOD_NS) { + processBuffer(buffer, receivedMessageList); + lastProcessedTime = System.nanoTime(); + } + records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + records.forEach(record -> { + buffer.add(record.value()); + }); + } + for (int insertPosition = 0; insertPosition <= receivedMessageList.size() - 1; insertPosition++) { + if (isOrderMaintained){ + Message sentMessage = sentMessageList.get(insertPosition); + Message receivedMessage = receivedMessageList.get(insertPosition); + if (!sentMessage.equals(receivedMessage)) { + isOrderMaintained = false; + } + } + } + assertTrue(isOrderMaintained); + } + + private static void processBuffer(List buffer, List receivedMessageList) { + Collections.sort(buffer); + buffer.forEach(message -> { + receivedMessageList.add(message); + System.out.println("Processing message with Global Sequence number: " + message.getGlobalSequenceNumber() + ", Application Identifier: " + message.getApplicationIdentifier()); + }); + buffer.clear(); + } +} From 5b936c47a0c9a4cbf1ad4f8b695d47d7b76ca5be Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Tue, 17 Oct 2023 19:39:27 -0400 Subject: [PATCH 035/233] Message to User Event Rename --- .../ExtSeqWithTimeWindowConsumer.java | 17 +++--- .../ExtSeqWithTimeWindowProducer.java | 17 +++--- .../ordering/MultiPartitionConsumer.java | 15 +++-- .../ordering/MultiPartitionProducer.java | 15 ++--- .../ordering/SinglePartitionConsumer.java | 13 ++-- .../ordering/SinglePartitionProducer.java | 16 ++--- .../message/ordering/payload/Message.java | 61 ------------------- .../message/ordering/payload/UserEvent.java | 58 ++++++++++++++++++ .../ExtSeqWithTimeWindowIntegrationTest.java | 46 +++++++------- .../MultiplePartitionIntegrationTest.java | 36 +++++------ .../SinglePartitionIntegrationTest.java | 34 +++++------ 11 files changed, 163 insertions(+), 165 deletions(-) delete mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java index cd424178ae..639a980462 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java @@ -1,13 +1,12 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.LongDeserializer; -import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; import java.util.*; @@ -23,13 +22,13 @@ public class ExtSeqWithTimeWindowConsumer { props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); - Consumer consumer = new KafkaConsumer<>(props); + props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); + Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("multi_partition_topic")); - List buffer = new ArrayList<>(); + List buffer = new ArrayList<>(); long lastProcessedTime = System.nanoTime(); while (true) { - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { buffer.add(record.value()); }); @@ -40,10 +39,10 @@ public class ExtSeqWithTimeWindowConsumer { } } - private static void processBuffer(List buffer) { + private static void processBuffer(List buffer) { Collections.sort(buffer); - buffer.forEach(message -> { - System.out.println("Processing message with Global Sequence number: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); + buffer.forEach(userEvent -> { + System.out.println("Processing message with Global Sequence number: " + userEvent.getGlobalSequenceNumber() + ", event nano time : " + userEvent.getEventNanoTime()); }); buffer.clear(); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java index 99e05990cb..c18e35b351 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -1,6 +1,6 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; @@ -8,6 +8,7 @@ import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.LongSerializer; import java.util.Properties; +import java.util.UUID; public class ExtSeqWithTimeWindowProducer { public static void main(String[] args) { @@ -15,13 +16,13 @@ public class ExtSeqWithTimeWindowProducer { props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - KafkaProducer producer = new KafkaProducer<>(props); - for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { - long applicationIdentifier = Message.getRandomApplicationIdentifier(); - Message message = new Message(partitionKey, applicationIdentifier); - message.setGlobalSequenceNumber(partitionKey); - producer.send(new ProducerRecord<>("multi_partition_topic", partitionKey, message)); - System.out.println("Partition key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); + KafkaProducer producer = new KafkaProducer<>(props); + for (long sequenceNumber = 1; sequenceNumber <= 10 ; sequenceNumber++) { + UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + userEvent.setEventNanoTime(System.nanoTime()); + userEvent.setGlobalSequenceNumber(sequenceNumber); + producer.send(new ProducerRecord<>("multi_partition_topic", sequenceNumber, userEvent)); + System.out.println("User Event Nano time : " + userEvent.getEventNanoTime() + ", User Event Id: " + userEvent.getUserEventId()); } producer.close(); System.out.println("ExternalSequencingProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java index c37c645d31..e738832425 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java @@ -1,13 +1,12 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.LongDeserializer; -import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; import java.util.Collections; @@ -22,15 +21,15 @@ public class MultiPartitionConsumer { props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); - Consumer consumer = new KafkaConsumer<>(props); + props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); + Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("multi_partition_topic")); while (true) { - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { - Message message = record.value(); - if (message != null) { - System.out.println("Process message with Partition key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); + UserEvent userEvent = record.value(); + if (userEvent != null) { + System.out.println("Process message with event nano time : " + userEvent.getEventNanoTime() + ", Event ID: " + userEvent.getUserEventId()); } }); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java index 81cc5c6af0..db02c87bbe 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java @@ -1,6 +1,6 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; @@ -8,6 +8,7 @@ import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.LongSerializer; import java.util.Properties; +import java.util.UUID; public class MultiPartitionProducer { public static void main(String[] args) { @@ -15,12 +16,12 @@ public class MultiPartitionProducer { props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - KafkaProducer producer = new KafkaProducer<>(props); - for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { - long applicationIdentifier = Message.getRandomApplicationIdentifier(); - Message message = new Message(partitionKey, applicationIdentifier); - producer.send(new ProducerRecord<>("multi_partition_topic", partitionKey, message)); - System.out.println("Partition Key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); + KafkaProducer producer = new KafkaProducer<>(props); + for (long count = 1; count <= 10 ; count++) { + UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + userEvent.setEventNanoTime(System.nanoTime()); + producer.send(new ProducerRecord<>("multi_partition_topic", count, userEvent)); + System.out.println("Process message with Event ID: " + userEvent.getUserEventId()); } producer.close(); System.out.println("SinglePartitionProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java index 9f44cd78c6..5f5ce86924 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java @@ -1,13 +1,12 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.LongDeserializer; -import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; import java.util.Collections; @@ -23,14 +22,14 @@ public class SinglePartitionConsumer { props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); - Consumer consumer = new KafkaConsumer<>(props); + props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); + Consumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("single_partition_topic")); while (true) { - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { - Message message = record.value(); - System.out.println("Process message with Partition Key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); + UserEvent userEvent = record.value(); + System.out.println("Process message with event nano time : " + userEvent.getEventNanoTime() + ", Event ID: " + userEvent.getUserEventId()); }); } } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java index efa6e5b93d..2a7719e34f 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java @@ -1,13 +1,15 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.LongSerializer; +import java.time.Instant; import java.util.Properties; +import java.util.UUID; public class SinglePartitionProducer { public static void main(String[] args) { @@ -15,12 +17,12 @@ public class SinglePartitionProducer { props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - KafkaProducer producer = new KafkaProducer<>(props); - for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { - long applicationIdentifier = Message.getRandomApplicationIdentifier(); - Message message = new Message(partitionKey, applicationIdentifier); - producer.send(new ProducerRecord<>("single_partition_topic", partitionKey, message)); - System.out.println("Partition key: " + message.getPartitionKey() + ", Application Identifier: " + message.getApplicationIdentifier()); + KafkaProducer producer = new KafkaProducer<>(props); + for (long count = 1; count <= 10 ; count++) { + UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + userEvent.setEventNanoTime(System.nanoTime()); + producer.send(new ProducerRecord<>("single_partition_topic", count, userEvent)); + System.out.println("Process message with Event ID: " + userEvent.getUserEventId()); } producer.close(); System.out.println("SinglePartitionProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java deleted file mode 100644 index 694d84f9d8..0000000000 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/Message.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.kafka.message.ordering.payload; - -import java.util.Objects; -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; - -public class Message implements Comparable { - private long partitionKey; - private long applicationIdentifier; - - private long globalSequenceNumber; - - public Message(){ - - } - - //Required for Kafka Serialization and Deserialization - public Message(long partitionKey, long applicationIdentifier) { - this.partitionKey = partitionKey; - this.applicationIdentifier = applicationIdentifier; - } - - public long getPartitionKey() { - return partitionKey; - } - - public long getApplicationIdentifier() { - return applicationIdentifier; - } - - public long getGlobalSequenceNumber() { - return globalSequenceNumber; - } - - public void setGlobalSequenceNumber(long globalSequenceNumber) { - this.globalSequenceNumber = globalSequenceNumber; - } - - @Override - public int compareTo(Message other) { - return Long.compare(this.globalSequenceNumber, other.globalSequenceNumber); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof Message)) { - return false; - } - Message message = (Message) obj; - return this.applicationIdentifier == message.getApplicationIdentifier() && Objects.equals(this.partitionKey, message.getPartitionKey()); - } - - public static long getRandomApplicationIdentifier() { - Random rand = new Random(); - return ThreadLocalRandom.current().nextInt(1000); - } -} - diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java new file mode 100644 index 0000000000..0c4018e624 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java @@ -0,0 +1,58 @@ +package com.baeldung.kafka.message.ordering.payload; + +import java.util.Objects; +public class UserEvent implements Comparable { + private String userEventId; + + private long eventNanoTime; + + private long globalSequenceNumber; + + public UserEvent(){ + + } + + //Required for Kafka Serialization and Deserialization + public UserEvent(String userEventId) { + this.userEventId = userEventId; + } + + public String getUserEventId() { + return userEventId; + } + + public long getEventNanoTime() { + return eventNanoTime; + } + + public void setEventNanoTime(long eventNanoTime) { + this.eventNanoTime = eventNanoTime; + } + + public long getGlobalSequenceNumber() { + return globalSequenceNumber; + } + + public void setGlobalSequenceNumber(long globalSequenceNumber) { + this.globalSequenceNumber = globalSequenceNumber; + } + + @Override + public int compareTo(UserEvent other) { + return Long.compare(this.globalSequenceNumber, other.globalSequenceNumber); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof UserEvent)) { + return false; + } + UserEvent userEvent = (UserEvent) obj; + return Objects.equals(this.userEventId, userEvent.getUserEventId()) + && userEvent.getEventNanoTime() == this.eventNanoTime; + } +} + diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java index a01c230026..5f540d5b50 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.admin.*; @@ -34,8 +34,8 @@ public class ExtSeqWithTimeWindowIntegrationTest { private static int PARTITIONS = 5; private static short REPLICATION_FACTOR = 1; private static Admin admin; - private static KafkaProducer producer; - private static KafkaConsumer consumer; + private static KafkaProducer producer; + private static KafkaConsumer consumer; private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); private static final long BUFFER_PERIOD_NS = 5000L * 1000000; // 5000 milliseconds converted to nanoseconds @@ -59,7 +59,7 @@ public class ExtSeqWithTimeWindowIntegrationTest { consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); + consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); @@ -85,29 +85,29 @@ public class ExtSeqWithTimeWindowIntegrationTest { @Test void givenMultiplePartitions_whenPublishedToKafkaAndConsumedWithExtSeqNumberAndTimeWindow_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { - List sentMessageList = new ArrayList<>(); - List receivedMessageList = new ArrayList<>(); - for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { - long applicationIdentifier = Message.getRandomApplicationIdentifier(); - Message message = new Message(partitionKey, applicationIdentifier); - message.setGlobalSequenceNumber(partitionKey); - Future future = producer.send(new ProducerRecord<>(TOPIC, partitionKey, message)); - sentMessageList.add(message); + List sentUserEventList = new ArrayList<>(); + List receivedUserEventList = new ArrayList<>(); + for (long sequenceNumber = 1; sequenceNumber <= 10 ; sequenceNumber++) { + UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + userEvent.setEventNanoTime(System.nanoTime()); + userEvent.setGlobalSequenceNumber(sequenceNumber); + Future future = producer.send(new ProducerRecord<>(TOPIC, sequenceNumber, userEvent)); + sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); System.out.println("Partition : " + metadata.partition()); } boolean isOrderMaintained = true; consumer.subscribe(Collections.singletonList(TOPIC)); - List buffer = new ArrayList<>(); + List buffer = new ArrayList<>(); long lastProcessedTime = System.nanoTime(); - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { buffer.add(record.value()); }); while (buffer.size() > 0) { if (System.nanoTime() - lastProcessedTime > BUFFER_PERIOD_NS) { - processBuffer(buffer, receivedMessageList); + processBuffer(buffer, receivedUserEventList); lastProcessedTime = System.nanoTime(); } records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); @@ -115,11 +115,11 @@ public class ExtSeqWithTimeWindowIntegrationTest { buffer.add(record.value()); }); } - for (int insertPosition = 0; insertPosition <= receivedMessageList.size() - 1; insertPosition++) { + for (int insertPosition = 0; insertPosition <= receivedUserEventList.size() - 1; insertPosition++) { if (isOrderMaintained){ - Message sentMessage = sentMessageList.get(insertPosition); - Message receivedMessage = receivedMessageList.get(insertPosition); - if (!sentMessage.equals(receivedMessage)) { + UserEvent sentUserEvent = sentUserEventList.get(insertPosition); + UserEvent receivedUserEvent = receivedUserEventList.get(insertPosition); + if (!sentUserEvent.equals(receivedUserEvent)) { isOrderMaintained = false; } } @@ -127,11 +127,11 @@ public class ExtSeqWithTimeWindowIntegrationTest { assertTrue(isOrderMaintained); } - private static void processBuffer(List buffer, List receivedMessageList) { + private static void processBuffer(List buffer, List receivedUserEventList) { Collections.sort(buffer); - buffer.forEach(message -> { - receivedMessageList.add(message); - System.out.println("Processing message with Global Sequence number: " + message.getGlobalSequenceNumber() + ", Application Identifier: " + message.getApplicationIdentifier()); + buffer.forEach(userEvent -> { + receivedUserEventList.add(userEvent); + System.out.println("Process message with Event ID: " + userEvent.getUserEventId()); }); buffer.clear(); } diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index c948effd70..d4b88ad06f 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.admin.*; @@ -34,8 +34,8 @@ public class MultiplePartitionIntegrationTest { private static int PARTITIONS = 5; private static short REPLICATION_FACTOR = 1; private static Admin admin; - private static KafkaProducer producer; - private static KafkaConsumer consumer; + private static KafkaProducer producer; + private static KafkaConsumer consumer; private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); @@ -57,7 +57,7 @@ public class MultiplePartitionIntegrationTest { consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); + consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); @@ -83,29 +83,29 @@ public class MultiplePartitionIntegrationTest { @Test void givenMultiplePartitions_whenPublishedToKafkaAndConsumed_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { - List sentMessageList = new ArrayList<>(); - List receivedMessageList = new ArrayList<>(); - for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { - long applicationIdentifier = Message.getRandomApplicationIdentifier(); - Message message = new Message(partitionKey, applicationIdentifier); - Future future = producer.send(new ProducerRecord<>(TOPIC, partitionKey, message)); - sentMessageList.add(message); + List sentUserEventList = new ArrayList<>(); + List receivedUserEventList = new ArrayList<>(); + for (long count = 1; count <= 10 ; count++) { + UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + userEvent.setEventNanoTime(System.nanoTime()); + Future future = producer.send(new ProducerRecord<>(TOPIC, count, userEvent)); + sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); System.out.println("Partition : " + metadata.partition()); } boolean isOrderMaintained = true; consumer.subscribe(Collections.singletonList(TOPIC)); - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { - Message message = record.value(); - receivedMessageList.add(message); + UserEvent userEvent = record.value(); + receivedUserEventList.add(userEvent); }); - for (int insertPosition = 0; insertPosition <= receivedMessageList.size() - 1; insertPosition++) { + for (int insertPosition = 0; insertPosition <= receivedUserEventList.size() - 1; insertPosition++) { if (isOrderMaintained){ - Message sentMessage = sentMessageList.get(insertPosition); - Message receivedMessage = receivedMessageList.get(insertPosition); - if (!sentMessage.equals(receivedMessage)) { + UserEvent sentUserEvent = sentUserEventList.get(insertPosition); + UserEvent receivedUserEvent = receivedUserEventList.get(insertPosition); + if (!sentUserEvent.equals(receivedUserEvent)) { isOrderMaintained = false; } } diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index 87b7d07431..b41dc67686 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.message.ordering.payload.Message; +import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.admin.Admin; @@ -36,8 +36,8 @@ public class SinglePartitionIntegrationTest { private static int PARTITIONS = 1; private static short REPLICATION_FACTOR = 1; private static Admin admin; - private static KafkaProducer producer; - private static KafkaConsumer consumer; + private static KafkaProducer producer; + private static KafkaConsumer consumer; private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); @@ -61,7 +61,7 @@ public class SinglePartitionIntegrationTest { consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, Message.class); + consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); @@ -87,29 +87,29 @@ public class SinglePartitionIntegrationTest { @Test void givenASinglePartition_whenPublishedToKafkaAndConsumed_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { - List sentMessageList = new ArrayList<>(); - List receivedMessageList = new ArrayList<>(); - for (long partitionKey = 1; partitionKey <= 10 ; partitionKey++) { - long applicationIdentifier = Message.getRandomApplicationIdentifier(); - Message message = new Message(partitionKey, applicationIdentifier); - ProducerRecord producerRecord = new ProducerRecord<>(TOPIC, partitionKey, message); + List sentUserEventList = new ArrayList<>(); + List receivedUserEventList = new ArrayList<>(); + for (long count = 1; count <= 10 ; count++) { + UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + userEvent.setEventNanoTime(System.nanoTime()); + ProducerRecord producerRecord = new ProducerRecord<>(TOPIC, userEvent); Future future = producer.send(producerRecord); - sentMessageList.add(message); + sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); System.out.println("Partition : " + metadata.partition()); } consumer.subscribe(Collections.singletonList(TOPIC)); - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); + ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { - Message message = record.value(); - receivedMessageList.add(message); + UserEvent userEvent = record.value(); + receivedUserEventList.add(userEvent); }); boolean result = true; for (int count = 0; count <= 9 ; count++) { - Message sentMessage = sentMessageList.get(count); - Message receivedMessage = receivedMessageList.get(count); - if (!sentMessage.equals(receivedMessage) && result){ + UserEvent sentUserEvent = sentUserEventList.get(count); + UserEvent receivedUserEvent = receivedUserEventList.get(count); + if (!sentUserEvent.equals(receivedUserEvent) && result){ result = false; } } From 1071a071706b8ed306153628d9610a91cf4de82a Mon Sep 17 00:00:00 2001 From: Bipinkumar27 Date: Thu, 19 Oct 2023 19:33:27 +0530 Subject: [PATCH 036/233] JAVA-18764: Changes made for updating the pkg --- .../cassecuredapp/CasSecuredApplication.java | 15 +++------------ .../baeldung/cassecuredapp/UserRepository.java | 15 --------------- .../CasUserDetailsService.java} | 18 ++++++++++-------- .../{Users.java => user/User.java} | 4 ++-- .../cassecuredapp/user/UserRepository.java | 14 ++++++++++++++ 5 files changed, 29 insertions(+), 37 deletions(-) delete mode 100644 security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/UserRepository.java rename security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/{MyUserDetailsService.java => service/CasUserDetailsService.java} (63%) rename security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/{Users.java => user/User.java} (91%) create mode 100644 security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java index 9293a3e00f..84bbd2ace4 100644 --- a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java @@ -1,30 +1,21 @@ package com.baeldung.cassecuredapp; import org.jasig.cas.client.session.SingleSignOutFilter; -import org.jasig.cas.client.session.SingleSignOutHttpSessionListener; import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; import org.jasig.cas.client.validation.TicketValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; -import org.springframework.context.event.EventListener; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.cas.ServiceProperties; import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.web.CasAuthenticationEntryPoint; import org.springframework.security.cas.web.CasAuthenticationFilter; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.authentication.logout.LogoutFilter; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; -import javax.servlet.http.HttpSessionEvent; +import com.baeldung.cassecuredapp.service.CasUserDetailsService; @SpringBootApplication public class CasSecuredApplication { @@ -61,8 +52,8 @@ public class CasSecuredApplication { } @Bean - public MyUserDetailsService getUser(){ - return new MyUserDetailsService(); + public CasUserDetailsService getUser(){ + return new CasUserDetailsService(); } @Bean public CasAuthenticationProvider casAuthenticationProvider( diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/UserRepository.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/UserRepository.java deleted file mode 100644 index 366329a3fb..0000000000 --- a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/UserRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.cassecuredapp; - -import java.util.Optional; - -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -@Repository -public interface UserRepository extends CrudRepository { - - Users findByEmail(@Param("email") String email); - -} diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/MyUserDetailsService.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/service/CasUserDetailsService.java similarity index 63% rename from security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/MyUserDetailsService.java rename to security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/service/CasUserDetailsService.java index 35c83bfd75..ac4fef1ff0 100644 --- a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/MyUserDetailsService.java +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/service/CasUserDetailsService.java @@ -1,15 +1,17 @@ -package com.baeldung.cassecuredapp; +package com.baeldung.cassecuredapp.service; import java.util.Collections; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; -public class MyUserDetailsService implements UserDetailsService { +import com.baeldung.cassecuredapp.user.User; +import com.baeldung.cassecuredapp.user.UserRepository; + +public class CasUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @@ -17,18 +19,18 @@ public class MyUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // Get the user from the database. - Users users = getUserFromDatabase(username); + User user = getUserFromDatabase(username); // Create a UserDetails object. - UserDetails userDetails = new User( - users.getEmail(), - users.getPassword(), + UserDetails userDetails = new org.springframework.security.core.userdetails.User( + user.getEmail(), + user.getPassword(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"))); return userDetails; } - private Users getUserFromDatabase(String username) { + private User getUserFromDatabase(String username) { return userRepository.findByEmail(username); } } diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/Users.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/User.java similarity index 91% rename from security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/Users.java rename to security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/User.java index 4e775e80e3..1dddc11458 100644 --- a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/Users.java +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/User.java @@ -1,11 +1,11 @@ -package com.baeldung.cassecuredapp; +package com.baeldung.cassecuredapp.user; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity -public class Users { +public class User { @Id private Long id; diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java new file mode 100644 index 0000000000..0481fabb06 --- /dev/null +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.cassecuredapp.user; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.baeldung.cassecuredapp.user.User; + +@Repository +public interface UserRepository extends CrudRepository { + + User findByEmail(@Param("email") String email); + +} From a16aa0ee61b10cfce6f78ff0146bbedbabd43a90 Mon Sep 17 00:00:00 2001 From: Vladyslav Chernov Date: Fri, 20 Oct 2023 15:17:36 -0700 Subject: [PATCH 037/233] BAEL-5755: remove comments --- .../main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) 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 d2acafc881..99e5c7c0cb 100644 --- a/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java +++ b/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java @@ -51,7 +51,6 @@ public class Xml2CsvExample { try (InputStream in = Files.newInputStream(Paths.get(xmlFilePath)); BufferedWriter writer = new BufferedWriter(new FileWriter(csvFilePath))) { - // Write header to CSV writer.write("bookstore_id,book_id,category,title,author_id,author_name,price\n"); XMLStreamReader reader = inputFactory.createXMLStreamReader(in); @@ -67,7 +66,7 @@ public class Xml2CsvExample { case XMLStreamConstants.START_ELEMENT: currentElement = reader.getLocalName(); if ("Bookstore".equals(currentElement)) { - bookstoreInfo.setLength(0); // clear previous bookstore info + bookstoreInfo.setLength(0); bookstoreInfo.append(reader.getAttributeValue(null, "id")) .append(","); } @@ -94,12 +93,10 @@ public class Xml2CsvExample { case XMLStreamConstants.END_ELEMENT: if ("Book".equals(reader.getLocalName())) { - // remove the last comma and add a newline csvRow.setLength(csvRow.length() - 1); csvRow.append("\n"); writer.write(csvRow.toString()); - // Reset the StringBuilder for the next row csvRow.setLength(0); } break; From 199df44c7f2978ed766273dd2bb17fce66ad0531 Mon Sep 17 00:00:00 2001 From: Bipinkumar27 Date: Mon, 23 Oct 2023 16:11:03 +0530 Subject: [PATCH 038/233] JAVA-18764: Changes made for updating the code --- .../cassecuredapp/CasSecuredApplication.java | 9 ++++++--- .../service/CasUserDetailsService.java | 13 +++++++------ .../cassecuredapp/user/{User.java => CasUser.java} | 2 +- .../baeldung/cassecuredapp/user/UserRepository.java | 6 ++---- .../src/main/resources/application.properties | 10 +++++----- 5 files changed, 21 insertions(+), 19 deletions(-) rename security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/{User.java => CasUser.java} (96%) diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java index 84bbd2ace4..f78d7a45d5 100644 --- a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java @@ -12,6 +12,8 @@ import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.cas.ServiceProperties; import org.springframework.security.cas.authentication.CasAuthenticationProvider; import org.springframework.security.cas.web.CasAuthenticationFilter; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; import org.springframework.security.web.authentication.logout.LogoutFilter; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; @@ -62,10 +64,11 @@ public class CasSecuredApplication { CasAuthenticationProvider provider = new CasAuthenticationProvider(); provider.setServiceProperties(serviceProperties); provider.setTicketValidator(ticketValidator); - /* provider.setUserDetailsService( + provider.setUserDetailsService( s -> new User("casuser", "Mellon", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ADMIN")));*/ - provider.setUserDetailsService(getUser()); + AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); + //For Authentication with a Database-backed UserDetailsService + //provider.setUserDetailsService(getUser()); provider.setKey("CAS_PROVIDER_LOCALHOST_8900"); return provider; } diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/service/CasUserDetailsService.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/service/CasUserDetailsService.java index ac4fef1ff0..801f5726b7 100644 --- a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/service/CasUserDetailsService.java +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/service/CasUserDetailsService.java @@ -4,11 +4,12 @@ import java.util.Collections; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; -import com.baeldung.cassecuredapp.user.User; +import com.baeldung.cassecuredapp.user.CasUser; import com.baeldung.cassecuredapp.user.UserRepository; public class CasUserDetailsService implements UserDetailsService { @@ -19,18 +20,18 @@ public class CasUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // Get the user from the database. - User user = getUserFromDatabase(username); + CasUser casUser = getUserFromDatabase(username); // Create a UserDetails object. - UserDetails userDetails = new org.springframework.security.core.userdetails.User( - user.getEmail(), - user.getPassword(), + UserDetails userDetails = new User( + casUser.getEmail(), + casUser.getPassword(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"))); return userDetails; } - private User getUserFromDatabase(String username) { + private CasUser getUserFromDatabase(String username) { return userRepository.findByEmail(username); } } diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/User.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/CasUser.java similarity index 96% rename from security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/User.java rename to security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/CasUser.java index 1dddc11458..2bf96d0994 100644 --- a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/User.java +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/CasUser.java @@ -5,7 +5,7 @@ import javax.persistence.Entity; import javax.persistence.Id; @Entity -public class User { +public class CasUser { @Id private Long id; diff --git a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java index 0481fabb06..623ccf2e38 100644 --- a/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java +++ b/security-modules/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/user/UserRepository.java @@ -4,11 +4,9 @@ import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import com.baeldung.cassecuredapp.user.User; - @Repository -public interface UserRepository extends CrudRepository { +public interface UserRepository extends CrudRepository { - User findByEmail(@Param("email") String email); + CasUser findByEmail(@Param("email") String email); } diff --git a/security-modules/cas/cas-secured-app/src/main/resources/application.properties b/security-modules/cas/cas-secured-app/src/main/resources/application.properties index fa13527982..5c93c67ff1 100644 --- a/security-modules/cas/cas-secured-app/src/main/resources/application.properties +++ b/security-modules/cas/cas-secured-app/src/main/resources/application.properties @@ -1,8 +1,8 @@ server.port=8900 spring.freemarker.suffix=.ftl -spring.jpa.generate-ddl=false -spring.datasource.url= jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC -spring.datasource.username=root -spring.datasource.password=root1234 -spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver \ No newline at end of file +#spring.jpa.generate-ddl=false +#spring.datasource.url= jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC +#spring.datasource.username=root +#spring.datasource.password=root +#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver \ No newline at end of file From d2cd902965cc8968628185b57f5f31e0de94724c Mon Sep 17 00:00:00 2001 From: Bipinkumar27 Date: Mon, 23 Oct 2023 16:12:35 +0530 Subject: [PATCH 039/233] JAVA-18764: Update article "CAS SSO with Spring Security" --- .../src/main/resources/application.yml | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/security-modules/cas/cas-server/src/main/resources/application.yml b/security-modules/cas/cas-server/src/main/resources/application.yml index 0fd72c539d..a49e86dd09 100644 --- a/security-modules/cas/cas-server/src/main/resources/application.yml +++ b/security-modules/cas/cas-server/src/main/resources/application.yml @@ -8,19 +8,19 @@ server: spring: main: allow-bean-definition-overriding: true -cas: - authn: - accept: - users: - jdbc: - query[0]: - sql: SELECT * FROM users WHERE email = ? - url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC - dialect: org.hibernate.dialect.MySQLDialect - user: root - password: root1234 - ddlAuto: none - driverClass: com.mysql.cj.jdbc.Driver - fieldPassword: password - passwordEncoder: - type: NONE +#cas: +# authn: +# accept: +# users: +# jdbc: +# query[0]: +# sql: SELECT * FROM users WHERE email = ? +# url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC +# dialect: org.hibernate.dialect.MySQLDialect +# user: root +# password: root +# ddlAuto: none +# driverClass: com.mysql.cj.jdbc.Driver +# fieldPassword: password +# passwordEncoder: +# type: NONE From bb9a96d9b36c5806a0ace5042d3f9df50e6c6673 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 27 Oct 2023 22:48:52 +0530 Subject: [PATCH 040/233] JAVA-26380 Change parent of spring-security-modules- Check build failures --- spring-security-modules/pom.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index ed8279c5f7..1b3db18b84 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -10,8 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 From dc6b248d9d31785226c255dc6f96495b2eb34e61 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 28 Oct 2023 12:26:06 +0530 Subject: [PATCH 041/233] JAVA-26280 Improve libraries-testing module build time --- libraries-testing/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index 2c7f231fdc..8db9e4e5c5 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -213,7 +213,7 @@ 1.9.9 1.46.0 1.9.0 - 3.6.12 + 4.0.18 1.5.0 3.0.0 0.8.1 From 246d83d49d6790be372681ef3233ff567b02334b Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 28 Oct 2023 13:19:47 +0530 Subject: [PATCH 042/233] JAVA-26380 Update parent of child modules to use immediate parent --- spring-security-modules/spring-security-acl/pom.xml | 3 +-- spring-security-modules/spring-security-auth0/pom.xml | 3 +-- spring-security-modules/spring-security-azuread/pom.xml | 3 +-- spring-security-modules/spring-security-cognito/pom.xml | 3 +-- spring-security-modules/spring-security-core-2/pom.xml | 3 +-- spring-security-modules/spring-security-core/pom.xml | 3 +-- spring-security-modules/spring-security-ldap/pom.xml | 3 +-- spring-security-modules/spring-security-legacy-oidc/pom.xml | 3 +-- spring-security-modules/spring-security-oauth2-sso/pom.xml | 3 +-- spring-security-modules/spring-security-oauth2/pom.xml | 3 +-- spring-security-modules/spring-security-oidc/pom.xml | 3 +-- spring-security-modules/spring-security-okta/pom.xml | 3 +-- spring-security-modules/spring-security-opa/pom.xml | 3 +-- spring-security-modules/spring-security-pkce/pom.xml | 3 +-- spring-security-modules/spring-security-saml/pom.xml | 3 +-- spring-security-modules/spring-security-social-login/pom.xml | 3 +-- spring-security-modules/spring-security-web-angular/pom.xml | 3 +-- spring-security-modules/spring-security-web-boot-1/pom.xml | 3 +-- spring-security-modules/spring-security-web-boot-2/pom.xml | 3 +-- spring-security-modules/spring-security-web-boot-3/pom.xml | 3 +-- spring-security-modules/spring-security-web-boot-4/pom.xml | 3 +-- spring-security-modules/spring-security-web-boot-5/pom.xml | 3 +-- spring-security-modules/spring-security-web-login-2/pom.xml | 3 +-- spring-security-modules/spring-security-web-mvc/pom.xml | 3 +-- .../spring-security-web-rest-basic-auth/pom.xml | 3 +-- .../spring-security-web-rest-custom/pom.xml | 3 +-- spring-security-modules/spring-security-web-springdoc/pom.xml | 3 +-- spring-security-modules/spring-security-web-thymeleaf/pom.xml | 3 +-- spring-security-modules/spring-security-web-x509/pom.xml | 3 +-- 29 files changed, 29 insertions(+), 58 deletions(-) diff --git a/spring-security-modules/spring-security-acl/pom.xml b/spring-security-modules/spring-security-acl/pom.xml index 7facc1b14b..734b85800a 100644 --- a/spring-security-modules/spring-security-acl/pom.xml +++ b/spring-security-modules/spring-security-acl/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-auth0/pom.xml b/spring-security-modules/spring-security-auth0/pom.xml index 106a0db29f..8ee59eeac1 100644 --- a/spring-security-modules/spring-security-auth0/pom.xml +++ b/spring-security-modules/spring-security-auth0/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-azuread/pom.xml b/spring-security-modules/spring-security-azuread/pom.xml index c1fe08b47a..7e67a7e635 100644 --- a/spring-security-modules/spring-security-azuread/pom.xml +++ b/spring-security-modules/spring-security-azuread/pom.xml @@ -6,9 +6,8 @@ 4.0.0 com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 spring-security-azuread diff --git a/spring-security-modules/spring-security-cognito/pom.xml b/spring-security-modules/spring-security-cognito/pom.xml index 56754ddf99..2e359382a7 100644 --- a/spring-security-modules/spring-security-cognito/pom.xml +++ b/spring-security-modules/spring-security-cognito/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-core-2/pom.xml b/spring-security-modules/spring-security-core-2/pom.xml index 5d77098869..54aac0d9a7 100644 --- a/spring-security-modules/spring-security-core-2/pom.xml +++ b/spring-security-modules/spring-security-core-2/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-core/pom.xml b/spring-security-modules/spring-security-core/pom.xml index 03d7030057..2a18145ac0 100644 --- a/spring-security-modules/spring-security-core/pom.xml +++ b/spring-security-modules/spring-security-core/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-ldap/pom.xml b/spring-security-modules/spring-security-ldap/pom.xml index 471ffff4a1..9f4f3b4106 100644 --- a/spring-security-modules/spring-security-ldap/pom.xml +++ b/spring-security-modules/spring-security-ldap/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-legacy-oidc/pom.xml b/spring-security-modules/spring-security-legacy-oidc/pom.xml index e98486b0ff..55b6e780b2 100644 --- a/spring-security-modules/spring-security-legacy-oidc/pom.xml +++ b/spring-security-modules/spring-security-legacy-oidc/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-oauth2-sso/pom.xml b/spring-security-modules/spring-security-oauth2-sso/pom.xml index a87e4d7814..d8101d2313 100644 --- a/spring-security-modules/spring-security-oauth2-sso/pom.xml +++ b/spring-security-modules/spring-security-oauth2-sso/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-oauth2/pom.xml b/spring-security-modules/spring-security-oauth2/pom.xml index 1b30f6685d..977e2c16fd 100644 --- a/spring-security-modules/spring-security-oauth2/pom.xml +++ b/spring-security-modules/spring-security-oauth2/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-oidc/pom.xml b/spring-security-modules/spring-security-oidc/pom.xml index 70031b7396..c27c084ad7 100644 --- a/spring-security-modules/spring-security-oidc/pom.xml +++ b/spring-security-modules/spring-security-oidc/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-okta/pom.xml b/spring-security-modules/spring-security-okta/pom.xml index 98b8abedb4..5ae1241b18 100644 --- a/spring-security-modules/spring-security-okta/pom.xml +++ b/spring-security-modules/spring-security-okta/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-opa/pom.xml b/spring-security-modules/spring-security-opa/pom.xml index 72b0574253..a6240f6e69 100644 --- a/spring-security-modules/spring-security-opa/pom.xml +++ b/spring-security-modules/spring-security-opa/pom.xml @@ -7,9 +7,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-pkce/pom.xml b/spring-security-modules/spring-security-pkce/pom.xml index 5899b297b4..e0bd8eb90e 100644 --- a/spring-security-modules/spring-security-pkce/pom.xml +++ b/spring-security-modules/spring-security-pkce/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-saml/pom.xml b/spring-security-modules/spring-security-saml/pom.xml index 8a9b418374..8d7cce939f 100644 --- a/spring-security-modules/spring-security-saml/pom.xml +++ b/spring-security-modules/spring-security-saml/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-social-login/pom.xml b/spring-security-modules/spring-security-social-login/pom.xml index ddda4235be..5efa5b703c 100644 --- a/spring-security-modules/spring-security-social-login/pom.xml +++ b/spring-security-modules/spring-security-social-login/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-angular/pom.xml b/spring-security-modules/spring-security-web-angular/pom.xml index 2a745bc6cc..15dc4d007c 100644 --- a/spring-security-modules/spring-security-web-angular/pom.xml +++ b/spring-security-modules/spring-security-web-angular/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 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 fa0fd567fe..08adb700ec 100644 --- a/spring-security-modules/spring-security-web-boot-1/pom.xml +++ b/spring-security-modules/spring-security-web-boot-1/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 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 3ba8726f51..2255f8b035 100644 --- a/spring-security-modules/spring-security-web-boot-2/pom.xml +++ b/spring-security-modules/spring-security-web-boot-2/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-boot-3/pom.xml b/spring-security-modules/spring-security-web-boot-3/pom.xml index 5229068dfa..0b71e89527 100644 --- a/spring-security-modules/spring-security-web-boot-3/pom.xml +++ b/spring-security-modules/spring-security-web-boot-3/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-boot-4/pom.xml b/spring-security-modules/spring-security-web-boot-4/pom.xml index ffbed0f8ab..b5bfc55a9f 100644 --- a/spring-security-modules/spring-security-web-boot-4/pom.xml +++ b/spring-security-modules/spring-security-web-boot-4/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-boot-5/pom.xml b/spring-security-modules/spring-security-web-boot-5/pom.xml index f4e2e3ad92..14b8d87f25 100644 --- a/spring-security-modules/spring-security-web-boot-5/pom.xml +++ b/spring-security-modules/spring-security-web-boot-5/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-login-2/pom.xml b/spring-security-modules/spring-security-web-login-2/pom.xml index 2d92a8567f..a44543a6ba 100644 --- a/spring-security-modules/spring-security-web-login-2/pom.xml +++ b/spring-security-modules/spring-security-web-login-2/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-mvc/pom.xml b/spring-security-modules/spring-security-web-mvc/pom.xml index 505826d1a2..10dd89f618 100644 --- a/spring-security-modules/spring-security-web-mvc/pom.xml +++ b/spring-security-modules/spring-security-web-mvc/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml b/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml index 3c842a8a54..9a3b21af92 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml +++ b/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-rest-custom/pom.xml b/spring-security-modules/spring-security-web-rest-custom/pom.xml index dfd2f59aaf..2e55fe8b89 100644 --- a/spring-security-modules/spring-security-web-rest-custom/pom.xml +++ b/spring-security-modules/spring-security-web-rest-custom/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-springdoc/pom.xml b/spring-security-modules/spring-security-web-springdoc/pom.xml index 03e938f1c8..30102fd83d 100644 --- a/spring-security-modules/spring-security-web-springdoc/pom.xml +++ b/spring-security-modules/spring-security-web-springdoc/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-thymeleaf/pom.xml b/spring-security-modules/spring-security-web-thymeleaf/pom.xml index c13aa6a471..dd5f2d7c97 100644 --- a/spring-security-modules/spring-security-web-thymeleaf/pom.xml +++ b/spring-security-modules/spring-security-web-thymeleaf/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-web-x509/pom.xml b/spring-security-modules/spring-security-web-x509/pom.xml index 5282ab7d83..ec0331fd53 100644 --- a/spring-security-modules/spring-security-web-x509/pom.xml +++ b/spring-security-modules/spring-security-web-x509/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + spring-security-modules 0.0.1-SNAPSHOT - ../../parent-boot-2 From 462ddc7f0260f44d0dbd56789f55c09ea9c5cd88 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Sat, 28 Oct 2023 21:11:08 +0530 Subject: [PATCH 043/233] BAEL-7145 Bill Pugh Singleton implementation --- .../baledung/billpugh/BillPughSingleton.java | 15 ++++++ .../billpugh/EagerLoadedSingleton.java | 11 +++++ .../billpugh/LazyLoadedSingleton.java | 15 ++++++ .../SynchronizedLazyLoadedSingleton.java | 15 ++++++ .../billpugh/BillPughSingletonUnitTest.java | 43 +++++++++++++++++ .../EagerLoadedSingletonUnitTest.java | 46 +++++++++++++++++++ .../billpugh/LazyLoadedSingletonUnitTest.java | 17 +++++++ ...nchronizedLazyLoadedSingletonUnitTest.java | 44 ++++++++++++++++++ 8 files changed, 206 insertions(+) create mode 100644 patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/BillPughSingleton.java create mode 100644 patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/EagerLoadedSingleton.java create mode 100644 patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/LazyLoadedSingleton.java create mode 100644 patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/SynchronizedLazyLoadedSingleton.java create mode 100644 patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/BillPughSingletonUnitTest.java create mode 100644 patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/EagerLoadedSingletonUnitTest.java create mode 100644 patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/LazyLoadedSingletonUnitTest.java create mode 100644 patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/SynchronizedLazyLoadedSingletonUnitTest.java diff --git a/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/BillPughSingleton.java b/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/BillPughSingleton.java new file mode 100644 index 0000000000..f558706a07 --- /dev/null +++ b/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/BillPughSingleton.java @@ -0,0 +1,15 @@ +package com.baledung.billpugh; + +public class BillPughSingleton { + private BillPughSingleton() { + + } + + private static class SingletonHelper { + private static final BillPughSingleton BILL_PUGH_SINGLETON_INSTANCE = new BillPughSingleton(); + } + + public static BillPughSingleton getInstance() { + return SingletonHelper.BILL_PUGH_SINGLETON_INSTANCE; + } +} diff --git a/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/EagerLoadedSingleton.java b/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/EagerLoadedSingleton.java new file mode 100644 index 0000000000..c0a535f2d5 --- /dev/null +++ b/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/EagerLoadedSingleton.java @@ -0,0 +1,11 @@ +package com.baledung.billpugh; + +public class EagerLoadedSingleton { + private static final EagerLoadedSingleton EAGER_LOADED_SINGLETON = new EagerLoadedSingleton(); + private EagerLoadedSingleton() { + + } + public static EagerLoadedSingleton getInstance() { + return EAGER_LOADED_SINGLETON; + } +} diff --git a/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/LazyLoadedSingleton.java b/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/LazyLoadedSingleton.java new file mode 100644 index 0000000000..b4967a58cd --- /dev/null +++ b/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/LazyLoadedSingleton.java @@ -0,0 +1,15 @@ +package com.baledung.billpugh; + +public class LazyLoadedSingleton { + private static LazyLoadedSingleton lazyLoadedSingletonObj; + + private LazyLoadedSingleton() { + } + + public static LazyLoadedSingleton getInstance() { + if (null == lazyLoadedSingletonObj) { + lazyLoadedSingletonObj = new LazyLoadedSingleton(); + } + return lazyLoadedSingletonObj; + } +} diff --git a/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/SynchronizedLazyLoadedSingleton.java b/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/SynchronizedLazyLoadedSingleton.java new file mode 100644 index 0000000000..fe3457e054 --- /dev/null +++ b/patterns-modules/design-patterns-singleton/src/main/java/com/baledung/billpugh/SynchronizedLazyLoadedSingleton.java @@ -0,0 +1,15 @@ +package com.baledung.billpugh; + +public class SynchronizedLazyLoadedSingleton { + private static SynchronizedLazyLoadedSingleton synchronizedLazyLoadedSingleton; + + private SynchronizedLazyLoadedSingleton() { + } + + public static synchronized SynchronizedLazyLoadedSingleton getInstance() { + if (null == synchronizedLazyLoadedSingleton) { + synchronizedLazyLoadedSingleton = new SynchronizedLazyLoadedSingleton(); + } + return synchronizedLazyLoadedSingleton; + } +} \ No newline at end of file diff --git a/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/BillPughSingletonUnitTest.java b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/BillPughSingletonUnitTest.java new file mode 100644 index 0000000000..b42d36229f --- /dev/null +++ b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/BillPughSingletonUnitTest.java @@ -0,0 +1,43 @@ +package com.baledung.billpugh; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class BillPughSingletonUnitTest { + Logger logger = LoggerFactory.getLogger(BillPughSingletonUnitTest.class); + @Test + void giveSynchronizedLazyLoadedImpl_whenCallgetInstance_thenReturnSingleton() { + Set setHoldingSingletonObj = new HashSet<>(); + List> futures = new ArrayList<>(); + + ExecutorService executorService = Executors.newFixedThreadPool(10); + Callable runnableTask = () -> { + logger.info("run called for:" + Thread.currentThread().getName()); + return BillPughSingleton.getInstance(); + }; + + int count = 0; + while(count < 10) { + futures.add(executorService.submit(runnableTask)); + count++; + } + futures.forEach(e -> { + try { + setHoldingSingletonObj.add(e.get()); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + }); + executorService.shutdown(); + assertEquals(1, setHoldingSingletonObj.size()); + } +} diff --git a/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/EagerLoadedSingletonUnitTest.java b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/EagerLoadedSingletonUnitTest.java new file mode 100644 index 0000000000..fd65ff6c5b --- /dev/null +++ b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/EagerLoadedSingletonUnitTest.java @@ -0,0 +1,46 @@ +package com.baledung.billpugh; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class EagerLoadedSingletonUnitTest { + + Logger logger = LoggerFactory.getLogger(EagerLoadedSingletonUnitTest.class); + + @Test + void giveEagerLoadedImpl_whenCallgetInstance_thenReturnSingleton() { + Set set = new HashSet<>(); + List> futures = new ArrayList<>(); + + ExecutorService executorService = Executors.newFixedThreadPool(10); + Callable runnableTask = () -> { + logger.info("run called for:" + Thread.currentThread().getName()); + return EagerLoadedSingleton.getInstance(); + }; + + int count = 0; + while(count < 10) { + futures.add(executorService.submit(runnableTask)); + count++; + } + futures.forEach(e -> { + try { + set.add(e.get()); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + }); + executorService.shutdown(); + assertEquals(1, set.size()); + } + +} diff --git a/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/LazyLoadedSingletonUnitTest.java b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/LazyLoadedSingletonUnitTest.java new file mode 100644 index 0000000000..0e0ea25779 --- /dev/null +++ b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/LazyLoadedSingletonUnitTest.java @@ -0,0 +1,17 @@ +package com.baledung.billpugh; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +public class LazyLoadedSingletonUnitTest { + + @Test + void givenLazyLoadedImpl_whenCallGetInstance_thenReturnSingleInstance() throws ClassNotFoundException { + Class bs = Class.forName("com.baledung.billpugh.LazyLoadedSingleton"); + assertThrows(IllegalAccessException.class, () -> bs.getDeclaredConstructor().newInstance()); + + LazyLoadedSingleton lazyLoadedSingletonObj1 = LazyLoadedSingleton.getInstance(); + LazyLoadedSingleton lazyLoadedSingletonObj2 = LazyLoadedSingleton.getInstance(); + assertEquals(lazyLoadedSingletonObj1.hashCode(), lazyLoadedSingletonObj2.hashCode()); + } +} diff --git a/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/SynchronizedLazyLoadedSingletonUnitTest.java b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/SynchronizedLazyLoadedSingletonUnitTest.java new file mode 100644 index 0000000000..1f1636b458 --- /dev/null +++ b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/SynchronizedLazyLoadedSingletonUnitTest.java @@ -0,0 +1,44 @@ +package com.baledung.billpugh; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class SynchronizedLazyLoadedSingletonUnitTest { + Logger logger = LoggerFactory.getLogger(SynchronizedLazyLoadedSingletonUnitTest.class); + @Test + void giveSynchronizedLazyLoadedImpl_whenCallgetInstance_thenReturnSingleton() { + Set setHoldingSingletonObj = new HashSet<>(); + List> futures = new ArrayList<>(); + + ExecutorService executorService = Executors.newFixedThreadPool(10); + Callable runnableTask = () -> { + logger.info("run called for:" + Thread.currentThread().getName()); + return SynchronizedLazyLoadedSingleton.getInstance(); + }; + + int count = 0; + while(count < 10) { + futures.add(executorService.submit(runnableTask)); + count++; + } + futures.forEach(e -> { + try { + setHoldingSingletonObj.add(e.get()); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + }); + executorService.shutdown(); + assertEquals(1, setHoldingSingletonObj.size()); + } + +} From 4596614dc9721bc246c587f35092c86330a92629 Mon Sep 17 00:00:00 2001 From: Niket Agrawal Date: Sun, 29 Oct 2023 01:42:22 +0530 Subject: [PATCH 044/233] Initial Commit --- .../core-java-persistence-3/pom.xml | 35 ++++++ .../ResultSetToMapUnitTest.java | 105 ++++++++++++++++++ persistence-modules/pom.xml | 1 + 3 files changed, 141 insertions(+) create mode 100644 persistence-modules/core-java-persistence-3/pom.xml create mode 100644 persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java diff --git a/persistence-modules/core-java-persistence-3/pom.xml b/persistence-modules/core-java-persistence-3/pom.xml new file mode 100644 index 0000000000..6868da27be --- /dev/null +++ b/persistence-modules/core-java-persistence-3/pom.xml @@ -0,0 +1,35 @@ + + 4.0.0 + com.baeldung.core-java-persistence-3 + core-java-persistence-3 + core-java-persistence-3 + 0.1.0-SNAPSHOT + jar + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + com.h2database + h2 + ${h2.version} + + + org.springframework + spring-jdbc + ${spring-jdbc.version} + + + commons-dbutils + commons-dbutils + ${commons-dbutils.version} + + + + 2.1.214 + 5.3.29 + 1.8.1 + + \ No newline at end of file diff --git a/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java b/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java new file mode 100644 index 0000000000..b483cc04c9 --- /dev/null +++ b/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung.resultsettomap; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.dbutils.QueryRunner; +import org.apache.commons.dbutils.ResultSetHandler; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ResultSetToMapUnitTest { + private static Connection connection = null; + private static final String JDBC_URL = "jdbc:h2:mem:testDatabase"; + private static final String USERNAME = "dbUser"; + private static final String PASSWORD = "dbPassword"; + + @Before + public void setup() throws Exception { + connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD); + initialDataSetup(); + } + + private void initialDataSetup() throws SQLException { + Statement statement = connection.createStatement(); + String sql = "CREATE TABLE EMPLOYEE (empId INTEGER not null, empName VARCHAR(50), empCity VARCHAR(50), PRIMARY KEY (empId))"; + statement.executeUpdate(sql); + List sqlQueryList = Arrays.asList("INSERT INTO EMPLOYEE VALUES (1, 'Steve','London')", "INSERT INTO EMPLOYEE VALUES (2, 'John','London')", "INSERT INTO EMPLOYEE VALUES (3, 'David', 'Sydney')", + "INSERT INTO EMPLOYEE VALUES (4, 'Kevin','London')", "INSERT INTO EMPLOYEE VALUES (5, 'Jade', 'Sydney')"); + for (String query : sqlQueryList) { + statement.executeUpdate(query); + } + } + + @Test + public void whenUsingNativeJava_thenConvertResultSetToMap() throws SQLException { + ResultSet resultSet = connection.prepareStatement("SELECT * FROM EMPLOYEE") + .executeQuery(); + Map> valueMap = new HashMap<>(); + + while (resultSet.next()) { + String empCity = resultSet.getString("empCity"); + String empName = resultSet.getString("empName"); + if (!valueMap.containsKey(empCity)) { + valueMap.putIfAbsent(empCity, new ArrayList<>()); + } + valueMap.get(empCity) + .add(empName); + } + assertEquals(3, valueMap.get("London") + .size()); + } + + @Test + public void whenUsingLambda_thenConvertResultSetToMap() throws SQLException { + ResultSet resultSet = connection.prepareStatement("SELECT * FROM EMPLOYEE") + .executeQuery(); + Map> valueMap = new HashMap<>(); + + while (resultSet.next()) { + String empCity = resultSet.getString("empCity"); + String empName = resultSet.getString("empName"); + valueMap.computeIfAbsent(empCity, data -> new ArrayList<>()) + .add(empName); + } + assertEquals(3, valueMap.get("London") + .size()); + } + + @Test + public void whenUsingDbUtils_thenConvertResultSetToMap() throws SQLException { + + ResultSetHandler>> handler = new ResultSetHandler>>() { + public Map> handle(ResultSet resultSet) throws SQLException { + Map> result = new HashMap<>(); + while (resultSet.next()) { + String empCity = resultSet.getString("empCity"); + String empName = resultSet.getString("empName"); + result.computeIfAbsent(empCity, data -> new ArrayList<>()) + .add(empName); + } + return result; + } + }; + QueryRunner run = new QueryRunner(); + Map> valueMap = run.query(connection, "SELECT * FROM EMPLOYEE", handler); + assertEquals(3, valueMap.get("London") + .size()); + } + + @After + public void preDestroy() throws Exception { + connection.close(); + } +} diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index a99a180390..162894f1e0 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -21,6 +21,7 @@ blaze-persistence core-java-persistence core-java-persistence-2 + core-java-persistence-3 elasticsearch flyway flyway-repair From 6d2e874c264e67437078e9506e19dca6f0c181a9 Mon Sep 17 00:00:00 2001 From: Niket Agrawal Date: Sun, 29 Oct 2023 01:46:23 +0530 Subject: [PATCH 045/233] Updated Pom --- persistence-modules/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 53e408c3a5..9c150a28d7 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -21,6 +21,7 @@ blaze-persistence core-java-persistence core-java-persistence-2 + core-java-persistence-3 couchbase elasticsearch flyway From 832584c68cdeadbb14cf17ee11ca215bfa4bfb40 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Tue, 31 Oct 2023 20:37:18 +0530 Subject: [PATCH 046/233] JAVA-26280 Improve libraries-testing module build time --- .../{SmurfsArchUnitTest.java => SmurfsArchManualTest.java} | 2 +- ...erStatusIntegrationTest.java => MemberStatusManualTest.java} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename libraries-testing/src/test/java/com/baeldung/archunit/smurfs/{SmurfsArchUnitTest.java => SmurfsArchManualTest.java} (98%) rename libraries-testing/src/test/java/com/baeldung/serenity/{MemberStatusIntegrationTest.java => MemberStatusManualTest.java} (98%) diff --git a/libraries-testing/src/test/java/com/baeldung/archunit/smurfs/SmurfsArchUnitTest.java b/libraries-testing/src/test/java/com/baeldung/archunit/smurfs/SmurfsArchManualTest.java similarity index 98% rename from libraries-testing/src/test/java/com/baeldung/archunit/smurfs/SmurfsArchUnitTest.java rename to libraries-testing/src/test/java/com/baeldung/archunit/smurfs/SmurfsArchManualTest.java index 9724c2bcae..7db104bd57 100644 --- a/libraries-testing/src/test/java/com/baeldung/archunit/smurfs/SmurfsArchUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/archunit/smurfs/SmurfsArchManualTest.java @@ -14,7 +14,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; -public class SmurfsArchUnitTest { +public class SmurfsArchManualTest { @Test public void givenPresentationLayerClasses_thenWrongCheckFails() { diff --git a/libraries-testing/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java b/libraries-testing/src/test/java/com/baeldung/serenity/MemberStatusManualTest.java similarity index 98% rename from libraries-testing/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java rename to libraries-testing/src/test/java/com/baeldung/serenity/MemberStatusManualTest.java index e95b63aa96..ec5346d27b 100644 --- a/libraries-testing/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java +++ b/libraries-testing/src/test/java/com/baeldung/serenity/MemberStatusManualTest.java @@ -14,7 +14,7 @@ import static com.baeldung.serenity.membership.MemberGrade.Gold; import static com.baeldung.serenity.membership.MemberGrade.Silver; @RunWith(SerenityRunner.class) -public class MemberStatusIntegrationTest { +public class MemberStatusManualTest { @Steps private MemberStatusSteps memberSteps; From feca50daca29d74b161e7ccb6fff6bde710f01e6 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Tue, 31 Oct 2023 20:17:39 -0400 Subject: [PATCH 047/233] Incorporated review comments --- .../baeldung/kafka/message/ordering/Config.java | 3 +++ .../ordering/ExtSeqWithTimeWindowConsumer.java | 6 +++--- .../ordering/ExtSeqWithTimeWindowProducer.java | 12 ++++++++---- .../message/ordering/MultiPartitionConsumer.java | 9 +++++---- .../message/ordering/MultiPartitionProducer.java | 14 +++++++++----- .../message/ordering/ProducerConfigurations.java | 2 +- .../message/ordering/SinglePartitionConsumer.java | 6 +++--- .../message/ordering/SinglePartitionProducer.java | 14 +++++++++----- 8 files changed, 41 insertions(+), 25 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java index 2635e72431..12acfecf51 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java @@ -2,4 +2,7 @@ package com.baeldung.kafka.message.ordering; public class Config { public static final String CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS = "value.deserializer.serializedClass"; + public static final String KAFKA_LOCAL = "localhost:9092"; + public static final String MULTI_PARTITION_TOPIC = "multi_partition_topic"; + public static final String SINGLE_PARTITION_TOPIC = "single_partition_topic"; } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java index 639a980462..06cb7104b7 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java @@ -17,14 +17,14 @@ public class ExtSeqWithTimeWindowConsumer { public static void main(String[] args) { Properties props = new Properties(); - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); Consumer consumer = new KafkaConsumer<>(props); - consumer.subscribe(Collections.singletonList("multi_partition_topic")); + consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); List buffer = new ArrayList<>(); long lastProcessedTime = System.nanoTime(); while (true) { @@ -42,7 +42,7 @@ public class ExtSeqWithTimeWindowConsumer { private static void processBuffer(List buffer) { Collections.sort(buffer); buffer.forEach(userEvent -> { - System.out.println("Processing message with Global Sequence number: " + userEvent.getGlobalSequenceNumber() + ", event nano time : " + userEvent.getEventNanoTime()); + System.out.println("Processing message with Global Sequence number: " + userEvent.getGlobalSequenceNumber() + ", User Event Id: " + userEvent.getUserEventId()); }); buffer.clear(); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java index c18e35b351..73a62c0bf2 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java @@ -5,15 +5,18 @@ import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.serialization.LongSerializer; import java.util.Properties; import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; public class ExtSeqWithTimeWindowProducer { - public static void main(String[] args) { + public static void main(String[] args) throws ExecutionException, InterruptedException { Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); KafkaProducer producer = new KafkaProducer<>(props); @@ -21,8 +24,9 @@ public class ExtSeqWithTimeWindowProducer { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); userEvent.setEventNanoTime(System.nanoTime()); userEvent.setGlobalSequenceNumber(sequenceNumber); - producer.send(new ProducerRecord<>("multi_partition_topic", sequenceNumber, userEvent)); - System.out.println("User Event Nano time : " + userEvent.getEventNanoTime() + ", User Event Id: " + userEvent.getUserEventId()); + Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, sequenceNumber, userEvent)); + RecordMetadata metadata = future.get(); + System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } producer.close(); System.out.println("ExternalSequencingProducer Completed."); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java index e738832425..82f05cc80e 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java @@ -14,22 +14,23 @@ import java.util.Properties; public class MultiPartitionConsumer { private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(100); + public static void main(String[] args) { Properties props = new Properties(); - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); + props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); Consumer consumer = new KafkaConsumer<>(props); - consumer.subscribe(Collections.singletonList("multi_partition_topic")); + consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); while (true) { ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { UserEvent userEvent = record.value(); if (userEvent != null) { - System.out.println("Process message with event nano time : " + userEvent.getEventNanoTime() + ", Event ID: " + userEvent.getUserEventId()); + System.out.println("User Event ID: " + userEvent.getUserEventId()); } }); } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java index db02c87bbe..52da49ab80 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java @@ -5,25 +5,29 @@ import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.serialization.LongSerializer; import java.util.Properties; import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; public class MultiPartitionProducer { - public static void main(String[] args) { + public static void main(String[] args) throws ExecutionException, InterruptedException { Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); KafkaProducer producer = new KafkaProducer<>(props); for (long count = 1; count <= 10 ; count++) { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); userEvent.setEventNanoTime(System.nanoTime()); - producer.send(new ProducerRecord<>("multi_partition_topic", count, userEvent)); - System.out.println("Process message with Event ID: " + userEvent.getUserEventId()); + Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, count, userEvent)); + RecordMetadata metadata = future.get(); + System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } producer.close(); - System.out.println("SinglePartitionProducer Completed."); + System.out.println("MultiPartitionProducer Completed."); } } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index 0eb563910e..61c9cb48aa 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -10,7 +10,7 @@ import java.util.Properties; public class ProducerConfigurations { public static void main(String[] args) { Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1"); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java index 5f5ce86924..1c50f3cf7a 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java @@ -17,19 +17,19 @@ public class SinglePartitionConsumer { public static void main(String[] args) { Properties props = new Properties(); - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); Consumer consumer = new KafkaConsumer<>(props); - consumer.subscribe(Collections.singletonList("single_partition_topic")); + consumer.subscribe(Collections.singletonList(Config.SINGLE_PARTITION_TOPIC)); while (true) { ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { UserEvent userEvent = record.value(); - System.out.println("Process message with event nano time : " + userEvent.getEventNanoTime() + ", Event ID: " + userEvent.getUserEventId()); + System.out.println("User Event ID: " + userEvent.getUserEventId()); }); } } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java index 2a7719e34f..9306abaebf 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java @@ -5,24 +5,28 @@ import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.serialization.LongSerializer; import java.time.Instant; import java.util.Properties; import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; public class SinglePartitionProducer { - public static void main(String[] args) { + public static void main(String[] args) throws ExecutionException, InterruptedException { Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); KafkaProducer producer = new KafkaProducer<>(props); - for (long count = 1; count <= 10 ; count++) { + for (long count = 1; count <= 10; count++) { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); userEvent.setEventNanoTime(System.nanoTime()); - producer.send(new ProducerRecord<>("single_partition_topic", count, userEvent)); - System.out.println("Process message with Event ID: " + userEvent.getUserEventId()); + Future future = producer.send(new ProducerRecord<>(Config.SINGLE_PARTITION_TOPIC, count, userEvent)); + RecordMetadata metadata = future.get(); + System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } producer.close(); System.out.println("SinglePartitionProducer Completed."); From 88f85963bb1614a10025cadb123ab5b26bc2b489 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Tue, 31 Oct 2023 22:04:32 -0400 Subject: [PATCH 048/233] Config changes --- .../kafka/message/ordering/ConsumerConfigurations.java | 4 ++-- .../kafka/message/ordering/ProducerConfigurations.java | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java index 15562cfcef..5b5a1f8e0b 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java @@ -16,7 +16,7 @@ import java.util.Properties; public class ConsumerConfigurations { public static void main(String[] args) { Properties props = new Properties(); - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); @@ -24,7 +24,7 @@ public class ConsumerConfigurations { props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, "1"); props.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, "500"); Consumer consumer = new KafkaConsumer<>(props); - consumer.subscribe(Collections.singletonList("multi_partition_topic")); + consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); while (true) { ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java index 61c9cb48aa..79fc42be3d 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java @@ -16,14 +16,15 @@ public class ProducerConfigurations { props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1"); props.put(ProducerConfig.BATCH_SIZE_CONFIG, "16384"); props.put(ProducerConfig.LINGER_MS_CONFIG, "5"); + props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true"); KafkaProducer producer = new KafkaProducer<>(props); for (int i = 0; i < 10; i++) { - String key = "Key-" + (i % 3); // Assuming 3 partitions - producer.send(new ProducerRecord<>("multi_partition_topic", key, "Message-" + i)); + String key = "Key-" + (i % 5); // Assuming 5 partitions + producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, key, "Message-" + i)); } producer.close(); - System.out.println("MultiPartitionProducer Completed."); + System.out.println("Producer Configurations Completed."); } } From a5d58617e2aac4e7605914a3f771d1a6617d9e7f Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Thu, 2 Nov 2023 20:21:59 +0530 Subject: [PATCH 049/233] BAEL-7177 Modifying Objects within Stream while iterating --- .../modifystream/entity/ImmutablePerson.java | 25 ++++ .../baledung/modifystream/entity/Person.java | 27 ++++ .../modifystream/ModifyStreamUnitTest.java | 140 ++++++++++++++++++ 3 files changed, 192 insertions(+) create mode 100644 core-java-modules/core-java-streams-5/src/main/java/com/baledung/modifystream/entity/ImmutablePerson.java create mode 100644 core-java-modules/core-java-streams-5/src/main/java/com/baledung/modifystream/entity/Person.java create mode 100644 core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baledung/modifystream/entity/ImmutablePerson.java b/core-java-modules/core-java-streams-5/src/main/java/com/baledung/modifystream/entity/ImmutablePerson.java new file mode 100644 index 0000000000..bb7f3b8eb3 --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/main/java/com/baledung/modifystream/entity/ImmutablePerson.java @@ -0,0 +1,25 @@ +package com.baledung.modifystream.entity; + +public class ImmutablePerson { + + private String name; + private String email; + + public ImmutablePerson(String name, String email) { + this.name = name; + this.email = email; + } + + public ImmutablePerson withEmail(String email) { + + return new ImmutablePerson(this.name, email); + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } +} diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baledung/modifystream/entity/Person.java b/core-java-modules/core-java-streams-5/src/main/java/com/baledung/modifystream/entity/Person.java new file mode 100644 index 0000000000..c82c159059 --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/main/java/com/baledung/modifystream/entity/Person.java @@ -0,0 +1,27 @@ +package com.baledung.modifystream.entity; + +public class Person { + private String name; + private String email; + + public Person(String name, String email) { + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java new file mode 100644 index 0000000000..72183ec94a --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java @@ -0,0 +1,140 @@ +package com.baeldung.modifystream; + +import com.baledung.modifystream.entity.ImmutablePerson; +import com.baledung.modifystream.entity.Person; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.ConcurrentModificationException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class ModifyStreamUnitTest { + Logger logger = LoggerFactory.getLogger(ModifyStreamUnitTest.class); + List personLst = new ArrayList(); + List immutablePersonList = new ArrayList(); + + @BeforeEach + void prepare() { + Person person1 = new Person("John", "john@gmail.com"); + Person person2 = new Person("Peter", "peter@gmail.com"); + Person person3 = new Person("Mary", "mary@gmail.com"); + Person person4 = new Person("William", "william@gmail.com"); + + personLst.add(person1); + personLst.add(person2); + personLst.add(person3); + personLst.add(person4); + } + + @BeforeEach + void prepareImmutablePerson() { + ImmutablePerson immutablePerson1 = new ImmutablePerson("John", "john@gmail.com"); + ImmutablePerson immutablePerson2 = new ImmutablePerson("Peter", "peter@gmail.com"); + ImmutablePerson immutablePerson3 = new ImmutablePerson("Mary", "mary@gmail.com"); + ImmutablePerson immutablePerson4 = new ImmutablePerson("William", "william@gmail.com"); + + immutablePersonList.add(immutablePerson1); + immutablePersonList.add(immutablePerson2); + immutablePersonList.add(immutablePerson3); + immutablePersonList.add(immutablePerson4); + } + + @Test + void givenPersonLst_whenRemoveWhileIterating_thenThrowException() { + assertThrows(NullPointerException.class, () -> { + personLst.stream().forEach(e -> { + if(e.getName().equals("John")) { + personLst.remove(e); + } + }); + }); + } + + @Test + void givenPersonLst_whenRemoveWhileIteratingWithForEach_thenThrowException() { + assertThrows(ConcurrentModificationException.class, () -> { + personLst.forEach(e -> { + if(e.getName().equals("John")) { + personLst.remove(e); + } + }); + }); + } + + @Test + void givenPersonLst_whenRemoveWhileIterating_thenPersonRemoved() { + assertEquals(4, personLst.size()); + + CopyOnWriteArrayList cps = new CopyOnWriteArrayList<>(personLst); + cps.stream().forEach(e -> { + if(e.getName().equals("John")) { + cps.remove(e); + } + }); + + assertEquals(3, cps.size()); + } + + + @Test + void givenPersonLst_whenRemovePersonWithFilter_thenPersonRemoved() { + assertEquals(4, personLst.size()); + + List newPersonLst = personLst.stream() + .filter(e -> !e.getName().equals("John")) + .collect(Collectors.toList()); + + assertEquals(3, newPersonLst.size()); + } + + @Test + void givenPersonLst_whenRemovePersonWithRemoveIf_thenPersonRemoved() { + assertEquals(4, personLst.size()); + + personLst.removeIf(e -> e.getName().equals("John")); + + assertEquals(3, personLst.size()); + } + + @Test + void givenPersonLst_whenUpdatePersonEmailByInterferingWithForEach_thenPersonEmailUpdated() { + personLst.stream().forEach(e -> e.setEmail(e.getEmail().toUpperCase())); + + personLst.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); + } + + @Test + void givenPersonLst_whenUpdatePersonEmailWithMapMethod_thenPersonEmailUpdated() { + List newPersonLst = personLst.stream() + .map(e -> new Person(e.getName(), e.getEmail().toUpperCase())) + .collect(Collectors.toList()); + + newPersonLst.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); + } + + @Test + void givenPersonLst_whenUpdateImmutablePersonEmailWithMapMethod_thenPersonEmailUpdated() { + List newImmutablePersonLst = immutablePersonList.stream() + .map(e -> e.withEmail(e.getEmail().toUpperCase())) + .collect(Collectors.toList()); + + newImmutablePersonLst.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); + } + @Test + void givenPersonLst_whenUpdatePersonEmailByInterferingWithPeek_thenPersonEmailUpdated() { + personLst.stream() + .peek(e -> e.setEmail(e.getEmail().toUpperCase())) + .collect(Collectors.toList()); + + personLst.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); + } + +} From aa2701442567f6efc2a50ef095ef449b836546eb Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Thu, 2 Nov 2023 23:12:45 +0530 Subject: [PATCH 050/233] BAEL-7177 Modifying Objects within Stream while iterating --- .../modifystream/ModifyStreamUnitTest.java | 68 +++++++++---------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java index 72183ec94a..f5fab408b8 100644 --- a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java @@ -18,7 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; public class ModifyStreamUnitTest { Logger logger = LoggerFactory.getLogger(ModifyStreamUnitTest.class); - List personLst = new ArrayList(); + List personList = new ArrayList(); List immutablePersonList = new ArrayList(); @BeforeEach @@ -28,10 +28,10 @@ public class ModifyStreamUnitTest { Person person3 = new Person("Mary", "mary@gmail.com"); Person person4 = new Person("William", "william@gmail.com"); - personLst.add(person1); - personLst.add(person2); - personLst.add(person3); - personLst.add(person4); + personList.add(person1); + personList.add(person2); + personList.add(person3); + personList.add(person4); } @BeforeEach @@ -48,32 +48,32 @@ public class ModifyStreamUnitTest { } @Test - void givenPersonLst_whenRemoveWhileIterating_thenThrowException() { + void givenPersonList_whenRemoveWhileIterating_thenThrowException() { assertThrows(NullPointerException.class, () -> { - personLst.stream().forEach(e -> { + personList.stream().forEach(e -> { if(e.getName().equals("John")) { - personLst.remove(e); + personList.remove(e); } }); }); } @Test - void givenPersonLst_whenRemoveWhileIteratingWithForEach_thenThrowException() { + void givenPersonList_whenRemoveWhileIteratingWithForEach_thenThrowException() { assertThrows(ConcurrentModificationException.class, () -> { - personLst.forEach(e -> { + personList.forEach(e -> { if(e.getName().equals("John")) { - personLst.remove(e); + personList.remove(e); } }); }); } @Test - void givenPersonLst_whenRemoveWhileIterating_thenPersonRemoved() { - assertEquals(4, personLst.size()); + void givenPersonList_whenRemoveWhileIterating_thenPersonRemoved() { + assertEquals(4, personList.size()); - CopyOnWriteArrayList cps = new CopyOnWriteArrayList<>(personLst); + CopyOnWriteArrayList cps = new CopyOnWriteArrayList<>(personList); cps.stream().forEach(e -> { if(e.getName().equals("John")) { cps.remove(e); @@ -85,56 +85,56 @@ public class ModifyStreamUnitTest { @Test - void givenPersonLst_whenRemovePersonWithFilter_thenPersonRemoved() { - assertEquals(4, personLst.size()); + void givenPersonList_whenRemovePersonWithFilter_thenPersonRemoved() { + assertEquals(4, personList.size()); - List newPersonLst = personLst.stream() + List newPersonList = personList.stream() .filter(e -> !e.getName().equals("John")) .collect(Collectors.toList()); - assertEquals(3, newPersonLst.size()); + assertEquals(3, newPersonList.size()); } @Test - void givenPersonLst_whenRemovePersonWithRemoveIf_thenPersonRemoved() { - assertEquals(4, personLst.size()); + void givenPersonList_whenRemovePersonWithRemoveIf_thenPersonRemoved() { + assertEquals(4, personList.size()); - personLst.removeIf(e -> e.getName().equals("John")); + personList.removeIf(e -> e.getName().equals("John")); - assertEquals(3, personLst.size()); + assertEquals(3, personList.size()); } @Test - void givenPersonLst_whenUpdatePersonEmailByInterferingWithForEach_thenPersonEmailUpdated() { - personLst.stream().forEach(e -> e.setEmail(e.getEmail().toUpperCase())); + void givenPersonList_whenUpdatePersonEmailByInterferingWithForEach_thenPersonEmailUpdated() { + personList.stream().forEach(e -> e.setEmail(e.getEmail().toUpperCase())); - personLst.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); + personList.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); } @Test - void givenPersonLst_whenUpdatePersonEmailWithMapMethod_thenPersonEmailUpdated() { - List newPersonLst = personLst.stream() + void givenPersonList_whenUpdatePersonEmailWithMapMethod_thenPersonEmailUpdated() { + List newPersonList = personList.stream() .map(e -> new Person(e.getName(), e.getEmail().toUpperCase())) .collect(Collectors.toList()); - newPersonLst.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); + newPersonList.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); } @Test - void givenPersonLst_whenUpdateImmutablePersonEmailWithMapMethod_thenPersonEmailUpdated() { - List newImmutablePersonLst = immutablePersonList.stream() + void givenPersonList_whenUpdateImmutablePersonEmailWithMapMethod_thenPersonEmailUpdated() { + List newImmutablePersonList = immutablePersonList.stream() .map(e -> e.withEmail(e.getEmail().toUpperCase())) .collect(Collectors.toList()); - newImmutablePersonLst.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); + newImmutablePersonList.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); } @Test - void givenPersonLst_whenUpdatePersonEmailByInterferingWithPeek_thenPersonEmailUpdated() { - personLst.stream() + void givenPersonList_whenUpdatePersonEmailByInterferingWithPeek_thenPersonEmailUpdated() { + personList.stream() .peek(e -> e.setEmail(e.getEmail().toUpperCase())) .collect(Collectors.toList()); - personLst.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); + personList.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); } } From 3fe81a3e075ae05044038788b23fa8729115f734 Mon Sep 17 00:00:00 2001 From: Niket Agrawal Date: Fri, 3 Nov 2023 03:49:06 +0530 Subject: [PATCH 051/233] Formatting changes --- .../core-java-persistence-3/pom.xml | 6 --- .../ResultSetToMapUnitTest.java | 44 ++++++++----------- 2 files changed, 19 insertions(+), 31 deletions(-) diff --git a/persistence-modules/core-java-persistence-3/pom.xml b/persistence-modules/core-java-persistence-3/pom.xml index 6868da27be..26ac2a5218 100644 --- a/persistence-modules/core-java-persistence-3/pom.xml +++ b/persistence-modules/core-java-persistence-3/pom.xml @@ -16,11 +16,6 @@ h2 ${h2.version} - - org.springframework - spring-jdbc - ${spring-jdbc.version} - commons-dbutils commons-dbutils @@ -29,7 +24,6 @@ 2.1.214 - 5.3.29 1.8.1 \ No newline at end of file diff --git a/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java b/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java index b483cc04c9..c8a6351804 100644 --- a/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java +++ b/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java @@ -33,48 +33,43 @@ public class ResultSetToMapUnitTest { private void initialDataSetup() throws SQLException { Statement statement = connection.createStatement(); - String sql = "CREATE TABLE EMPLOYEE (empId INTEGER not null, empName VARCHAR(50), empCity VARCHAR(50), PRIMARY KEY (empId))"; - statement.executeUpdate(sql); - List sqlQueryList = Arrays.asList("INSERT INTO EMPLOYEE VALUES (1, 'Steve','London')", "INSERT INTO EMPLOYEE VALUES (2, 'John','London')", "INSERT INTO EMPLOYEE VALUES (3, 'David', 'Sydney')", - "INSERT INTO EMPLOYEE VALUES (4, 'Kevin','London')", "INSERT INTO EMPLOYEE VALUES (5, 'Jade', 'Sydney')"); + String ddlQuery = "CREATE TABLE employee (empId INTEGER not null, empName VARCHAR(50), empCity VARCHAR(50), PRIMARY KEY (empId))"; + statement.execute(ddlQuery); + List sqlQueryList = Arrays.asList("INSERT INTO employee VALUES (1, 'Steve','London')", "INSERT INTO employee VALUES (2, 'John','London')", "INSERT INTO employee VALUES (3, 'David', 'Sydney')", + "INSERT INTO employee VALUES (4, 'Kevin','London')", "INSERT INTO employee VALUES (5, 'Jade', 'Sydney')"); + for (String query : sqlQueryList) { - statement.executeUpdate(query); + statement.execute(query); } } @Test - public void whenUsingNativeJava_thenConvertResultSetToMap() throws SQLException { - ResultSet resultSet = connection.prepareStatement("SELECT * FROM EMPLOYEE") - .executeQuery(); + public void whenUsingContainsKey_thenConvertResultSetToMap() throws SQLException { + ResultSet resultSet = connection.prepareStatement("SELECT * FROM employee").executeQuery(); Map> valueMap = new HashMap<>(); while (resultSet.next()) { String empCity = resultSet.getString("empCity"); String empName = resultSet.getString("empName"); if (!valueMap.containsKey(empCity)) { - valueMap.putIfAbsent(empCity, new ArrayList<>()); + valueMap.put(empCity, new ArrayList<>()); } - valueMap.get(empCity) - .add(empName); + valueMap.get(empCity).add(empName); } - assertEquals(3, valueMap.get("London") - .size()); + assertEquals(3, valueMap.get("London").size()); } @Test - public void whenUsingLambda_thenConvertResultSetToMap() throws SQLException { - ResultSet resultSet = connection.prepareStatement("SELECT * FROM EMPLOYEE") - .executeQuery(); + public void whenUsingComputeIfAbsent_thenConvertResultSetToMap() throws SQLException { + ResultSet resultSet = connection.prepareStatement("SELECT * FROM employee").executeQuery(); Map> valueMap = new HashMap<>(); while (resultSet.next()) { String empCity = resultSet.getString("empCity"); String empName = resultSet.getString("empName"); - valueMap.computeIfAbsent(empCity, data -> new ArrayList<>()) - .add(empName); + valueMap.computeIfAbsent(empCity, data -> new ArrayList<>()).add(empName); } - assertEquals(3, valueMap.get("London") - .size()); + assertEquals(3, valueMap.get("London").size()); } @Test @@ -86,16 +81,15 @@ public class ResultSetToMapUnitTest { while (resultSet.next()) { String empCity = resultSet.getString("empCity"); String empName = resultSet.getString("empName"); - result.computeIfAbsent(empCity, data -> new ArrayList<>()) - .add(empName); + result.computeIfAbsent(empCity, data -> new ArrayList<>()).add(empName); } return result; } }; + QueryRunner run = new QueryRunner(); - Map> valueMap = run.query(connection, "SELECT * FROM EMPLOYEE", handler); - assertEquals(3, valueMap.get("London") - .size()); + Map> valueMap = run.query(connection, "SELECT * FROM employee", handler); + assertEquals(3, valueMap.get("London").size()); } @After From b7d743c62973913c244eed64befca97b45c6c8ee Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 2 Nov 2023 19:40:36 -0400 Subject: [PATCH 052/233] Incorporated Review comments --- .../kafka/message/ordering/Config.java | 5 +- .../ordering/ConsumerConfigurations.java | 36 -------------- .../ExtSeqWithTimeWindowConsumer.java | 49 ------------------- .../ExtSeqWithTimeWindowProducer.java | 34 ------------- .../ordering/MultiPartitionConsumer.java | 39 --------------- .../ordering/MultiPartitionProducer.java | 33 ------------- .../ordering/ProducerConfigurations.java | 30 ------------ .../ordering/SinglePartitionConsumer.java | 37 -------------- .../ordering/SinglePartitionProducer.java | 35 ------------- .../ExtSeqWithTimeWindowIntegrationTest.java | 16 +++--- .../MultiplePartitionIntegrationTest.java | 15 +++--- .../SinglePartitionIntegrationTest.java | 15 +++--- 12 files changed, 25 insertions(+), 319 deletions(-) delete mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java delete mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java delete mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java delete mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java delete mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java delete mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java delete mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java delete mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java index 12acfecf51..9cc6314309 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java @@ -2,7 +2,10 @@ package com.baeldung.kafka.message.ordering; public class Config { public static final String CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS = "value.deserializer.serializedClass"; - public static final String KAFKA_LOCAL = "localhost:9092"; public static final String MULTI_PARTITION_TOPIC = "multi_partition_topic"; public static final String SINGLE_PARTITION_TOPIC = "single_partition_topic"; + + public static final int MULTIPLE_PARTITIONS = 5; + public static final int SINGLE_PARTITION = 1; + public static short REPLICATION_FACTOR = 1; } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java deleted file mode 100644 index 5b5a1f8e0b..0000000000 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ConsumerConfigurations.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.kafka.message.ordering; - -import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; -import org.apache.kafka.clients.consumer.Consumer; -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.common.serialization.StringDeserializer; -import org.apache.kafka.common.serialization.StringSerializer; - -import java.time.Duration; -import java.util.Collections; -import java.util.Properties; - -public class ConsumerConfigurations { - public static void main(String[] args) { - Properties props = new Properties(); - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); - props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); - props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "500"); - props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, "1"); - props.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, "500"); - Consumer consumer = new KafkaConsumer<>(props); - consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); - - while (true) { - ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); - records.forEach(record -> { - System.out.println("Partition: " + record.partition() + ", Message: " + record.value()); - }); - } - } -} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java deleted file mode 100644 index 06cb7104b7..0000000000 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowConsumer.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.kafka.message.ordering; - -import com.baeldung.kafka.message.ordering.payload.UserEvent; -import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; -import org.apache.kafka.clients.consumer.Consumer; -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.common.serialization.LongDeserializer; - -import java.time.Duration; -import java.util.*; - -public class ExtSeqWithTimeWindowConsumer { - private static final long BUFFER_PERIOD_NS = 5000L * 1000000; // 5000 milliseconds converted to nanoseconds - private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(100); - - public static void main(String[] args) { - Properties props = new Properties(); - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); - props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); - props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); - Consumer consumer = new KafkaConsumer<>(props); - consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); - List buffer = new ArrayList<>(); - long lastProcessedTime = System.nanoTime(); - while (true) { - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); - records.forEach(record -> { - buffer.add(record.value()); - }); - if (System.nanoTime() - lastProcessedTime > BUFFER_PERIOD_NS) { - processBuffer(buffer); - lastProcessedTime = System.nanoTime(); - } - } - } - - private static void processBuffer(List buffer) { - Collections.sort(buffer); - buffer.forEach(userEvent -> { - System.out.println("Processing message with Global Sequence number: " + userEvent.getGlobalSequenceNumber() + ", User Event Id: " + userEvent.getUserEventId()); - }); - buffer.clear(); - } -} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java deleted file mode 100644 index 73a62c0bf2..0000000000 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowProducer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.kafka.message.ordering; - -import com.baeldung.kafka.message.ordering.payload.UserEvent; -import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.clients.producer.RecordMetadata; -import org.apache.kafka.common.serialization.LongSerializer; - -import java.util.Properties; -import java.util.UUID; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -public class ExtSeqWithTimeWindowProducer { - public static void main(String[] args) throws ExecutionException, InterruptedException { - Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - KafkaProducer producer = new KafkaProducer<>(props); - for (long sequenceNumber = 1; sequenceNumber <= 10 ; sequenceNumber++) { - UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); - userEvent.setEventNanoTime(System.nanoTime()); - userEvent.setGlobalSequenceNumber(sequenceNumber); - Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, sequenceNumber, userEvent)); - RecordMetadata metadata = future.get(); - System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); - } - producer.close(); - System.out.println("ExternalSequencingProducer Completed."); - } -} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java deleted file mode 100644 index 82f05cc80e..0000000000 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionConsumer.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.kafka.message.ordering; - -import com.baeldung.kafka.message.ordering.payload.UserEvent; -import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; -import org.apache.kafka.clients.consumer.Consumer; -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.common.serialization.LongDeserializer; - -import java.time.Duration; -import java.util.Collections; -import java.util.Properties; - -public class MultiPartitionConsumer { - private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(100); - - public static void main(String[] args) { - Properties props = new Properties(); - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); - props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); - props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - Consumer consumer = new KafkaConsumer<>(props); - consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); - while (true) { - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); - records.forEach(record -> { - UserEvent userEvent = record.value(); - if (userEvent != null) { - System.out.println("User Event ID: " + userEvent.getUserEventId()); - } - }); - } - } -} - diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java deleted file mode 100644 index 52da49ab80..0000000000 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/MultiPartitionProducer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.kafka.message.ordering; - -import com.baeldung.kafka.message.ordering.payload.UserEvent; -import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.clients.producer.RecordMetadata; -import org.apache.kafka.common.serialization.LongSerializer; - -import java.util.Properties; -import java.util.UUID; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -public class MultiPartitionProducer { - public static void main(String[] args) throws ExecutionException, InterruptedException { - Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - KafkaProducer producer = new KafkaProducer<>(props); - for (long count = 1; count <= 10 ; count++) { - UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); - userEvent.setEventNanoTime(System.nanoTime()); - Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, count, userEvent)); - RecordMetadata metadata = future.get(); - System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); - } - producer.close(); - System.out.println("MultiPartitionProducer Completed."); - } -} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java deleted file mode 100644 index 79fc42be3d..0000000000 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/ProducerConfigurations.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.kafka.message.ordering; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; - -import java.util.Properties; - -public class ProducerConfigurations { - public static void main(String[] args) { - Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); - props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1"); - props.put(ProducerConfig.BATCH_SIZE_CONFIG, "16384"); - props.put(ProducerConfig.LINGER_MS_CONFIG, "5"); - props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true"); - KafkaProducer producer = new KafkaProducer<>(props); - - for (int i = 0; i < 10; i++) { - String key = "Key-" + (i % 5); // Assuming 5 partitions - producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, key, "Message-" + i)); - } - - producer.close(); - System.out.println("Producer Configurations Completed."); - } -} diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java deleted file mode 100644 index 1c50f3cf7a..0000000000 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionConsumer.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.kafka.message.ordering; - -import com.baeldung.kafka.message.ordering.payload.UserEvent; -import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; -import org.apache.kafka.clients.consumer.Consumer; -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.common.serialization.LongDeserializer; - -import java.time.Duration; -import java.util.Collections; -import java.util.Properties; - -public class SinglePartitionConsumer { - private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(100); - - public static void main(String[] args) { - Properties props = new Properties(); - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); - props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonDeserializer.class.getName()); - props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); - Consumer consumer = new KafkaConsumer<>(props); - consumer.subscribe(Collections.singletonList(Config.SINGLE_PARTITION_TOPIC)); - while (true) { - ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); - records.forEach(record -> { - UserEvent userEvent = record.value(); - System.out.println("User Event ID: " + userEvent.getUserEventId()); - }); - } - } -} - diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java deleted file mode 100644 index 9306abaebf..0000000000 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/SinglePartitionProducer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.kafka.message.ordering; - -import com.baeldung.kafka.message.ordering.payload.UserEvent; -import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.clients.producer.RecordMetadata; -import org.apache.kafka.common.serialization.LongSerializer; - -import java.time.Instant; -import java.util.Properties; -import java.util.UUID; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -public class SinglePartitionProducer { - public static void main(String[] args) throws ExecutionException, InterruptedException { - Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.KAFKA_LOCAL); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - KafkaProducer producer = new KafkaProducer<>(props); - for (long count = 1; count <= 10; count++) { - UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); - userEvent.setEventNanoTime(System.nanoTime()); - Future future = producer.send(new ProducerRecord<>(Config.SINGLE_PARTITION_TOPIC, count, userEvent)); - RecordMetadata metadata = future.get(); - System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); - } - producer.close(); - System.out.println("SinglePartitionProducer Completed."); - } - -} diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java index 5f540d5b50..0535e3c4e6 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.*; @Testcontainers public class ExtSeqWithTimeWindowIntegrationTest { - private static String TOPIC = "multi_partition_topic"; - private static int PARTITIONS = 5; - private static short REPLICATION_FACTOR = 1; + private static Admin admin; private static KafkaProducer producer; private static KafkaConsumer consumer; @@ -65,10 +63,10 @@ public class ExtSeqWithTimeWindowIntegrationTest { producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); List topicList = new ArrayList<>(); - NewTopic newTopic = new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR); + NewTopic newTopic = new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR); topicList.add(newTopic); CreateTopicsResult result = admin.createTopics(topicList); - KafkaFuture future = result.values().get(TOPIC); + KafkaFuture future = result.values().get(Config.MULTI_PARTITION_TOPIC); future.whenComplete((voidResult, exception) -> { if (exception != null) { System.err.println("Error creating the topic: " + exception.getMessage()); @@ -91,14 +89,14 @@ public class ExtSeqWithTimeWindowIntegrationTest { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); userEvent.setEventNanoTime(System.nanoTime()); userEvent.setGlobalSequenceNumber(sequenceNumber); - Future future = producer.send(new ProducerRecord<>(TOPIC, sequenceNumber, userEvent)); + Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, sequenceNumber, userEvent)); sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); - System.out.println("Partition : " + metadata.partition()); + System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } boolean isOrderMaintained = true; - consumer.subscribe(Collections.singletonList(TOPIC)); + consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); List buffer = new ArrayList<>(); long lastProcessedTime = System.nanoTime(); ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); @@ -131,7 +129,7 @@ public class ExtSeqWithTimeWindowIntegrationTest { Collections.sort(buffer); buffer.forEach(userEvent -> { receivedUserEventList.add(userEvent); - System.out.println("Process message with Event ID: " + userEvent.getUserEventId()); + System.out.println("Processing message with Global Sequence number: " + userEvent.getGlobalSequenceNumber() + ", User Event Id: " + userEvent.getUserEventId()); }); buffer.clear(); } diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index d4b88ad06f..bbe9fcf7f8 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.*; @Testcontainers public class MultiplePartitionIntegrationTest { - private static String TOPIC = "multi_partition_topic"; - private static int PARTITIONS = 5; - private static short REPLICATION_FACTOR = 1; + private static Admin admin; private static KafkaProducer producer; private static KafkaConsumer consumer; @@ -63,10 +61,10 @@ public class MultiplePartitionIntegrationTest { producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); List topicList = new ArrayList<>(); - NewTopic newTopic = new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR); + NewTopic newTopic = new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR); topicList.add(newTopic); CreateTopicsResult result = admin.createTopics(topicList); - KafkaFuture future = result.values().get(TOPIC); + KafkaFuture future = result.values().get(Config.MULTI_PARTITION_TOPIC); future.whenComplete((voidResult, exception) -> { if (exception != null) { System.err.println("Error creating the topic: " + exception.getMessage()); @@ -88,18 +86,19 @@ public class MultiplePartitionIntegrationTest { for (long count = 1; count <= 10 ; count++) { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); userEvent.setEventNanoTime(System.nanoTime()); - Future future = producer.send(new ProducerRecord<>(TOPIC, count, userEvent)); + Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, count, userEvent)); sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); - System.out.println("Partition : " + metadata.partition()); + System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } boolean isOrderMaintained = true; - consumer.subscribe(Collections.singletonList(TOPIC)); + consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { UserEvent userEvent = record.value(); receivedUserEventList.add(userEvent); + System.out.println("User Event ID: " + userEvent.getUserEventId()); }); for (int insertPosition = 0; insertPosition <= receivedUserEventList.size() - 1; insertPosition++) { if (isOrderMaintained){ diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index b41dc67686..6894b0fe80 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -32,9 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @Testcontainers public class SinglePartitionIntegrationTest { - private static String TOPIC = "single_partition_topic"; - private static int PARTITIONS = 1; - private static short REPLICATION_FACTOR = 1; + private static Admin admin; private static KafkaProducer producer; private static KafkaConsumer consumer; @@ -67,10 +65,10 @@ public class SinglePartitionIntegrationTest { producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); List topicList = new ArrayList<>(); - NewTopic newTopic = new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR); + NewTopic newTopic = new NewTopic(Config.SINGLE_PARTITION_TOPIC, Config.SINGLE_PARTITION, Config.REPLICATION_FACTOR); topicList.add(newTopic); CreateTopicsResult result = admin.createTopics(topicList); - KafkaFuture future = result.values().get(TOPIC); + KafkaFuture future = result.values().get(Config.SINGLE_PARTITION_TOPIC); future.whenComplete((voidResult, exception) -> { if (exception != null) { System.err.println("Error creating the topic: " + exception.getMessage()); @@ -92,18 +90,19 @@ public class SinglePartitionIntegrationTest { for (long count = 1; count <= 10 ; count++) { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); userEvent.setEventNanoTime(System.nanoTime()); - ProducerRecord producerRecord = new ProducerRecord<>(TOPIC, userEvent); + ProducerRecord producerRecord = new ProducerRecord<>(Config.SINGLE_PARTITION_TOPIC, userEvent); Future future = producer.send(producerRecord); sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); - System.out.println("Partition : " + metadata.partition()); + System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } - consumer.subscribe(Collections.singletonList(TOPIC)); + consumer.subscribe(Collections.singletonList(Config.SINGLE_PARTITION_TOPIC)); ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { UserEvent userEvent = record.value(); receivedUserEventList.add(userEvent); + System.out.println("User Event ID: " + userEvent.getUserEventId()); }); boolean result = true; for (int count = 0; count <= 9 ; count++) { From 667620821b143d5c750bb4869fceb939dbc60c47 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 2 Nov 2023 19:41:15 -0400 Subject: [PATCH 053/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java Co-authored-by: Liam Williams --- .../message/ordering/ExtSeqWithTimeWindowIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java index 0535e3c4e6..ab3e37916a 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -38,7 +38,7 @@ public class ExtSeqWithTimeWindowIntegrationTest { private static final long BUFFER_PERIOD_NS = 5000L * 1000000; // 5000 milliseconds converted to nanoseconds @Container - private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + private static final long BUFFER_PERIOD_NS = Duration.ofSeconds(5).toNanos(); @BeforeAll static void setup() throws ExecutionException, InterruptedException { From d0edfbc423a834b8ce6a6674cf54713a44ea4513 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 2 Nov 2023 19:41:27 -0400 Subject: [PATCH 054/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java Co-authored-by: Liam Williams --- .../message/ordering/ExtSeqWithTimeWindowIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java index ab3e37916a..af4aa53cc0 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -34,7 +34,7 @@ public class ExtSeqWithTimeWindowIntegrationTest { private static Admin admin; private static KafkaProducer producer; private static KafkaConsumer consumer; - private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); + private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); private static final long BUFFER_PERIOD_NS = 5000L * 1000000; // 5000 milliseconds converted to nanoseconds @Container From 83d6d89db5287e00c9e563737e24b4d979a2d2d9 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 2 Nov 2023 19:41:34 -0400 Subject: [PATCH 055/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java Co-authored-by: Liam Williams --- .../kafka/message/ordering/SinglePartitionIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index 6894b0fe80..35b6602510 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -37,7 +37,7 @@ public class SinglePartitionIntegrationTest { private static KafkaProducer producer; private static KafkaConsumer consumer; - private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); + private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); From bfa7c53b5463ad47c32dc595c234b2d6e5837da2 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 2 Nov 2023 19:41:54 -0400 Subject: [PATCH 056/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java Co-authored-by: Liam Williams --- .../message/ordering/MultiplePartitionIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index bbe9fcf7f8..64a063c6c9 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -34,7 +34,7 @@ public class MultiplePartitionIntegrationTest { private static Admin admin; private static KafkaProducer producer; private static KafkaConsumer consumer; - private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofMillis(5000); + private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); From 02e02f928f4ff4e4bad974b1e3e30e17b2fbc8ed Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Thu, 2 Nov 2023 17:47:02 -0600 Subject: [PATCH 057/233] [BAEL-7074] Synchronization for static data examples --- .../retry/RetryCompletableFuture.java | 2 +- .../threadpool/CustomCompletableFuture.java | 8 +- .../atomicinteger/Employee.java | 32 +++++++ .../synchronizestatic/none/Employee.java | 28 ++++++ .../reentrantlock/Employee.java | 44 +++++++++ .../synchronizedblock/Employee.java | 34 +++++++ .../synchronizedmethod/Employee.java | 27 ++++++ .../volatilekeyword/Employee.java | 29 ++++++ .../SychronizeStaticDataUnitTest.java | 89 +++++++++++++++++++ 9 files changed, 288 insertions(+), 5 deletions(-) create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/none/Employee.java create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/reentrantlock/Employee.java create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedblock/Employee.java create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedmethod/Employee.java create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/volatilekeyword/Employee.java create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java index a3df6b3624..a46665559f 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java @@ -48,7 +48,7 @@ public class RetryCompletableFuture { CompletableFuture cf = CompletableFuture.supplyAsync(supplier); sleep(100); for (int i = 0; i < maxRetries; i++) { - cf = cf.exceptionallyAsync(__ -> supplier.get()); + //cf = cf.exceptionallyAsync(__ -> supplier.get()); } return cf; } diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/threadpool/CustomCompletableFuture.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/threadpool/CustomCompletableFuture.java index 1f3997768e..473cc562ca 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/threadpool/CustomCompletableFuture.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/threadpool/CustomCompletableFuture.java @@ -20,9 +20,9 @@ public class CustomCompletableFuture extends CompletableFuture { return future; } - @Override - public Executor defaultExecutor() { - return executor; - } +// @Override +// public Executor defaultExecutor() { +// return executor; +// } } \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java new file mode 100644 index 0000000000..845dd65ce6 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java @@ -0,0 +1,32 @@ +package com.baeldung.concurrent.synchronizestatic.atomicinteger; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Synchronizing static variable with AtomicInteger. + */ +public class Employee { + + private static final AtomicInteger count = new AtomicInteger(0); + + int id; + String name; + String title; + + public Employee(int id, String name, String title) + { + incrementCount(); + this.id = id; + this.name = name; + this.title = title; + } + + private static void incrementCount() { + count.incrementAndGet(); + System.out.println("Count = " + count.get()); + } + + public static int getCount() { + return count.get(); + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/none/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/none/Employee.java new file mode 100644 index 0000000000..f050a68be4 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/none/Employee.java @@ -0,0 +1,28 @@ +package com.baeldung.concurrent.synchronizestatic.none; + +/** + * No synchronization. + */ +public class Employee { + + static int count; + int id; + String name; + String title; + + public Employee(int id, String name, String title) + { + incrementCount(); + this.id = id; + this.name = name; + this.title = title; + } + + private static void incrementCount() { + System.out.println("Count = " + ++count); + } + + public static Integer getCount() { + return count; + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/reentrantlock/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/reentrantlock/Employee.java new file mode 100644 index 0000000000..2ac0b0d3f2 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/reentrantlock/Employee.java @@ -0,0 +1,44 @@ +package com.baeldung.concurrent.synchronizestatic.reentrantlock; + +import java.util.concurrent.locks.ReentrantLock; + +/** + * Synchronizing static variable with a Reenatrant Lock. + */ +public class Employee { + + private static final ReentrantLock lock = new ReentrantLock(); + + static int count; + int id; + String name; + String title; + + public Employee(int id, String name, String title) + { + incrementCount(); + this.id = id; + this.name = name; + this.title = title; + } + + private static void incrementCount() { + lock.lock(); + try { + System.out.println("Count = " + ++count); + } + finally { + lock.unlock(); + } + } + + public static int getCount() { + lock.lock(); + try { + return count; + } + finally { + lock.unlock(); + } + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedblock/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedblock/Employee.java new file mode 100644 index 0000000000..9c078e7abe --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedblock/Employee.java @@ -0,0 +1,34 @@ +package com.baeldung.concurrent.synchronizestatic.synchronizedblock; + +/** + * Synchronizing static variable with a synchronized block. + */ +public class Employee { + + private static final Object lock = new Object(); + + static int count; + int id; + String name; + String title; + + public Employee(int id, String name, String title) + { + incrementCount(); + this.id = id; + this.name = name; + this.title = title; + } + + private static void incrementCount() { + synchronized(lock) { + System.out.println("Count = " + ++count); + } + } + + public static int getCount() { + synchronized(lock) { + return count; + } + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedmethod/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedmethod/Employee.java new file mode 100644 index 0000000000..f0a785c427 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedmethod/Employee.java @@ -0,0 +1,27 @@ +package com.baeldung.concurrent.synchronizestatic.synchronizedmethod; + +/** + * Synchronizing static variable with a synchronized method. + */ +public class Employee { + static int count; + int id; + String name; + String title; + + public Employee(int id, String name, String title) + { + incrementCount(); + this.id = id; + this.name = name; + this.title = title; + } + + private static synchronized void incrementCount() { + System.out.println("Count = " + ++count); + } + + public static synchronized int getCount() { + return count; + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/volatilekeyword/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/volatilekeyword/Employee.java new file mode 100644 index 0000000000..f41b10e160 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/volatilekeyword/Employee.java @@ -0,0 +1,29 @@ +package com.baeldung.concurrent.synchronizestatic.volatilekeyword; + +/** + * No synchronization. + */ +public class Employee +{ + + volatile static int count; + int id; + String name; + String title; + + public Employee(int id, String name, String title) + { + incrementCount(); + this.id = id; + this.name = name; + this.title = title; + } + + private static void incrementCount() { + System.out.println("Count = " + ++count); + } + + public static Integer getCount() { + return count; + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java new file mode 100644 index 0000000000..d8d9a344f1 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.concurrent.synchronizestatic; + +import org.junit.Test; + +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +public class SychronizeStaticDataUnitTest +{ + private final Executor pool = Executors.newFixedThreadPool(4); + + @Test + public void whenNotSynchronized_thenDataOutOfOrder() { + int numberToTest = 100; + + for(int i = 0; i < numberToTest; i++) { + int finalI = i; + pool.execute(() -> + { + new com.baeldung.concurrent.synchronizestatic.none.Employee(finalI, "John", "Smith"); + }); + } + } + + @Test + public void whenVolatile_thenDataInOrder() { + int numberToTest = 100; + + for(int i = 0; i < numberToTest; i++) { + int finalI = i; + pool.execute(() -> + { + new com.baeldung.concurrent.synchronizestatic.volatilekeyword.Employee(finalI, "John", "Smith"); + }); + } + } + + @Test + public void whenSynchronizedMethod_thenDataInOrder() { + int numberToTest = 100; + + for(int i = 0; i < numberToTest; i++) { + int finalI = i; + pool.execute(() -> + { + new com.baeldung.concurrent.synchronizestatic.synchronizedmethod.Employee(finalI, "John", "Smith"); + }); + } + } + + @Test + public void whenSynchronizedBlock_thenDataInOrder() { + int numberToTest = 100; + + for(int i = 0; i < numberToTest; i++) { + int finalI = i; + pool.execute(() -> + { + new com.baeldung.concurrent.synchronizestatic.synchronizedblock.Employee(finalI, "John", "Smith"); + }); + } + } + + @Test + public void whenAtomicInteger_thenDataInOrder() { + int numberToTest = 100; + + for(int i = 0; i < numberToTest; i++) { + int finalI = i; + pool.execute(() -> + { + new com.baeldung.concurrent.synchronizestatic.atomicinteger.Employee(finalI, "John", "Smith"); + }); + } + } + + @Test + public void whenReentrantLock_thenDataInOrder() { + int numberToTest = 100; + + for(int i = 0; i < numberToTest; i++) { + int finalI = i; + pool.execute(() -> + { + new com.baeldung.concurrent.synchronizestatic.reentrantlock.Employee(finalI, "John", "Smith"); + }); + } + } +} From 1ab4017ad65984900919fa396e52a51637555a3b Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 2 Nov 2023 19:47:05 -0400 Subject: [PATCH 058/233] Issue fixes --- .../ordering/ExtSeqWithTimeWindowIntegrationTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java index af4aa53cc0..a18efe9961 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -35,11 +35,11 @@ public class ExtSeqWithTimeWindowIntegrationTest { private static KafkaProducer producer; private static KafkaConsumer consumer; private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); - - private static final long BUFFER_PERIOD_NS = 5000L * 1000000; // 5000 milliseconds converted to nanoseconds - @Container private static final long BUFFER_PERIOD_NS = Duration.ofSeconds(5).toNanos(); + @Container + private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + @BeforeAll static void setup() throws ExecutionException, InterruptedException { KAFKA_CONTAINER.addExposedPort(9092); From 45bc3d94d407819a1d4c4e139c9b79b38e797e54 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 2 Nov 2023 20:18:19 -0400 Subject: [PATCH 059/233] Code Formatting --- .../ordering/SinglePartitionIntegrationTest.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index 35b6602510..0c65618014 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -24,10 +24,12 @@ import org.testcontainers.containers.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; + import java.time.Duration; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; + import static org.junit.jupiter.api.Assertions.assertTrue; @Testcontainers @@ -53,6 +55,7 @@ public class SinglePartitionIntegrationTest { producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); + producer = new KafkaProducer<>(producerProperties); Properties consumerProperties = new Properties(); consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); @@ -61,9 +64,10 @@ public class SinglePartitionIntegrationTest { consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - admin = Admin.create(adminProperties); - producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); + admin = Admin.create(adminProperties); + + List topicList = new ArrayList<>(); NewTopic newTopic = new NewTopic(Config.SINGLE_PARTITION_TOPIC, Config.SINGLE_PARTITION, Config.REPLICATION_FACTOR); topicList.add(newTopic); @@ -87,7 +91,7 @@ public class SinglePartitionIntegrationTest { void givenASinglePartition_whenPublishedToKafkaAndConsumed_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { List sentUserEventList = new ArrayList<>(); List receivedUserEventList = new ArrayList<>(); - for (long count = 1; count <= 10 ; count++) { + for (long count = 1; count <= 10; count++) { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); userEvent.setEventNanoTime(System.nanoTime()); ProducerRecord producerRecord = new ProducerRecord<>(Config.SINGLE_PARTITION_TOPIC, userEvent); @@ -105,10 +109,10 @@ public class SinglePartitionIntegrationTest { System.out.println("User Event ID: " + userEvent.getUserEventId()); }); boolean result = true; - for (int count = 0; count <= 9 ; count++) { + for (int count = 0; count <= 9; count++) { UserEvent sentUserEvent = sentUserEventList.get(count); UserEvent receivedUserEvent = receivedUserEventList.get(count); - if (!sentUserEvent.equals(receivedUserEvent) && result){ + if (!sentUserEvent.equals(receivedUserEvent) && result) { result = false; } } From 38f30e733fc9ecf70a79a90c65f2ed82947d05b4 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Thu, 2 Nov 2023 19:23:43 -0600 Subject: [PATCH 060/233] [BAEL-7074] Update tests --- .../atomicinteger/Employee.java | 1 - .../volatilekeyword/Employee.java | 29 ------------ .../SychronizeStaticDataUnitTest.java | 45 ++++++++----------- 3 files changed, 19 insertions(+), 56 deletions(-) delete mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/volatilekeyword/Employee.java diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java index 845dd65ce6..9c3c9b987c 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java @@ -23,7 +23,6 @@ public class Employee { private static void incrementCount() { count.incrementAndGet(); - System.out.println("Count = " + count.get()); } public static int getCount() { diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/volatilekeyword/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/volatilekeyword/Employee.java deleted file mode 100644 index f41b10e160..0000000000 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/volatilekeyword/Employee.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.concurrent.synchronizestatic.volatilekeyword; - -/** - * No synchronization. - */ -public class Employee -{ - - volatile static int count; - int id; - String name; - String title; - - public Employee(int id, String name, String title) - { - incrementCount(); - this.id = id; - this.name = name; - this.title = title; - } - - private static void incrementCount() { - System.out.println("Count = " + ++count); - } - - public static Integer getCount() { - return count; - } -} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java index d8d9a344f1..7e5dca9f2b 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java @@ -5,13 +5,22 @@ import org.junit.Test; import java.util.concurrent.Executor; import java.util.concurrent.Executors; +/** + * The tests in this class show the output of creating multiple + * types of Employee classes in the synchronizedstatic + * package. When not synchronized the out will not be sequential; + * when it is synchronized the output will be in sequential. + */ public class SychronizeStaticDataUnitTest { private final Executor pool = Executors.newFixedThreadPool(4); + private final int numberToTest = 100; + @Test public void whenNotSynchronized_thenDataOutOfOrder() { - int numberToTest = 100; + + System.out.println("No synchronization"); for(int i = 0; i < numberToTest; i++) { int finalI = i; @@ -22,22 +31,10 @@ public class SychronizeStaticDataUnitTest } } - @Test - public void whenVolatile_thenDataInOrder() { - int numberToTest = 100; - - for(int i = 0; i < numberToTest; i++) { - int finalI = i; - pool.execute(() -> - { - new com.baeldung.concurrent.synchronizestatic.volatilekeyword.Employee(finalI, "John", "Smith"); - }); - } - } - @Test public void whenSynchronizedMethod_thenDataInOrder() { - int numberToTest = 100; + + System.out.println("Synchronization with synchronized method"); for(int i = 0; i < numberToTest; i++) { int finalI = i; @@ -50,7 +47,8 @@ public class SychronizeStaticDataUnitTest @Test public void whenSynchronizedBlock_thenDataInOrder() { - int numberToTest = 100; + + System.out.println("Synchronization with synchronized block"); for(int i = 0; i < numberToTest; i++) { int finalI = i; @@ -63,20 +61,15 @@ public class SychronizeStaticDataUnitTest @Test public void whenAtomicInteger_thenDataInOrder() { - int numberToTest = 100; - - for(int i = 0; i < numberToTest; i++) { - int finalI = i; - pool.execute(() -> - { - new com.baeldung.concurrent.synchronizestatic.atomicinteger.Employee(finalI, "John", "Smith"); - }); - } + // Not straight forward to test this because we cannot log/print + // and increment values in a synchronized fashion like other + // tests } @Test public void whenReentrantLock_thenDataInOrder() { - int numberToTest = 100; + + System.out.println("Synchronization with ReentrantLock"); for(int i = 0; i < numberToTest; i++) { int finalI = i; From 3d561e24df46720097f8f2e1eeaea780c18d102d Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Fri, 3 Nov 2023 12:43:44 +0000 Subject: [PATCH 061/233] BAEL-7105 Add code for StringBuilder comparison --- .../core-java-string-apis-2/pom.xml | 10 +++++ .../StringBuilderCompare.java | 17 ++++++++ .../StringBuilderComparisonUnitTest.java | 43 +++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 core-java-modules/core-java-string-apis-2/src/main/java/stringbuildercomparison/StringBuilderCompare.java create mode 100644 core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/stringbuildercomparison/StringBuilderComparisonUnitTest.java diff --git a/core-java-modules/core-java-string-apis-2/pom.xml b/core-java-modules/core-java-string-apis-2/pom.xml index 814d301532..0289a18e85 100644 --- a/core-java-modules/core-java-string-apis-2/pom.xml +++ b/core-java-modules/core-java-string-apis-2/pom.xml @@ -33,6 +33,16 @@ core-java-string-apis-2 + + + org.apache.maven.plugins + maven-compiler-plugin + + 11 + 11 + + + src/main/resources diff --git a/core-java-modules/core-java-string-apis-2/src/main/java/stringbuildercomparison/StringBuilderCompare.java b/core-java-modules/core-java-string-apis-2/src/main/java/stringbuildercomparison/StringBuilderCompare.java new file mode 100644 index 0000000000..2d2dc04b83 --- /dev/null +++ b/core-java-modules/core-java-string-apis-2/src/main/java/stringbuildercomparison/StringBuilderCompare.java @@ -0,0 +1,17 @@ +package stringbuildercomparison; + +public class StringBuilderCompare { + + public static boolean compare(StringBuilder one, StringBuilder two){ + if(one.length() != two.length()){ + return false; + } + for(int i = 0; i < one.length(); i++){ + if(one.charAt(i) != two.charAt(i)){ + return false; + } + } + return true; + } + +} diff --git a/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/stringbuildercomparison/StringBuilderComparisonUnitTest.java b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/stringbuildercomparison/StringBuilderComparisonUnitTest.java new file mode 100644 index 0000000000..b1a5a83770 --- /dev/null +++ b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/stringbuildercomparison/StringBuilderComparisonUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.stringbuildercomparison; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertNotSame; + +import org.junit.Test; + +import stringbuildercomparison.StringBuilderCompare; + +public class StringBuilderComparisonUnitTest { + + @Test + public void whenUsingJavaEight_givenTwoIdenticalStringBuilders_thenCorrectlyMatch(){ + StringBuilder one = new StringBuilder("Hello"); + StringBuilder two = new StringBuilder("Hello"); + boolean result = StringBuilderCompare.compare(one, two); + assertEquals(true, result); + } + + @Test + public void whenUsingJavaEight_givenTwoDifferentStringBuilders_thenCorrectlyIdentifyDifference(){ + StringBuilder one = new StringBuilder("Hello"); + StringBuilder two = new StringBuilder("World"); + boolean result = StringBuilderCompare.compare(one, two); + assertEquals(false, result); + } + + @Test + public void whenUsingJavaEleven_givenTwoIdenticalStringBuilders_thenCorrectlyMatch(){ + StringBuilder one = new StringBuilder("Hello"); + StringBuilder two = new StringBuilder("Hello"); + assertEquals(0, one.compareTo(two)); + } + + @Test + public void whenUsingJavaEleven_givenTwoDifferentStringBuilders_thenCorrectlyIdentifyDifference(){ + StringBuilder one = new StringBuilder("Hello"); + StringBuilder two = new StringBuilder("World"); + assertNotSame(0, one.compareTo(two)); + } + + +} From 1aa2f849f49c5f14c25e07966e199593ca449e80 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Fri, 3 Nov 2023 13:10:24 -0600 Subject: [PATCH 062/233] Revert 2 changes unrelated to BAEL-7074 --- .../completablefuture/retry/RetryCompletableFuture.java | 2 +- .../threadpool/CustomCompletableFuture.java | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java index a46665559f..a3df6b3624 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java @@ -48,7 +48,7 @@ public class RetryCompletableFuture { CompletableFuture cf = CompletableFuture.supplyAsync(supplier); sleep(100); for (int i = 0; i < maxRetries; i++) { - //cf = cf.exceptionallyAsync(__ -> supplier.get()); + cf = cf.exceptionallyAsync(__ -> supplier.get()); } return cf; } diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/threadpool/CustomCompletableFuture.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/threadpool/CustomCompletableFuture.java index 473cc562ca..1f3997768e 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/threadpool/CustomCompletableFuture.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/threadpool/CustomCompletableFuture.java @@ -20,9 +20,9 @@ public class CustomCompletableFuture extends CompletableFuture { return future; } -// @Override -// public Executor defaultExecutor() { -// return executor; -// } + @Override + public Executor defaultExecutor() { + return executor; + } } \ No newline at end of file From 159461815d99562f7d8f1babe787c7f784145a92 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Fri, 3 Nov 2023 15:31:25 -0600 Subject: [PATCH 063/233] New example and unit test --- .../synchronizedclass/Employee.java | 32 +++++++++++++++++++ .../SychronizeStaticDataUnitTest.java | 16 +++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java new file mode 100644 index 0000000000..a69b633f3b --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java @@ -0,0 +1,32 @@ +package com.baeldung.concurrent.synchronizestatic.synchronizedclass; + +/** + * Synchronizing static variable with a synchronized block. + */ +public class Employee +{ + static int count; + int id; + String name; + String title; + + public Employee(int id, String name, String title) + { + incrementCount(); + this.id = id; + this.name = name; + this.title = title; + } + + private static void incrementCount() { + synchronized(Employee.class) { + System.out.println("Count = " + ++count); + } + } + + public static int getCount() { + synchronized(Employee.class) { + return count; + } + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java index 7e5dca9f2b..e633005c6f 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java @@ -45,10 +45,24 @@ public class SychronizeStaticDataUnitTest } } + @Test + public void whenSynchronizedClass_thenDataInOrder() { + + System.out.println("Synchronization with synchronized block on class"); + + for(int i = 0; i < numberToTest; i++) { + int finalI = i; + pool.execute(() -> + { + new com.baeldung.concurrent.synchronizestatic.synchronizedclass.Employee(finalI, "John", "Smith"); + }); + } + } + @Test public void whenSynchronizedBlock_thenDataInOrder() { - System.out.println("Synchronization with synchronized block"); + System.out.println("Synchronization with synchronized block on a private object"); for(int i = 0; i < numberToTest; i++) { int finalI = i; From 0f6149ef8cbbd7b60312b2726f7501dcdd85dc13 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Fri, 3 Nov 2023 23:31:49 +0200 Subject: [PATCH 064/233] [JAVA-26735] Upgraded gson library to 2.10.1 version --- aws-modules/aws-dynamodb/pom.xml | 2 +- aws-modules/aws-miscellaneous/pom.xml | 2 +- java-websocket/pom.xml | 2 +- json-modules/gson/pom.xml | 2 +- .../JsonObjectConversionsUnitTest.java | 31 ++++++++++++------- json-modules/json-arrays/pom.xml | 2 +- json-modules/json/pom.xml | 2 +- libraries-data-io/pom.xml | 2 +- libraries-data/pom.xml | 2 +- libraries-http-2/pom.xml | 2 +- libraries-http/pom.xml | 2 +- web-modules/javax-servlets/pom.xml | 2 +- web-modules/spark-java/pom.xml | 2 +- 13 files changed, 31 insertions(+), 24 deletions(-) diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml index 37b88327f4..adce036733 100644 --- a/aws-modules/aws-dynamodb/pom.xml +++ b/aws-modules/aws-dynamodb/pom.xml @@ -79,7 +79,7 @@ - 2.8.0 + 2.10.1 1.21.1 3.1.1 diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index 4126256fb9..5fdd7fa04d 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -73,7 +73,7 @@ - 2.8.0 + 2.10.1 1.21.1 1.10.L001 0.9.4.0006L diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml index d529b32022..fd97fd9db3 100644 --- a/java-websocket/pom.xml +++ b/java-websocket/pom.xml @@ -29,7 +29,7 @@ 1.1 - 2.8.0 + 2.10.1 \ No newline at end of file diff --git a/json-modules/gson/pom.xml b/json-modules/gson/pom.xml index ecfbaa7be4..ba968d9ae1 100644 --- a/json-modules/gson/pom.xml +++ b/json-modules/gson/pom.xml @@ -64,7 +64,7 @@ - 2.8.0 + 2.10.1 2.9.6 diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java index 9f07617969..18d9ccaf06 100644 --- a/json-modules/gson/src/test/java/com/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java +++ b/json-modules/gson/src/test/java/com/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java @@ -1,7 +1,9 @@ package com.baeldung.gson.conversion; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.google.gson.*; -import org.junit.Assert; import org.junit.jupiter.api.Test; public class JsonObjectConversionsUnitTest { @@ -10,24 +12,29 @@ public class JsonObjectConversionsUnitTest { void whenUsingJsonParser_thenConvertToJsonObject() throws Exception { // Example 1: Using JsonParser String json = "{ \"name\": \"Baeldung\", \"java\": true }"; - - JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); - - Assert.assertTrue(jsonObject.isJsonObject()); - Assert.assertTrue(jsonObject.get("name").getAsString().equals("Baeldung")); - Assert.assertTrue(jsonObject.get("java").getAsBoolean() == true); + + JsonObject jsonObject = JsonParser.parseString(json) + .getAsJsonObject(); + + assertTrue(jsonObject.isJsonObject()); + assertEquals("Baeldung", jsonObject.get("name") + .getAsString()); + assertTrue(jsonObject.get("java") + .getAsBoolean()); } @Test void whenUsingGsonInstanceFromJson_thenConvertToJsonObject() throws Exception { // Example 2: Using fromJson String json = "{ \"name\": \"Baeldung\", \"java\": true }"; - + JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); - - Assert.assertTrue(convertedObject.isJsonObject()); - Assert.assertTrue(convertedObject.get("name").getAsString().equals("Baeldung")); - Assert.assertTrue(convertedObject.get("java").getAsBoolean() == true); + + assertTrue(convertedObject.isJsonObject()); + assertEquals("Baeldung", convertedObject.get("name") + .getAsString()); + assertTrue(convertedObject.get("java") + .getAsBoolean()); } } diff --git a/json-modules/json-arrays/pom.xml b/json-modules/json-arrays/pom.xml index 10c487fbda..ec492b49cc 100644 --- a/json-modules/json-arrays/pom.xml +++ b/json-modules/json-arrays/pom.xml @@ -38,7 +38,7 @@ 1.0 - 2.8.5 + 2.10.1 1.1.2 2.28.0 diff --git a/json-modules/json/pom.xml b/json-modules/json/pom.xml index 27c9262279..ba075be679 100644 --- a/json-modules/json/pom.xml +++ b/json-modules/json/pom.xml @@ -68,7 +68,7 @@ 1.0.72 1.0 1.0.1 - 2.8.5 + 2.10.1 1.1.2 2.28.0 diff --git a/libraries-data-io/pom.xml b/libraries-data-io/pom.xml index 2e126610d4..0a8afa02e2 100644 --- a/libraries-data-io/pom.xml +++ b/libraries-data-io/pom.xml @@ -106,7 +106,7 @@ v4-rev493-1.21.0 6.1.2 2.3.1 - 2.8.7 + 2.10.1 1.15 0.14.2 3.17.3 diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index a721e967d2..85ef01e704 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -210,7 +210,7 @@ 3.3.1 2.14.0 2.9.1 - 2.9.1 + 2.10.1 1.1.1 1.5.0 5.2.0 diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml index fa3b6534db..c80c5729a7 100644 --- a/libraries-http-2/pom.xml +++ b/libraries-http-2/pom.xml @@ -110,7 +110,7 @@ 4.9.1 - 2.8.5 + 2.10.1 4.9.1 1.0.3 9.4.19.v20190610 diff --git a/libraries-http/pom.xml b/libraries-http/pom.xml index 18ba571f60..c726b56b5d 100644 --- a/libraries-http/pom.xml +++ b/libraries-http/pom.xml @@ -103,7 +103,7 @@ - 2.8.5 + 2.10.1 4.5.3 4.9.1 1.23.0 diff --git a/web-modules/javax-servlets/pom.xml b/web-modules/javax-servlets/pom.xml index 80a1e3af9f..406cfc05c1 100644 --- a/web-modules/javax-servlets/pom.xml +++ b/web-modules/javax-servlets/pom.xml @@ -49,7 +49,7 @@ 4.5.3 - 2.8.2 + 2.10.1 \ No newline at end of file diff --git a/web-modules/spark-java/pom.xml b/web-modules/spark-java/pom.xml index da09467212..e49be68319 100644 --- a/web-modules/spark-java/pom.xml +++ b/web-modules/spark-java/pom.xml @@ -30,7 +30,7 @@ 2.5.4 - 2.8.0 + 2.10.1 \ No newline at end of file From a324fc5c33993d3721f210c9e9079fb3233b4161 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Fri, 3 Nov 2023 23:52:59 +0200 Subject: [PATCH 065/233] [JAVA-26735] Replaced deprecated API JsonParser --- .../JsonObjectConversionsUnitTest.java | 2 ++ .../test/GsonDeserializationUnitTest.java | 8 ++--- .../gson/jsoncompare/JsonCompareUnitTest.java | 34 +++++++------------ .../serialization/GsonSerializeUnitTest.java | 3 +- 4 files changed, 20 insertions(+), 27 deletions(-) diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java index 18d9ccaf06..e1e5e48269 100644 --- a/json-modules/gson/src/test/java/com/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java +++ b/json-modules/gson/src/test/java/com/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java @@ -4,6 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.gson.*; + +import org.junit.Assert; import org.junit.jupiter.api.Test; public class JsonObjectConversionsUnitTest { diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/deserialization/test/GsonDeserializationUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/deserialization/test/GsonDeserializationUnitTest.java index adc046ed8e..81d59cf364 100644 --- a/json-modules/gson/src/test/java/com/baeldung/gson/deserialization/test/GsonDeserializationUnitTest.java +++ b/json-modules/gson/src/test/java/com/baeldung/gson/deserialization/test/GsonDeserializationUnitTest.java @@ -3,8 +3,9 @@ package com.baeldung.gson.deserialization.test; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.not; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; + import java.lang.reflect.Type; import java.util.ArrayList; @@ -68,7 +69,7 @@ public class GsonDeserializationUnitTest { final GenericFoo targetObject = new Gson().fromJson(json, typeToken); - assertEquals(targetObject.theValue, new Integer(1)); + assertEquals(targetObject.theValue, Integer.valueOf(1)); } // tests - multiple elements @@ -98,8 +99,7 @@ public class GsonDeserializationUnitTest { @Test public void whenDeserializingJsonIntoElements_thenCorrect() { final String jsonSourceObject = "{\"valueInt\":7,\"valueString\":\"seven\"}"; - final JsonParser jParser = new JsonParser(); - final JsonElement jElement = jParser.parse(jsonSourceObject); + final JsonElement jElement = JsonParser.parseString(jsonSourceObject); final JsonObject jObject = jElement.getAsJsonObject(); final int intValue = jObject.get("valueInt").getAsInt(); final String stringValue = jObject.get("valueString").getAsString(); diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/jsoncompare/JsonCompareUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/jsoncompare/JsonCompareUnitTest.java index 84989a7411..4235eb426a 100644 --- a/json-modules/gson/src/test/java/com/baeldung/gson/jsoncompare/JsonCompareUnitTest.java +++ b/json-modules/gson/src/test/java/com/baeldung/gson/jsoncompare/JsonCompareUnitTest.java @@ -16,79 +16,71 @@ public class JsonCompareUnitTest { @Test public void givenIdenticalSimpleObjects_whenCompared_thenEqual() { - JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}"; String string2 = "{\"customer\": {\"id\": \"44521\", \"fullName\": \"Emily Jenkins\",\"age\": 27}}"; - assertTrue(parser.parse(string1) - .isJsonObject()); - assertEquals(parser.parse(string1), parser.parse(string2)); + assertTrue(JsonParser.parseString(string1).isJsonObject()); + assertEquals(JsonParser.parseString(string1), JsonParser.parseString(string2)); } @Test public void givenSameObjectsInDifferentOrder_whenCompared_thenEqual() { - JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}"; String string2 = "{\"customer\": {\"id\": \"44521\",\"age\": 27, \"fullName\": \"Emily Jenkins\" }}"; - JsonElement json1 = parser.parse(string1); - JsonElement json2 = parser.parse(string2); + JsonElement json1 = JsonParser.parseString(string1); + JsonElement json2 = JsonParser.parseString(string2); assertEquals(json1, json2); } @Test public void givenIdenticalArrays_whenCompared_thenEqual() { - JsonParser parser = new JsonParser(); String string1 = "[10, 20, 30]"; String string2 = "[10, 20, 30]"; - assertTrue(parser.parse(string1) + assertTrue(JsonParser.parseString(string1) .isJsonArray()); - assertEquals(parser.parse(string1), parser.parse(string2)); + assertEquals(JsonParser.parseString(string1), JsonParser.parseString(string2)); } @Test public void givenArraysInDifferentOrder_whenCompared_thenNotEqual() { - JsonParser parser = new JsonParser(); String string1 = "[20, 10, 30]"; String string2 = "[10, 20, 30]"; - assertNotEquals(parser.parse(string1), parser.parse(string2)); + assertNotEquals(JsonParser.parseString(string1), JsonParser.parseString(string2)); } @Test public void givenIdenticalNestedObjects_whenCompared_thenEqual() { - JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"fav_product\": \"Coke\", \"last_buy\": \"2012-04-23\"}}}"; String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"fav_product\": \"Coke\"}}}"; - JsonElement json1 = parser.parse(string1); - JsonElement json2 = parser.parse(string2); + JsonElement json1 = JsonParser.parseString(string1); + JsonElement json2 = JsonParser.parseString(string2); assertEquals(json1, json2); } @Test public void givenIdenticalNestedObjectsWithArray_whenCompared_thenEqual() { - JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}"; String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}"; - JsonElement json1 = parser.parse(string1); - JsonElement json2 = parser.parse(string2); + JsonElement json1 = JsonParser.parseString(string1); + JsonElement json2 = JsonParser.parseString(string2); assertEquals(json1, json2); } @Test public void givenNestedObjectsDifferentArrayOrder_whenCompared_thenNotEqual() { - JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}"; String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"eggs\", \"banana\"]}}}"; - JsonElement json1 = parser.parse(string1); - JsonElement json2 = parser.parse(string2); + JsonElement json1 = JsonParser.parseString(string1); + JsonElement json2 = JsonParser.parseString(string2); assertNotEquals(json1, json2); } diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java index 21d2bedd24..0d54cffbb4 100644 --- a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java +++ b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java @@ -41,8 +41,7 @@ public class GsonSerializeUnitTest { .serializeNulls() .disableHtmlEscaping() .create() - .toJson(new JsonParser() - .parse("{\"imdbId\":null,\"actors\":[{\"IMDB Code\":\"nm2199632\",\"Date Of Birth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}")); + .toJson(JsonParser.parseString("{\"imdbId\":null,\"actors\":[{\"IMDB Code\":\"nm2199632\",\"Date Of Birth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}")); Assert.assertEquals(gson.toJson(movieWithNullValue), expectedOutput); } } From 049770733ccef4e7e364c2cd6768f66b66e85e77 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 4 Nov 2023 12:24:35 +0530 Subject: [PATCH 066/233] JAVA-27176 Upgrade hibernate validator version in core-java-string-operations-2 module --- .../core-java-string-operations-2/pom.xml | 22 +++++-------------- .../SomeClassWithValidations.java | 2 +- .../emptystrings/EmptyStringsUnitTest.java | 8 +++---- 3 files changed, 10 insertions(+), 22 deletions(-) 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 902e8f09b4..383a3b4a40 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -14,11 +14,6 @@ - - javax.validation - validation-api - ${validation-api.version} - org.apache.commons commons-lang3 @@ -30,14 +25,9 @@ ${hibernate-validator.version} - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish.web - javax.el - ${javax.el.version} + org.glassfish.expressly + expressly + ${expressly.version} org.openjdk.jmh @@ -95,10 +85,8 @@ - 2.0.0.Final - 6.0.2.Final - 3.0.0 - 2.2.6 + 8.0.1.Final + 5.0.0 1.14 5.3.0 diff --git a/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java index 058d53ba82..abe311938a 100644 --- a/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java @@ -1,6 +1,6 @@ package com.baeldung.emptystrings; -import javax.validation.constraints.Pattern; +import jakarta.validation.constraints.Pattern; class SomeClassWithValidations { diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java index 9652e0e770..c756953c70 100644 --- a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java @@ -5,10 +5,10 @@ import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.springframework.util.ObjectUtils; -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; import java.util.Set; import static org.hamcrest.Matchers.iterableWithSize; From 674f03a8fe8eee695e78aac18fe9cbe472f466e9 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 4 Nov 2023 12:43:56 +0530 Subject: [PATCH 067/233] JAVA-27177 Upgrade hibernate-validator version in atomikos module --- atomikos/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atomikos/pom.xml b/atomikos/pom.xml index cd798825d1..d2ef7c84b2 100644 --- a/atomikos/pom.xml +++ b/atomikos/pom.xml @@ -114,7 +114,7 @@ 1.1 1.0 2.0.1.Final - 6.1.2.Final + 8.0.1.Final 3.0.0 2.2.4 From 20361bec8ebc4b3f059b2ce9a98e2433e9622781 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 4 Nov 2023 12:59:59 +0530 Subject: [PATCH 068/233] JAVA-27178 Upgrade hibernate-validator in javaxval module --- javaxval/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaxval/pom.xml b/javaxval/pom.xml index bececb2ea7..c4a30f915d 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -37,7 +37,7 @@ - 6.2.0.Final + 8.0.1.Final 3.0.4 From 885111ea75a8e4edb6b5fd82e94389effc8232ae Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 4 Nov 2023 13:13:28 +0530 Subject: [PATCH 069/233] JAVA-27177 Upragde hibernate validator- Remove dependencies no longer needed --- atomikos/pom.xml | 18 ------------------ .../atomikos/spring/jpa/Application.java | 8 ++++---- .../atomikos/spring/jpa/order/Order.java | 2 +- 3 files changed, 5 insertions(+), 23 deletions(-) diff --git a/atomikos/pom.xml b/atomikos/pom.xml index d2ef7c84b2..2cbc106268 100644 --- a/atomikos/pom.xml +++ b/atomikos/pom.xml @@ -82,26 +82,11 @@ geronimo-jta_1.0.1B_spec ${geronimo.version} - - javax.validation - validation-api - ${validation-api.version} - org.hibernate.validator hibernate-validator ${hibernate-validator.version} - - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish.web - javax.el - ${javax.el.version} - @@ -113,10 +98,7 @@ 10.8.1.2 1.1 1.0 - 2.0.1.Final 8.0.1.Final - 3.0.0 - 2.2.4 \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java index cf1fef2cd8..ad828bd2ca 100644 --- a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java @@ -3,10 +3,10 @@ package com.baeldung.atomikos.spring.jpa; import java.util.Set; import java.util.UUID; -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java index 4b9ae2dd1d..3a580e6448 100644 --- a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java @@ -3,7 +3,7 @@ package com.baeldung.atomikos.spring.jpa.order; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; -import javax.validation.constraints.Max; +import jakarta.validation.constraints.Max; @Entity @Table(name = "ORDERS") From 3ee56ca66ed6aebf9f2ba92e3eaafd4b474e089c Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 4 Nov 2023 11:12:34 +0200 Subject: [PATCH 070/233] [JAVA-26735] Fixed test case --- .../primitives/PrimitiveValuesUnitTest.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/primitives/PrimitiveValuesUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/primitives/PrimitiveValuesUnitTest.java index e1241fa92a..00edcd426a 100644 --- a/json-modules/gson/src/test/java/com/baeldung/gson/primitives/PrimitiveValuesUnitTest.java +++ b/json-modules/gson/src/test/java/com/baeldung/gson/primitives/PrimitiveValuesUnitTest.java @@ -43,8 +43,8 @@ public class PrimitiveValuesUnitTest { gson.toJson(model); } - @Test(expected = IllegalArgumentException.class) public void - whenSerializingNaN_thenShouldRaiseAnException() { + @Test(expected = IllegalArgumentException.class) + public void whenSerializingNaN_thenShouldRaiseAnException() { FloatExample model = new FloatExample(); model.value = Float.NaN; @@ -52,7 +52,8 @@ public class PrimitiveValuesUnitTest { gson.toJson(model); } - @Test public void whenDeserializingFromJSON_thenShouldParseTheValueInTheString() { + @Test + public void whenDeserializingFromJSON_thenShouldParseTheValueInTheString() { String json = "{\"byteValue\": 17, \"shortValue\": 3, \"intValue\": 3, " + "\"longValue\": 3, \"floatValue\": 3.5" + ", \"doubleValue\": 3.5" + ", \"booleanValue\": true, \"charValue\": \"a\"}"; @@ -72,14 +73,16 @@ public class PrimitiveValuesUnitTest { // @formatter:on } - @Test public void whenDeserializingHighPrecissionNumberIntoFloat_thenShouldPerformRounding() { + @Test + public void whenDeserializingHighPrecissionNumberIntoFloat_thenShouldPerformRounding() { String json = "{\"value\": 12.123425589123456}"; Gson gson = new Gson(); FloatExample model = gson.fromJson(json, FloatExample.class); assertEquals(12.123426f, model.value, 0.000001); } - @Test public void whenDeserializingHighPrecissiongNumberIntoDouble_thenShouldPerformRounding() { + @Test + public void whenDeserializingHighPrecissiongNumberIntoDouble_thenShouldPerformRounding() { String json = "{\"value\": 12.123425589123556}"; Gson gson = new Gson(); DoubleExample model = gson.fromJson(json, DoubleExample.class); @@ -87,12 +90,12 @@ public class PrimitiveValuesUnitTest { } - @Test public void whenDeserializingValueThatOverflows_thenShouldOverflowSilently() { + @Test(expected = JsonSyntaxException.class) + public void whenDeserializingValueThatOverflows_thenShouldRaiseAnException() { Gson gson = new Gson(); String json = "{\"value\": \"300\"}"; ByteExample model = gson.fromJson(json, ByteExample.class); - assertEquals(44, model.value); } @Test public void whenDeserializingRealIntoByte_thenShouldRaiseAnException() { From 1394665355ba988ac79b65b98158fa3cd1c0eb97 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:46:09 -0400 Subject: [PATCH 071/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java Co-authored-by: Liam Williams --- .../ordering/SinglePartitionIntegrationTest.java | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index 0c65618014..068d536b1a 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -68,18 +68,7 @@ public class SinglePartitionIntegrationTest { admin = Admin.create(adminProperties); - List topicList = new ArrayList<>(); - NewTopic newTopic = new NewTopic(Config.SINGLE_PARTITION_TOPIC, Config.SINGLE_PARTITION, Config.REPLICATION_FACTOR); - topicList.add(newTopic); - CreateTopicsResult result = admin.createTopics(topicList); - KafkaFuture future = result.values().get(Config.SINGLE_PARTITION_TOPIC); - future.whenComplete((voidResult, exception) -> { - if (exception != null) { - System.err.println("Error creating the topic: " + exception.getMessage()); - } else { - System.out.println("Topic created successfully!"); - } - }).get(); + admin.createTopics(ImmutableList.of(new NewTopic(Config.SINGLE_PARTITION_TOPIC, Config.SINGLE_PARTITION, Config.REPLICATION_FACTOR))).all().get(); } @AfterAll From c2453a503f9e7168469f5fa32084c632b1380913 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:46:17 -0400 Subject: [PATCH 072/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java Co-authored-by: Liam Williams --- .../ExtSeqWithTimeWindowIntegrationTest.java | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java index a18efe9961..f723d290c2 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -62,18 +62,7 @@ public class ExtSeqWithTimeWindowIntegrationTest { admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); - List topicList = new ArrayList<>(); - NewTopic newTopic = new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR); - topicList.add(newTopic); - CreateTopicsResult result = admin.createTopics(topicList); - KafkaFuture future = result.values().get(Config.MULTI_PARTITION_TOPIC); - future.whenComplete((voidResult, exception) -> { - if (exception != null) { - System.err.println("Error creating the topic: " + exception.getMessage()); - } else { - System.out.println("Topic created successfully!"); - } - }).get(); + admin.createTopics(ImmutableList.of(new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR))).all().get(); } @AfterAll From e5da66643251d2f66eecd0ca3d607e10fa143179 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:49:26 -0400 Subject: [PATCH 073/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java Co-authored-by: Liam Williams --- .../ordering/MultiplePartitionIntegrationTest.java | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index 64a063c6c9..88281014b6 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -60,18 +60,7 @@ public class MultiplePartitionIntegrationTest { admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); - List topicList = new ArrayList<>(); - NewTopic newTopic = new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR); - topicList.add(newTopic); - CreateTopicsResult result = admin.createTopics(topicList); - KafkaFuture future = result.values().get(Config.MULTI_PARTITION_TOPIC); - future.whenComplete((voidResult, exception) -> { - if (exception != null) { - System.err.println("Error creating the topic: " + exception.getMessage()); - } else { - System.out.println("Topic created successfully!"); - } - }).get(); + admin.createTopics(ImmutableList.of(new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR))).all().get(); } @AfterAll From 41ab2ed2213b8a20fbeb8f3ee52357757b552e31 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:55:03 -0400 Subject: [PATCH 074/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java Co-authored-by: Liam Williams --- .../com/baeldung/kafka/message/ordering/payload/UserEvent.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java index 0c4018e624..040c7d6995 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java @@ -3,9 +3,7 @@ package com.baeldung.kafka.message.ordering.payload; import java.util.Objects; public class UserEvent implements Comparable { private String userEventId; - private long eventNanoTime; - private long globalSequenceNumber; public UserEvent(){ From 0399cf0e5f0d788367d5209def3ad41be8ae92d3 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:55:32 -0400 Subject: [PATCH 075/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java Co-authored-by: Liam Williams --- .../baeldung/kafka/message/ordering/payload/UserEvent.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java index 040c7d6995..67e6b70c08 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java @@ -6,11 +6,11 @@ public class UserEvent implements Comparable { private long eventNanoTime; private long globalSequenceNumber; + @SuppressWarnings("unused") public UserEvent(){ - + // Required for Jackson Serialization and Deserialization } - //Required for Kafka Serialization and Deserialization public UserEvent(String userEventId) { this.userEventId = userEventId; } From d4842ac511422a11dd746d07d337fe9dda74e76f Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:56:07 -0400 Subject: [PATCH 076/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java Co-authored-by: Liam Williams --- .../message/ordering/serialization/JacksonDeserializer.java | 1 - 1 file changed, 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java index be2b104761..2cc0bde853 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java @@ -8,7 +8,6 @@ import java.util.Map; /** * Configured via {@link org.apache.kafka.clients.consumer.ConsumerConfig#VALUE_DESERIALIZER_CLASS_CONFIG} */ -@SuppressWarnings("unused") public class JacksonDeserializer implements Deserializer { private final ObjectMapper objectMapper = new ObjectMapper(); private Class type; From aeb5f55e0e27a67aaa18fd756fdf21664e56f6d4 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:56:47 -0400 Subject: [PATCH 077/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java Co-authored-by: Liam Williams --- .../message/ordering/serialization/JacksonDeserializer.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java index 2cc0bde853..300a43ca7c 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java @@ -33,9 +33,8 @@ public class JacksonDeserializer implements Deserializer { try { return objectMapper.readValue(bytes, type); } catch (Exception e) { - //throw new RuntimeException("Error deserializing value", e); + throw new RuntimeException("Error deserializing value", e); } - return null; } } From 9a76f1a6375eceba23f8ce24748db06e9c1519f8 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:57:02 -0400 Subject: [PATCH 078/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java Co-authored-by: Liam Williams --- .../message/ordering/ExtSeqWithTimeWindowIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java index f723d290c2..e9a77bd2d7 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -29,7 +29,7 @@ import java.util.concurrent.Future; import static org.junit.jupiter.api.Assertions.*; @Testcontainers -public class ExtSeqWithTimeWindowIntegrationTest { +public class ExternalSequenceWithTimeWindowIntegrationTest { private static Admin admin; private static KafkaProducer producer; From 33b18c0ca49d4814eb032df2122dc302e2bb5ebf Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:57:19 -0400 Subject: [PATCH 079/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java Co-authored-by: Liam Williams --- .../message/ordering/ExtSeqWithTimeWindowIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java index e9a77bd2d7..f47a01486c 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -92,7 +92,7 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { records.forEach(record -> { buffer.add(record.value()); }); - while (buffer.size() > 0) { + while (!buffer.isEmpty()) { if (System.nanoTime() - lastProcessedTime > BUFFER_PERIOD_NS) { processBuffer(buffer, receivedUserEventList); lastProcessedTime = System.nanoTime(); From 3e2975196d8842459acfaa23d4b22b86e5d08f1b Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:57:32 -0400 Subject: [PATCH 080/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java Co-authored-by: Liam Williams --- .../ExtSeqWithTimeWindowIntegrationTest.java | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java index f47a01486c..76e4a47d17 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java @@ -102,16 +102,9 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { buffer.add(record.value()); }); } - for (int insertPosition = 0; insertPosition <= receivedUserEventList.size() - 1; insertPosition++) { - if (isOrderMaintained){ - UserEvent sentUserEvent = sentUserEventList.get(insertPosition); - UserEvent receivedUserEvent = receivedUserEventList.get(insertPosition); - if (!sentUserEvent.equals(receivedUserEvent)) { - isOrderMaintained = false; - } - } - } - assertTrue(isOrderMaintained); + assertThat(receivedUserEventList) + .isEqualTo(sentUserEventList) + .containsExactlyElementsOf(sentUserEventList); } private static void processBuffer(List buffer, List receivedUserEventList) { From 9c463c752b17ca3843490cef337a44f1a96f07f3 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:57:47 -0400 Subject: [PATCH 081/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java Co-authored-by: Liam Williams --- .../ordering/MultiplePartitionIntegrationTest.java | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index 88281014b6..752514c09a 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -89,15 +89,8 @@ public class MultiplePartitionIntegrationTest { receivedUserEventList.add(userEvent); System.out.println("User Event ID: " + userEvent.getUserEventId()); }); - for (int insertPosition = 0; insertPosition <= receivedUserEventList.size() - 1; insertPosition++) { - if (isOrderMaintained){ - UserEvent sentUserEvent = sentUserEventList.get(insertPosition); - UserEvent receivedUserEvent = receivedUserEventList.get(insertPosition); - if (!sentUserEvent.equals(receivedUserEvent)) { - isOrderMaintained = false; - } - } - } - assertFalse(isOrderMaintained); + assertThat(receivedUserEventList) + .isNotEqualTo(sentUserEventList) + .containsExactlyInAnyOrderElementsOf(sentUserEventList); } } From ddc5e0a5efbfb15a8a19c6bf0b91a2986883efbe Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:58:01 -0400 Subject: [PATCH 082/233] Update apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java Co-authored-by: Liam Williams --- .../ordering/SinglePartitionIntegrationTest.java | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index 068d536b1a..a767133627 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -97,14 +97,8 @@ public class SinglePartitionIntegrationTest { receivedUserEventList.add(userEvent); System.out.println("User Event ID: " + userEvent.getUserEventId()); }); - boolean result = true; - for (int count = 0; count <= 9; count++) { - UserEvent sentUserEvent = sentUserEventList.get(count); - UserEvent receivedUserEvent = receivedUserEventList.get(count); - if (!sentUserEvent.equals(receivedUserEvent) && result) { - result = false; - } - } - assertTrue(result); + assertThat(receivedUserEventList) + .isEqualTo(sentUserEventList) + .containsExactlyElementsOf(sentUserEventList); } } From cb274a7ed4a86fbdb1fa129d1a68c31d316a8011 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:58:28 -0400 Subject: [PATCH 083/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java Co-authored-by: Liam Williams --- .../kafka/message/ordering/serialization/JacksonSerializer.java | 1 - 1 file changed, 1 deletion(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java index 2d7432cc7b..4c081de3cc 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java @@ -6,7 +6,6 @@ import org.apache.kafka.common.serialization.Serializer; /** * Configured via {@link org.apache.kafka.clients.producer.ProducerConfig#VALUE_SERIALIZER_CLASS_CONFIG} */ -@SuppressWarnings("unused") public class JacksonSerializer implements Serializer { private final ObjectMapper objectMapper = new ObjectMapper(); From b24851bfcee4223b94d51e5b3d2d079824f8cb09 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 16:59:10 -0400 Subject: [PATCH 084/233] Update apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java Co-authored-by: Liam Williams --- .../ordering/serialization/JacksonDeserializer.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java index 300a43ca7c..4868ecaf2e 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java @@ -12,13 +12,6 @@ public class JacksonDeserializer implements Deserializer { private final ObjectMapper objectMapper = new ObjectMapper(); private Class type; - public JacksonDeserializer(Class type) { - this.type = type; - } - - public JacksonDeserializer() { - - } @Override public void configure(Map configs, boolean isKey) { From 2cecae1dfb6af13c311e48d89dfc38d1f70ba181 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 17:18:20 -0400 Subject: [PATCH 085/233] Incorporate Review comments --- .../com/baeldung/kafka/message/ordering/Config.java | 2 +- ...ternalSequenceWithTimeWindowIntegrationTest.java} | 12 +++++------- .../ordering/MultiplePartitionIntegrationTest.java | 7 +++---- .../ordering/SinglePartitionIntegrationTest.java | 6 ++---- 4 files changed, 11 insertions(+), 16 deletions(-) rename apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/{ExtSeqWithTimeWindowIntegrationTest.java => ExternalSequenceWithTimeWindowIntegrationTest.java} (95%) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java index 9cc6314309..7fae8403b5 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/Config.java @@ -7,5 +7,5 @@ public class Config { public static final int MULTIPLE_PARTITIONS = 5; public static final int SINGLE_PARTITION = 1; - public static short REPLICATION_FACTOR = 1; + public static final short REPLICATION_FACTOR = 1; } diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java similarity index 95% rename from apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java rename to apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java index 76e4a47d17..0c64f663f3 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExtSeqWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java @@ -11,7 +11,6 @@ import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; -import org.apache.kafka.common.KafkaFuture; import org.apache.kafka.common.serialization.LongDeserializer; import org.apache.kafka.common.serialization.LongSerializer; import org.junit.jupiter.api.AfterAll; @@ -25,8 +24,8 @@ import java.time.Duration; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; - -import static org.junit.jupiter.api.Assertions.*; +import com.google.common.collect.ImmutableList; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @Testcontainers public class ExternalSequenceWithTimeWindowIntegrationTest { @@ -84,7 +83,6 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } - boolean isOrderMaintained = true; consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); List buffer = new ArrayList<>(); long lastProcessedTime = System.nanoTime(); @@ -102,9 +100,9 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { buffer.add(record.value()); }); } - assertThat(receivedUserEventList) - .isEqualTo(sentUserEventList) - .containsExactlyElementsOf(sentUserEventList); + assertThat(receivedUserEventList) + .isEqualTo(sentUserEventList) + .containsExactlyElementsOf(sentUserEventList); } private static void processBuffer(List buffer, List receivedUserEventList) { diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index 752514c09a..2fde24114c 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -11,7 +11,6 @@ import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; -import org.apache.kafka.common.KafkaFuture; import org.apache.kafka.common.serialization.LongDeserializer; import org.apache.kafka.common.serialization.LongSerializer; import org.junit.jupiter.api.AfterAll; @@ -25,8 +24,8 @@ import java.time.Duration; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; - -import static org.junit.jupiter.api.Assertions.*; +import com.google.common.collect.ImmutableList; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @Testcontainers public class MultiplePartitionIntegrationTest { @@ -89,7 +88,7 @@ public class MultiplePartitionIntegrationTest { receivedUserEventList.add(userEvent); System.out.println("User Event ID: " + userEvent.getUserEventId()); }); - assertThat(receivedUserEventList) + assertThat(receivedUserEventList) .isNotEqualTo(sentUserEventList) .containsExactlyInAnyOrderElementsOf(sentUserEventList); } diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index a767133627..0826365f97 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -5,7 +5,6 @@ import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; import org.apache.kafka.clients.admin.Admin; import org.apache.kafka.clients.admin.AdminClientConfig; -import org.apache.kafka.clients.admin.CreateTopicsResult; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; @@ -14,7 +13,6 @@ import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; -import org.apache.kafka.common.KafkaFuture; import org.apache.kafka.common.serialization.LongDeserializer; import org.apache.kafka.common.serialization.LongSerializer; import org.junit.jupiter.api.AfterAll; @@ -29,8 +27,8 @@ import java.time.Duration; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; - -import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.common.collect.ImmutableList; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @Testcontainers public class SinglePartitionIntegrationTest { From 2a6e561f769cd38cfa43c2c1d7742a24b43e52d7 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 18:09:21 -0400 Subject: [PATCH 086/233] Fixed unit test case failures --- .../kafka/message/ordering/payload/UserEvent.java | 10 +++++++--- .../ordering/MultiplePartitionIntegrationTest.java | 6 +++--- .../ordering/SinglePartitionIntegrationTest.java | 3 ++- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java index 67e6b70c08..676b469ce8 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java @@ -42,15 +42,19 @@ public class UserEvent implements Comparable { @Override public boolean equals(Object obj) { - if (obj == this) { + if (this == obj) { return true; } if (!(obj instanceof UserEvent)) { return false; } UserEvent userEvent = (UserEvent) obj; - return Objects.equals(this.userEventId, userEvent.getUserEventId()) - && userEvent.getEventNanoTime() == this.eventNanoTime; + return this.globalSequenceNumber == userEvent.globalSequenceNumber; + } + + @Override + public int hashCode() { + return Objects.hash(globalSequenceNumber); } } diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index 2fde24114c..0405184074 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -71,16 +71,16 @@ public class MultiplePartitionIntegrationTest { void givenMultiplePartitions_whenPublishedToKafkaAndConsumed_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { List sentUserEventList = new ArrayList<>(); List receivedUserEventList = new ArrayList<>(); - for (long count = 1; count <= 10 ; count++) { + for (long sequenceNumber = 1; sequenceNumber <= 10; sequenceNumber++) { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + userEvent.setGlobalSequenceNumber(sequenceNumber); userEvent.setEventNanoTime(System.nanoTime()); - Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, count, userEvent)); + Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, sequenceNumber, userEvent)); sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } - boolean isOrderMaintained = true; consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); ConsumerRecords records = consumer.poll(TIMEOUT_WAIT_FOR_MESSAGES); records.forEach(record -> { diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index 0826365f97..39d298826c 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -78,8 +78,9 @@ public class SinglePartitionIntegrationTest { void givenASinglePartition_whenPublishedToKafkaAndConsumed_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { List sentUserEventList = new ArrayList<>(); List receivedUserEventList = new ArrayList<>(); - for (long count = 1; count <= 10; count++) { + for (long sequenceNumber = 1; sequenceNumber <= 10; sequenceNumber++) { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + userEvent.setGlobalSequenceNumber(sequenceNumber); userEvent.setEventNanoTime(System.nanoTime()); ProducerRecord producerRecord = new ProducerRecord<>(Config.SINGLE_PARTITION_TOPIC, userEvent); Future future = producer.send(producerRecord); From 80cd71fff3e37122a22884fa85b394537e709e20 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 4 Nov 2023 18:33:09 -0400 Subject: [PATCH 087/233] Removing slf4j-log4j12, deleting log4j.properties and adding a standard src/test/resources/logback.xml, since the Kafka libraries use the logback SLF4J binding. --- apache-kafka-2/log4j.properties | 1 - apache-kafka-2/pom.xml | 5 ----- ...ExternalSequenceWithTimeWindowIntegrationTest.java | 9 +++++++-- .../ordering/MultiplePartitionIntegrationTest.java | 8 ++++++-- .../ordering/SinglePartitionIntegrationTest.java | 7 +++++-- apache-kafka-2/src/test/resources/logback.xml | 11 +++++++++++ 6 files changed, 29 insertions(+), 12 deletions(-) delete mode 100644 apache-kafka-2/log4j.properties create mode 100644 apache-kafka-2/src/test/resources/logback.xml diff --git a/apache-kafka-2/log4j.properties b/apache-kafka-2/log4j.properties deleted file mode 100644 index 2173c5d96f..0000000000 --- a/apache-kafka-2/log4j.properties +++ /dev/null @@ -1 +0,0 @@ -log4j.rootLogger=INFO, stdout diff --git a/apache-kafka-2/pom.xml b/apache-kafka-2/pom.xml index d0838a386e..d1f74e8aae 100644 --- a/apache-kafka-2/pom.xml +++ b/apache-kafka-2/pom.xml @@ -23,11 +23,6 @@ slf4j-api ${org.slf4j.version} - - org.slf4j - slf4j-log4j12 - ${org.slf4j.version} - com.google.guava guava diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java index 0c64f663f3..a5ec7a98a3 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.kafka.message.ordering; +import com.baeldung.kafka.headers.KafkaMessageHeaders; import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; @@ -16,6 +17,8 @@ import org.apache.kafka.common.serialization.LongSerializer; 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.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -36,6 +39,8 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); private static final long BUFFER_PERIOD_NS = Duration.ofSeconds(5).toNanos(); + private static Logger logger = LoggerFactory.getLogger(ExternalSequenceWithTimeWindowIntegrationTest.class); + @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); @@ -80,7 +85,7 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, sequenceNumber, userEvent)); sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); - System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); + logger.info("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); @@ -109,7 +114,7 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { Collections.sort(buffer); buffer.forEach(userEvent -> { receivedUserEventList.add(userEvent); - System.out.println("Processing message with Global Sequence number: " + userEvent.getGlobalSequenceNumber() + ", User Event Id: " + userEvent.getUserEventId()); + logger.info("Processing message with Global Sequence number: " + userEvent.getGlobalSequenceNumber() + ", User Event Id: " + userEvent.getUserEventId()); }); buffer.clear(); } diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index 0405184074..adfa9a0399 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -16,6 +16,8 @@ import org.apache.kafka.common.serialization.LongSerializer; 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.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -34,6 +36,8 @@ public class MultiplePartitionIntegrationTest { private static KafkaProducer producer; private static KafkaConsumer consumer; private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); + + private static Logger logger = LoggerFactory.getLogger(MultiplePartitionIntegrationTest.class); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); @@ -78,7 +82,7 @@ public class MultiplePartitionIntegrationTest { Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, sequenceNumber, userEvent)); sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); - System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); + logger.info("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } consumer.subscribe(Collections.singletonList(Config.MULTI_PARTITION_TOPIC)); @@ -86,7 +90,7 @@ public class MultiplePartitionIntegrationTest { records.forEach(record -> { UserEvent userEvent = record.value(); receivedUserEventList.add(userEvent); - System.out.println("User Event ID: " + userEvent.getUserEventId()); + logger.info("User Event ID: " + userEvent.getUserEventId()); }); assertThat(receivedUserEventList) .isNotEqualTo(sentUserEventList) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index 39d298826c..7280a1218a 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -18,6 +18,8 @@ import org.apache.kafka.common.serialization.LongSerializer; 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.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -39,6 +41,7 @@ public class SinglePartitionIntegrationTest { private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); + private static Logger logger = LoggerFactory.getLogger(SinglePartitionIntegrationTest.class); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); @@ -86,7 +89,7 @@ public class SinglePartitionIntegrationTest { Future future = producer.send(producerRecord); sentUserEventList.add(userEvent); RecordMetadata metadata = future.get(); - System.out.println("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); + logger.info("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); } consumer.subscribe(Collections.singletonList(Config.SINGLE_PARTITION_TOPIC)); @@ -94,7 +97,7 @@ public class SinglePartitionIntegrationTest { records.forEach(record -> { UserEvent userEvent = record.value(); receivedUserEventList.add(userEvent); - System.out.println("User Event ID: " + userEvent.getUserEventId()); + logger.info("User Event ID: " + userEvent.getUserEventId()); }); assertThat(receivedUserEventList) .isEqualTo(sentUserEventList) diff --git a/apache-kafka-2/src/test/resources/logback.xml b/apache-kafka-2/src/test/resources/logback.xml new file mode 100644 index 0000000000..6156c2188e --- /dev/null +++ b/apache-kafka-2/src/test/resources/logback.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file From cea912e42ff8fc40bac122b0e78625f5ca92811a Mon Sep 17 00:00:00 2001 From: Vladyslav Chernov Date: Sat, 4 Nov 2023 15:33:30 -0700 Subject: [PATCH 088/233] BAEL-5852: remove comments --- .../src/main/java/com/baeldung/holder/SupplierService.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java index 473a4de423..66889f99bf 100644 --- a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java @@ -2,8 +2,6 @@ package com.baeldung.holder; public class SupplierService { public void getSupplierByZipCode(String zip, Holder resultHolder) { - // Let's pretend we did some work here to get the supplier - // And let's say all zip codes starting with "9" are valid, just for this example if (zip.startsWith("9")) { resultHolder.value = true; } else { From ee97389e28c04795bd0c45a543a5eebfce05429f Mon Sep 17 00:00:00 2001 From: Vladyslav Chernov Date: Sat, 4 Nov 2023 15:38:37 -0700 Subject: [PATCH 089/233] BAEL-5755: remove BAEL-5852 commits --- .../main/java/com/baeldung/holder/Holder.java | 9 ------ .../com/baeldung/holder/SupplierService.java | 11 ------- .../holder/SupplierServiceUnitTest.java | 31 ------------------- 3 files changed, 51 deletions(-) delete mode 100644 core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/Holder.java delete mode 100644 core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java delete mode 100644 core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/holder/SupplierServiceUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/Holder.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/Holder.java deleted file mode 100644 index da066ee5c6..0000000000 --- a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/Holder.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.holder; - -public class Holder { - public T value; - - public Holder(T value) { - this.value = value; - } -} diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java deleted file mode 100644 index 66889f99bf..0000000000 --- a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/holder/SupplierService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.holder; - -public class SupplierService { - public void getSupplierByZipCode(String zip, Holder resultHolder) { - if (zip.startsWith("9")) { - resultHolder.value = true; - } else { - resultHolder.value = false; - } - } -} diff --git a/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/holder/SupplierServiceUnitTest.java b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/holder/SupplierServiceUnitTest.java deleted file mode 100644 index e1446fc229..0000000000 --- a/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/holder/SupplierServiceUnitTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.holder; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; - -public class SupplierServiceUnitTest { - - @Test - public void givenValidZipCode_whenGetSupplierByZipCode_thenTrue() { - SupplierService service = new SupplierService(); - Holder resultHolder = new Holder<>(false); - String zipCode = "98682"; - - service.getSupplierByZipCode(zipCode, resultHolder); - - assertTrue(resultHolder.value); - } - - @Test - public void givenInvalidZipCode_whenGetSupplierByZipCode_thenFalse() { - SupplierService service = new SupplierService(); - Holder resultHolder = new Holder<>(true); - String zipCode = "12345"; - - service.getSupplierByZipCode(zipCode, resultHolder); - - assertFalse(resultHolder.value); - } -} From 88a874082de402224520387bfb59d2ed05c0eb78 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 12:49:07 +0800 Subject: [PATCH 090/233] Update README.md [skip ci] --- core-java-modules/core-java-strings/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md index dbbfcc79b6..e782793fea 100644 --- a/core-java-modules/core-java-strings/README.md +++ b/core-java-modules/core-java-strings/README.md @@ -15,3 +15,4 @@ Listed here there are only those articles that does not fit into other core-java - [Java Multi-line String](https://www.baeldung.com/java-multiline-string) - [Reuse StringBuilder for Efficiency](https://www.baeldung.com/java-reuse-stringbuilder-for-efficiency) - [How to Iterate Over the String Characters in Java](https://www.baeldung.com/java-iterate-string-characters) +- [Passing Strings by Reference in Java](https://www.baeldung.com/java-method-pass-string-reference) From 252696e2b3572fed41fee8cd65e51ef483ddc010 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 12:58:15 +0800 Subject: [PATCH 091/233] Update README.md [skip ci] --- core-java-modules/core-java-concurrency-basic-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-basic-3/README.md b/core-java-modules/core-java-concurrency-basic-3/README.md index 179a69495c..09d085a32b 100644 --- a/core-java-modules/core-java-concurrency-basic-3/README.md +++ b/core-java-modules/core-java-concurrency-basic-3/README.md @@ -11,4 +11,5 @@ This module contains articles about basic Java concurrency. - [CompletableFuture and ThreadPool in Java](https://www.baeldung.com/java-completablefuture-threadpool) - [CompletableFuture allOf().join() vs. CompletableFuture.join()](https://www.baeldung.com/java-completablefuture-allof-join) - [Retry Logic with CompletableFuture](https://www.baeldung.com/java-completablefuture-retry-logic) +- [Convert From List of CompletableFuture to CompletableFuture List](https://www.baeldung.com/java-completablefuture-list-convert) - [[<-- Prev]](../core-java-concurrency-basic-2) From 67d1902524af4d229dd672b8fb1b57fac0cd68de Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 13:02:33 +0800 Subject: [PATCH 092/233] Update README.md [skip ci] --- core-java-modules/core-java-io-apis-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-io-apis-2/README.md b/core-java-modules/core-java-io-apis-2/README.md index 3ec3220424..043e0c1ee3 100644 --- a/core-java-modules/core-java-io-apis-2/README.md +++ b/core-java-modules/core-java-io-apis-2/README.md @@ -8,3 +8,4 @@ This module contains articles about core Java input/output(IO) APIs. - [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty) - [Converting Relative to Absolute Paths in Java](https://www.baeldung.com/java-from-relative-to-absolute-paths) - [Detect EOF in Java](https://www.baeldung.com/java-file-detect-end-of-file) +- [PrintWriter vs. FileWriter in Java](https://www.baeldung.com/java-printwriter-filewriter-difference) From 9d7705309e0e2453b128b000bb8a10939866fdde Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 13:08:59 +0800 Subject: [PATCH 093/233] Create README.md [skip ci] --- persistence-modules/spring-jdbc-2/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 persistence-modules/spring-jdbc-2/README.md diff --git a/persistence-modules/spring-jdbc-2/README.md b/persistence-modules/spring-jdbc-2/README.md new file mode 100644 index 0000000000..5edb34f4c5 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [A Guide to Spring 6 JdbcClient API](https://www.baeldung.com/spring-6-jdbcclient-api) From 686196c0402c773681add1669951be7ebc86b56c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 13:16:48 +0800 Subject: [PATCH 094/233] Update README.md [skip ci] --- core-java-modules/core-java-io-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-io-5/README.md b/core-java-modules/core-java-io-5/README.md index 3cc514e087..4578cf3777 100644 --- a/core-java-modules/core-java-io-5/README.md +++ b/core-java-modules/core-java-io-5/README.md @@ -5,5 +5,6 @@ This module contains articles about core Java input and output (IO) ### Relevant Articles: - [Get File Extension From MIME Type in Java](https://www.baeldung.com/java-mime-type-file-extension) - [How to Remove Line Breaks From a File in Java](https://www.baeldung.com/java-file-remove-line-breaks) +- [Difference Between ZipFile and ZipInputStream in Java](https://www.baeldung.com/java-zipfile-vs-zipinputstream) - [[<-- Prev]](/core-java-modules/core-java-io-4) From 4ee135819b1b11dc3b1cd6505fc8602d3c85afc0 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 13:24:26 +0800 Subject: [PATCH 095/233] Create README.md [skip ci] --- libraries-llms/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 libraries-llms/README.md diff --git a/libraries-llms/README.md b/libraries-llms/README.md new file mode 100644 index 0000000000..78a621ffa6 --- /dev/null +++ b/libraries-llms/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Introduction to LangChain](https://www.baeldung.com/java-langchain-basics) From ac7cedb7efabac67821b43ad7bb39b9c22d7942a Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 13:30:32 +0800 Subject: [PATCH 096/233] Update README.md [skip ci] --- xml-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/xml-2/README.md b/xml-2/README.md index e91078dbf0..cc60ae2764 100644 --- a/xml-2/README.md +++ b/xml-2/README.md @@ -7,3 +7,4 @@ This module contains articles about eXtensible Markup Language (XML) - [Pretty-Print XML in Java](https://www.baeldung.com/java-pretty-print-xml) - [Validate an XML File Against an XSD File](https://www.baeldung.com/java-validate-xml-xsd) - [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) From 0391a9c840e86573800ad1032b9a58142b45f5bc Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 13:35:00 +0800 Subject: [PATCH 097/233] Update README.md [skip ci] --- xml-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/xml-2/README.md b/xml-2/README.md index cc60ae2764..e9c1a07586 100644 --- a/xml-2/README.md +++ b/xml-2/README.md @@ -8,3 +8,4 @@ This module contains articles about eXtensible Markup Language (XML) - [Validate an XML File Against an XSD File](https://www.baeldung.com/java-validate-xml-xsd) - [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) From 4f98043b953827532f27fb51131def85edaeaa01 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 13:39:48 +0800 Subject: [PATCH 098/233] Update README.md [skip ci] --- spring-cucumber/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-cucumber/README.md b/spring-cucumber/README.md index 85bc1f65d5..87623b28d4 100644 --- a/spring-cucumber/README.md +++ b/spring-cucumber/README.md @@ -4,3 +4,4 @@ This module contains articles about Spring testing with Cucumber ### Relevant Articles: - [Cucumber Spring Integration](https://www.baeldung.com/cucumber-spring-integration) +- [Overriding Cucumber Option Values](https://www.baeldung.com/java-overriding-cucumber-option-values) From 9ba05068aa4aab95407db2dd16079078f54bf750 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 5 Nov 2023 13:45:06 +0800 Subject: [PATCH 099/233] Create README.md [skip ci] --- .../src/test/java/com/baeldung/algorithms/connect4/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/README.md diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/README.md b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/README.md new file mode 100644 index 0000000000..55bc2abec5 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Implement Connect 4 Game with Java](https://www.baeldung.com/java-connect-4-game) From dad8f5cf2b58a7fa83e430743488a44f8ac02576 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 5 Nov 2023 11:48:26 +0530 Subject: [PATCH 100/233] JAVA-27180 Upgrade hibernate-validator version in hibernate-mapping module --- persistence-modules/hibernate-mapping/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 1e3dc8be5f..0ce112b9e6 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -20,7 +20,7 @@ test - org.hibernate + org.hibernate.orm hibernate-core ${hibernate.version} @@ -36,7 +36,7 @@ - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} @@ -82,7 +82,7 @@ 2.1.214 6.1.7.Final 2.21.1 - 8.0.0.Final + 8.0.1.Final 3.0.1-b11 1.1 1.4.2 From a8af97e2eb5f534576447dddacc6ce8c79e206b5 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 5 Nov 2023 12:40:54 +0530 Subject: [PATCH 101/233] JAVA-27181 Update hibernate-validator version in jpa-hibarnate-cascade-type module --- .../jpa-hibernate-cascade-type/pom.xml | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/persistence-modules/jpa-hibernate-cascade-type/pom.xml b/persistence-modules/jpa-hibernate-cascade-type/pom.xml index fd0ae117c7..90dd826a6e 100644 --- a/persistence-modules/jpa-hibernate-cascade-type/pom.xml +++ b/persistence-modules/jpa-hibernate-cascade-type/pom.xml @@ -24,27 +24,15 @@ - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} - - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish - javax.el - ${org.glassfish.javax.el.version} - 5.4.3.Final - 6.0.17.Final - 3.0.0 - 3.0.1-b11 + 8.0.1.Final \ No newline at end of file From 9e0b0945f7820d8e431b44c49f3a47a2d70be952 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 5 Nov 2023 13:05:01 +0530 Subject: [PATCH 102/233] JAVA-27182 Upgrade hibernate-validator version in spring-data-couchbase-2 module --- persistence-modules/spring-data-couchbase-2/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-data-couchbase-2/pom.xml b/persistence-modules/spring-data-couchbase-2/pom.xml index deb7d3b524..45462d477e 100644 --- a/persistence-modules/spring-data-couchbase-2/pom.xml +++ b/persistence-modules/spring-data-couchbase-2/pom.xml @@ -40,7 +40,7 @@ - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} @@ -71,7 +71,7 @@ 6.0.6 5.0.3 - 8.0.0.Final + 8.0.1.Final 2.12.2 From a575de93b1025cf723f87f98ebbbfe45bc2a6952 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 5 Nov 2023 13:36:30 +0530 Subject: [PATCH 103/233] JAVA-27183 Upgrade hibernate-validator version in spring-jpa module --- persistence-modules/spring-jpa/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index c08e4f823a..10e44c0ce4 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -71,7 +71,7 @@ - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} @@ -122,7 +122,7 @@ 6.0.0 - 8.0.0.Final + 8.0.1.Final 2.0.2 2.1.214 5.0.0 From 790ec2b7fb71711ab9a8c793b6d101ac3e27cae8 Mon Sep 17 00:00:00 2001 From: timis1 Date: Sun, 5 Nov 2023 23:27:26 +0200 Subject: [PATCH 104/233] JAVA-27237 Review log statements for projects - Week 16 - 2023 (moved-13) (conti-1) --- .../test/resources/META-INF/persistence.xml | 2 +- .../src/test/resources/logback-test.xml | 2 +- .../src/test/resources/logback-test.xml | 2 ++ .../config/src/main/resources/logback.xml | 6 ++++++ .../src/main/resources/logback.xml | 18 +++++++++++++++++ .../src/main/resources/logback.xml | 20 +++++++++++++++++++ .../src/test/resources/logback-test.xml | 6 ++++++ 7 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/src/main/resources/logback.xml create mode 100644 spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-echo-demo/src/main/resources/logback.xml diff --git a/persistence-modules/deltaspike/src/test/resources/META-INF/persistence.xml b/persistence-modules/deltaspike/src/test/resources/META-INF/persistence.xml index ffcf20878c..60b415abd7 100644 --- a/persistence-modules/deltaspike/src/test/resources/META-INF/persistence.xml +++ b/persistence-modules/deltaspike/src/test/resources/META-INF/persistence.xml @@ -35,7 +35,7 @@ - + diff --git a/persistence-modules/deltaspike/src/test/resources/logback-test.xml b/persistence-modules/deltaspike/src/test/resources/logback-test.xml index bdc292924b..6a9aa37e7f 100644 --- a/persistence-modules/deltaspike/src/test/resources/logback-test.xml +++ b/persistence-modules/deltaspike/src/test/resources/logback-test.xml @@ -7,7 +7,7 @@ - + diff --git a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/resources/logback-test.xml index 8d4771e308..b9242f40a8 100644 --- a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/resources/logback-test.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/resources/logback-test.xml @@ -6,6 +6,8 @@ + + diff --git a/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/resources/logback.xml b/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/resources/logback.xml index 7d900d8ea8..896eaf9c88 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/resources/logback.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/resources/logback.xml @@ -7,6 +7,12 @@ + + + + + + diff --git a/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/src/main/resources/logback.xml b/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/src/main/resources/logback.xml new file mode 100644 index 0000000000..d944288ca4 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/src/main/resources/logback.xml @@ -0,0 +1,18 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-echo-demo/src/main/resources/logback.xml b/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-echo-demo/src/main/resources/logback.xml new file mode 100644 index 0000000000..5f3e764e22 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-echo-demo/src/main/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-jenkins-pipeline/src/test/resources/logback-test.xml b/spring-jenkins-pipeline/src/test/resources/logback-test.xml index b9242f40a8..69ab60701a 100644 --- a/spring-jenkins-pipeline/src/test/resources/logback-test.xml +++ b/spring-jenkins-pipeline/src/test/resources/logback-test.xml @@ -8,6 +8,12 @@ + + + + + + From 63953b74f3cef3f6989bffa257ec32e0578c64fc Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Mon, 6 Nov 2023 02:26:25 +0100 Subject: [PATCH 105/233] Nth substring (#15120) * [nth-substring] nth substring in a string * [nth-substring] find n-th substring --- .../FindNthSubstringIndexUnitTest.java | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nthsubstring/FindNthSubstringIndexUnitTest.java diff --git a/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nthsubstring/FindNthSubstringIndexUnitTest.java b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nthsubstring/FindNthSubstringIndexUnitTest.java new file mode 100644 index 0000000000..779585ffb0 --- /dev/null +++ b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nthsubstring/FindNthSubstringIndexUnitTest.java @@ -0,0 +1,106 @@ +package com.baeldung.nthsubstring; + +import org.junit.jupiter.api.Test; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class FindNthSubstringIndexUnitTest { + // "0 8 16 24 " + private final static String INPUT = "a word, a word, a word, a word"; + + @Test + void whenCallingIndexOfTwice_thenGetTheSecondSubstringIndex() { + int firstIdx = INPUT.indexOf("a"); + int result = INPUT.indexOf("a", firstIdx + "a".length()); + assertEquals(8, result); + } + + // the recursive approach + static int nthIndexOf(String input, String substring, int nth) { + if (nth == 1) { + return input.indexOf(substring); + } else { + return input.indexOf(substring, nthIndexOf(input, substring, nth - 1) + substring.length()); + } + } + + @Test + void whenCallingRecursiveMethod_thenGetTheExpectedResult() { + int result1 = nthIndexOf(INPUT, "a", 1); + assertEquals(0, result1); + + int result2 = nthIndexOf(INPUT, "a", 2); + assertEquals(8, result2); + + int result3 = nthIndexOf(INPUT, "a", 3); + assertEquals(16, result3); + + int result4 = nthIndexOf(INPUT, "a", 4); + assertEquals(24, result4); + + int result5 = nthIndexOf(INPUT, "a", 5); + assertEquals(-1, result5); + } + + // loop-based approach + static int nthIndexOf2(String input, String substring, int nth) { + int index = -1; + while (nth > 0) { + index = input.indexOf(substring, index + substring.length()); + if (index == -1) { + return -1; + } + nth--; + } + return index; + } + + @Test + void whenCallingLoopBasedMethod_thenGetTheExpectedResult() { + int result1 = nthIndexOf2(INPUT, "a", 1); + assertEquals(0, result1); + + int result2 = nthIndexOf2(INPUT, "a", 2); + assertEquals(8, result2); + + int result3 = nthIndexOf2(INPUT, "a", 3); + assertEquals(16, result3); + + int result4 = nthIndexOf2(INPUT, "a", 4); + assertEquals(24, result4); + + int result5 = nthIndexOf2(INPUT, "a", 5); + assertEquals(-1, result5); + } + + static int nthOccurrenceIndex(String input, String regexPattern, int nth) { + Matcher matcher = Pattern.compile(regexPattern).matcher(INPUT); + for (int i = 0; i < nth; i++) { + if (!matcher.find()) { + return -1; + } + } + return matcher.start(); + } + + @Test + void whenCallingRegexBasedMethod_thenGetTheExpectedResult() { + int result1 = nthOccurrenceIndex(INPUT, "a", 1); + assertEquals(0, result1); + + int result2 = nthOccurrenceIndex(INPUT, "a", 2); + assertEquals(8, result2); + + int result3 = nthOccurrenceIndex(INPUT, "a", 3); + assertEquals(16, result3); + + int result4 = nthOccurrenceIndex(INPUT, "a", 4); + assertEquals(24, result4); + + int result5 = nthOccurrenceIndex(INPUT, "a", 5); + assertEquals(-1, result5); + } +} \ No newline at end of file From da8167cf17cd23cc083853ae286bd836d686984d Mon Sep 17 00:00:00 2001 From: Rajat Garg Date: Mon, 6 Nov 2023 07:15:53 +0530 Subject: [PATCH 106/233] [BAEL-7069] Pass list as a query parameter in Jersey (#15051) * Pass list as a query parameter in Jersey * Address review comment * Address review comment --------- Co-authored-by: rajatgarg --- .../client/listdemo/JerseyListDemo.java | 15 +++++ .../jersey/client/listdemo/ListDemoApp.java | 9 +++ .../listdemo/JerseyListDemoUnitTest.java | 57 +++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 jersey/src/main/java/com/baeldung/jersey/client/listdemo/JerseyListDemo.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/client/listdemo/ListDemoApp.java create mode 100644 jersey/src/test/java/com/baeldung/jersey/client/listdemo/JerseyListDemoUnitTest.java diff --git a/jersey/src/main/java/com/baeldung/jersey/client/listdemo/JerseyListDemo.java b/jersey/src/main/java/com/baeldung/jersey/client/listdemo/JerseyListDemo.java new file mode 100644 index 0000000000..52be341653 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/client/listdemo/JerseyListDemo.java @@ -0,0 +1,15 @@ +package com.baeldung.jersey.client.listdemo; + +import java.util.List; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.QueryParam; + +@Path("/") +public class JerseyListDemo { + @GET + public String getItems(@QueryParam("items") List items) { + return "Received items: " + items; + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/client/listdemo/ListDemoApp.java b/jersey/src/main/java/com/baeldung/jersey/client/listdemo/ListDemoApp.java new file mode 100644 index 0000000000..7f5be883da --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/client/listdemo/ListDemoApp.java @@ -0,0 +1,9 @@ +package com.baeldung.jersey.client.listdemo; + +import org.glassfish.jersey.server.ResourceConfig; + +public class ListDemoApp extends ResourceConfig { + public ListDemoApp() { + packages("com.baeldung.jersey.client.listdemo"); + } +} diff --git a/jersey/src/test/java/com/baeldung/jersey/client/listdemo/JerseyListDemoUnitTest.java b/jersey/src/test/java/com/baeldung/jersey/client/listdemo/JerseyListDemoUnitTest.java new file mode 100644 index 0000000000..0aff6dcabf --- /dev/null +++ b/jersey/src/test/java/com/baeldung/jersey/client/listdemo/JerseyListDemoUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.jersey.client.listdemo; + +import static org.junit.Assert.assertEquals; + +import java.net.URI; +import java.util.Arrays; +import java.util.List; + +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.Test; + +import jakarta.ws.rs.core.Application; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriBuilder; + +public class JerseyListDemoUnitTest extends JerseyTest { + + @Override + protected Application configure() { + enable(TestProperties.LOG_TRAFFIC); + enable(TestProperties.DUMP_ENTITY); + return new ListDemoApp(); + } + + @Test + public void givenList_whenUsingQueryParam_thenPassParamsAsList() { + Response response = target("/") + .queryParam("items", "item1", "item2") + .request() + .get(); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + assertEquals("Received items: [item1, item2]", response.readEntity(String.class)); + } + + @Test + public void givenList_whenUsingCommaSeparatedString_thenPassParamsAsList() { + Response response = target("/") + .queryParam("items", "item1,item2") + .request() + .get(); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + assertEquals("Received items: [item1,item2]", response.readEntity(String.class)); + } + + @Test + public void givenList_whenUsingUriBuilder_thenPassParamsAsList() { + List itemsList = Arrays.asList("item1", "item2"); + UriBuilder builder = UriBuilder.fromUri("/"); + for (String item : itemsList) { + builder.queryParam("items", item); + } + URI uri = builder.build(); + String expectedUri = "/?items=item1&items=item2"; + assertEquals(expectedUri, uri.toString()); + } +} From 5d3f08d0e915ca8b077666253fa4b3899475155c Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 5 Nov 2023 21:32:49 -0500 Subject: [PATCH 107/233] Fix the whitespace and newline issues - wuth code formatter --- .../message/ordering/payload/UserEvent.java | 3 ++- .../serialization/JacksonDeserializer.java | 3 ++- .../serialization/JacksonSerializer.java | 1 + ...SequenceWithTimeWindowIntegrationTest.java | 22 ++++++++++++------- .../MultiplePartitionIntegrationTest.java | 14 ++++++++---- .../SinglePartitionIntegrationTest.java | 19 +++++++++------- 6 files changed, 40 insertions(+), 22 deletions(-) diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java index 676b469ce8..99e0cc6c7e 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/payload/UserEvent.java @@ -1,13 +1,14 @@ package com.baeldung.kafka.message.ordering.payload; import java.util.Objects; + public class UserEvent implements Comparable { private String userEventId; private long eventNanoTime; private long globalSequenceNumber; @SuppressWarnings("unused") - public UserEvent(){ + public UserEvent() { // Required for Jackson Serialization and Deserialization } diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java index 4868ecaf2e..cf72ab12df 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonDeserializer.java @@ -1,6 +1,8 @@ package com.baeldung.kafka.message.ordering.serialization; + import com.baeldung.kafka.message.ordering.Config; import com.fasterxml.jackson.databind.ObjectMapper; + import org.apache.kafka.common.serialization.Deserializer; import java.util.Map; @@ -12,7 +14,6 @@ public class JacksonDeserializer implements Deserializer { private final ObjectMapper objectMapper = new ObjectMapper(); private Class type; - @Override public void configure(Map configs, boolean isKey) { this.type = (Class) configs.get(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS); diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java index 4c081de3cc..b2ace3b8ed 100644 --- a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/ordering/serialization/JacksonSerializer.java @@ -1,6 +1,7 @@ package com.baeldung.kafka.message.ordering.serialization; import com.fasterxml.jackson.databind.ObjectMapper; + import org.apache.kafka.common.serialization.Serializer; /** diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java index a5ec7a98a3..caffe12620 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java @@ -4,6 +4,7 @@ import com.baeldung.kafka.headers.KafkaMessageHeaders; import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; + import org.apache.kafka.clients.admin.*; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; @@ -23,11 +24,14 @@ import org.testcontainers.containers.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; + import java.time.Duration; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; + import com.google.common.collect.ImmutableList; + import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @Testcontainers @@ -37,8 +41,8 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { private static KafkaProducer producer; private static KafkaConsumer consumer; private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); - private static final long BUFFER_PERIOD_NS = Duration.ofSeconds(5).toNanos(); - + private static final long BUFFER_PERIOD_NS = Duration.ofSeconds(5) + .toNanos(); private static Logger logger = LoggerFactory.getLogger(ExternalSequenceWithTimeWindowIntegrationTest.class); @Container @@ -66,7 +70,9 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); - admin.createTopics(ImmutableList.of(new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR))).all().get(); + admin.createTopics(ImmutableList.of(new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR))) + .all() + .get(); } @AfterAll @@ -78,8 +84,9 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { void givenMultiplePartitions_whenPublishedToKafkaAndConsumedWithExtSeqNumberAndTimeWindow_thenCheckForMessageOrder() throws ExecutionException, InterruptedException { List sentUserEventList = new ArrayList<>(); List receivedUserEventList = new ArrayList<>(); - for (long sequenceNumber = 1; sequenceNumber <= 10 ; sequenceNumber++) { - UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + for (long sequenceNumber = 1; sequenceNumber <= 10; sequenceNumber++) { + UserEvent userEvent = new UserEvent(UUID.randomUUID() + .toString()); userEvent.setEventNanoTime(System.nanoTime()); userEvent.setGlobalSequenceNumber(sequenceNumber); Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, sequenceNumber, userEvent)); @@ -105,9 +112,8 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { buffer.add(record.value()); }); } - assertThat(receivedUserEventList) - .isEqualTo(sentUserEventList) - .containsExactlyElementsOf(sentUserEventList); + assertThat(receivedUserEventList).isEqualTo(sentUserEventList) + .containsExactlyElementsOf(sentUserEventList); } private static void processBuffer(List buffer, List receivedUserEventList) { diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java index adfa9a0399..bb25486f00 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; + import org.apache.kafka.clients.admin.*; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; @@ -22,11 +23,14 @@ import org.testcontainers.containers.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; + import java.time.Duration; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; + import com.google.common.collect.ImmutableList; + import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @Testcontainers @@ -63,7 +67,9 @@ public class MultiplePartitionIntegrationTest { admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); - admin.createTopics(ImmutableList.of(new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR))).all().get(); + admin.createTopics(ImmutableList.of(new NewTopic(Config.MULTI_PARTITION_TOPIC, Config.MULTIPLE_PARTITIONS, Config.REPLICATION_FACTOR))) + .all() + .get(); } @AfterAll @@ -76,7 +82,8 @@ public class MultiplePartitionIntegrationTest { List sentUserEventList = new ArrayList<>(); List receivedUserEventList = new ArrayList<>(); for (long sequenceNumber = 1; sequenceNumber <= 10; sequenceNumber++) { - UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + UserEvent userEvent = new UserEvent(UUID.randomUUID() + .toString()); userEvent.setGlobalSequenceNumber(sequenceNumber); userEvent.setEventNanoTime(System.nanoTime()); Future future = producer.send(new ProducerRecord<>(Config.MULTI_PARTITION_TOPIC, sequenceNumber, userEvent)); @@ -92,8 +99,7 @@ public class MultiplePartitionIntegrationTest { receivedUserEventList.add(userEvent); logger.info("User Event ID: " + userEvent.getUserEventId()); }); - assertThat(receivedUserEventList) - .isNotEqualTo(sentUserEventList) + assertThat(receivedUserEventList).isNotEqualTo(sentUserEventList) .containsExactlyInAnyOrderElementsOf(sentUserEventList); } } diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java index 7280a1218a..8656df1bf3 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung.kafka.message.ordering; import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; + import org.apache.kafka.clients.admin.Admin; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.NewTopic; @@ -29,7 +30,9 @@ import java.time.Duration; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; + import com.google.common.collect.ImmutableList; + import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @Testcontainers @@ -56,7 +59,6 @@ public class SinglePartitionIntegrationTest { producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JacksonSerializer.class.getName()); - producer = new KafkaProducer<>(producerProperties); Properties consumerProperties = new Properties(); consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); @@ -65,11 +67,12 @@ public class SinglePartitionIntegrationTest { consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); consumerProperties.put(Config.CONSUMER_VALUE_DESERIALIZER_SERIALIZED_CLASS, UserEvent.class); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group"); - consumer = new KafkaConsumer<>(consumerProperties); admin = Admin.create(adminProperties); - - - admin.createTopics(ImmutableList.of(new NewTopic(Config.SINGLE_PARTITION_TOPIC, Config.SINGLE_PARTITION, Config.REPLICATION_FACTOR))).all().get(); + producer = new KafkaProducer<>(producerProperties); + consumer = new KafkaConsumer<>(consumerProperties); + admin.createTopics(ImmutableList.of(new NewTopic(Config.SINGLE_PARTITION_TOPIC, Config.SINGLE_PARTITION, Config.REPLICATION_FACTOR))) + .all() + .get(); } @AfterAll @@ -82,7 +85,8 @@ public class SinglePartitionIntegrationTest { List sentUserEventList = new ArrayList<>(); List receivedUserEventList = new ArrayList<>(); for (long sequenceNumber = 1; sequenceNumber <= 10; sequenceNumber++) { - UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + UserEvent userEvent = new UserEvent(UUID.randomUUID() + .toString()); userEvent.setGlobalSequenceNumber(sequenceNumber); userEvent.setEventNanoTime(System.nanoTime()); ProducerRecord producerRecord = new ProducerRecord<>(Config.SINGLE_PARTITION_TOPIC, userEvent); @@ -99,8 +103,7 @@ public class SinglePartitionIntegrationTest { receivedUserEventList.add(userEvent); logger.info("User Event ID: " + userEvent.getUserEventId()); }); - assertThat(receivedUserEventList) - .isEqualTo(sentUserEventList) + assertThat(receivedUserEventList).isEqualTo(sentUserEventList) .containsExactlyElementsOf(sentUserEventList); } } From 6e758b8438de2bd367ccf741fa2a53a01c9399ec Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 5 Nov 2023 21:39:02 -0500 Subject: [PATCH 108/233] The test names should be LiveTest not IntegrationTest, as per the other similar tests in this module. This naming is used to mark these tests as manually runnable only, since they are heavy tests that spin up a container, so we don't want them to be run as part of the automatic CI build. Same for the other tests. --- ...Test.java => ExternalSequenceWithTimeWindowLiveTest.java} | 5 ++--- ...onIntegrationTest.java => MultiplePartitionLiveTest.java} | 4 ++-- ...tionIntegrationTest.java => SinglePartitionLiveTest.java} | 4 ++-- 3 files changed, 6 insertions(+), 7 deletions(-) rename apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/{ExternalSequenceWithTimeWindowIntegrationTest.java => ExternalSequenceWithTimeWindowLiveTest.java} (97%) rename apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/{MultiplePartitionIntegrationTest.java => MultiplePartitionLiveTest.java} (98%) rename apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/{SinglePartitionIntegrationTest.java => SinglePartitionLiveTest.java} (98%) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowLiveTest.java similarity index 97% rename from apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java rename to apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowLiveTest.java index caffe12620..f36c6ebd63 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/ExternalSequenceWithTimeWindowLiveTest.java @@ -1,6 +1,5 @@ package com.baeldung.kafka.message.ordering; -import com.baeldung.kafka.headers.KafkaMessageHeaders; import com.baeldung.kafka.message.ordering.payload.UserEvent; import com.baeldung.kafka.message.ordering.serialization.JacksonDeserializer; import com.baeldung.kafka.message.ordering.serialization.JacksonSerializer; @@ -35,7 +34,7 @@ import com.google.common.collect.ImmutableList; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @Testcontainers -public class ExternalSequenceWithTimeWindowIntegrationTest { +public class ExternalSequenceWithTimeWindowLiveTest { private static Admin admin; private static KafkaProducer producer; @@ -43,7 +42,7 @@ public class ExternalSequenceWithTimeWindowIntegrationTest { private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); private static final long BUFFER_PERIOD_NS = Duration.ofSeconds(5) .toNanos(); - private static Logger logger = LoggerFactory.getLogger(ExternalSequenceWithTimeWindowIntegrationTest.class); + private static Logger logger = LoggerFactory.getLogger(ExternalSequenceWithTimeWindowLiveTest.class); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionLiveTest.java similarity index 98% rename from apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java rename to apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionLiveTest.java index bb25486f00..407b4d52a9 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/MultiplePartitionLiveTest.java @@ -34,14 +34,14 @@ import com.google.common.collect.ImmutableList; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @Testcontainers -public class MultiplePartitionIntegrationTest { +public class MultiplePartitionLiveTest { private static Admin admin; private static KafkaProducer producer; private static KafkaConsumer consumer; private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); - private static Logger logger = LoggerFactory.getLogger(MultiplePartitionIntegrationTest.class); + private static Logger logger = LoggerFactory.getLogger(MultiplePartitionLiveTest.class); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionLiveTest.java similarity index 98% rename from apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java rename to apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionLiveTest.java index 8656df1bf3..9c6a15ebeb 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionIntegrationTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/ordering/SinglePartitionLiveTest.java @@ -36,7 +36,7 @@ import com.google.common.collect.ImmutableList; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @Testcontainers -public class SinglePartitionIntegrationTest { +public class SinglePartitionLiveTest { private static Admin admin; private static KafkaProducer producer; @@ -44,7 +44,7 @@ public class SinglePartitionIntegrationTest { private static final Duration TIMEOUT_WAIT_FOR_MESSAGES = Duration.ofSeconds(5); - private static Logger logger = LoggerFactory.getLogger(SinglePartitionIntegrationTest.class); + private static Logger logger = LoggerFactory.getLogger(SinglePartitionLiveTest.class); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); From 91293d64b0be2e2d1bb61d44de5fa85aa5328fee Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Mon, 6 Nov 2023 08:52:53 +0000 Subject: [PATCH 109/233] =?UTF-8?q?[JAVA-26049]=20Upgraded=20spring-boot-e?= =?UTF-8?q?nvironment=20module=20to=20spring-boot=203=E2=80=A6=20(#14994)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../spring-boot-environment/pom.xml | 22 +++++++++++-------- .../main/resources/META-INF/spring.factories | 6 ----- .../META-INF/spring/AutoConfiguration.imports | 1 + .../META-INF/spring/spring.factories | 3 +++ 4 files changed, 17 insertions(+), 15 deletions(-) delete mode 100644 spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring.factories create mode 100644 spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring/AutoConfiguration.imports create mode 100644 spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring/spring.factories diff --git a/spring-boot-modules/spring-boot-environment/pom.xml b/spring-boot-modules/spring-boot-environment/pom.xml index 4bdb35358c..9974d41f45 100644 --- a/spring-boot-modules/spring-boot-environment/pom.xml +++ b/spring-boot-modules/spring-boot-environment/pom.xml @@ -9,9 +9,10 @@ Demo project for Spring Boot - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -46,11 +47,6 @@ h2 runtime - - javax.persistence - javax.persistence-api - ${jpa.version} - com.google.guava guava @@ -96,6 +92,15 @@ + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.environmentpostprocessor.PriceCalculationApplication + + + @@ -151,7 +156,6 @@ - 2.2 3.1.7 4.5.8 2021.0.0 diff --git a/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring.factories b/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring.factories deleted file mode 100644 index c36b67f8d7..0000000000 --- a/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,6 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig - -org.springframework.boot.env.EnvironmentPostProcessor=\ -com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor - diff --git a/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring/AutoConfiguration.imports b/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring/AutoConfiguration.imports new file mode 100644 index 0000000000..350e2efa94 --- /dev/null +++ b/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring/AutoConfiguration.imports @@ -0,0 +1 @@ +com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig diff --git a/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring/spring.factories b/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring/spring.factories new file mode 100644 index 0000000000..ff5e404c84 --- /dev/null +++ b/spring-boot-modules/spring-boot-environment/src/main/resources/META-INF/spring/spring.factories @@ -0,0 +1,3 @@ +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor + From 81be7c4ad51e4f88a53d99dc834e8b7fd7098d80 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Mon, 6 Nov 2023 09:45:12 +0000 Subject: [PATCH 110/233] [JAVA-26374-boot-runtime] Moved "CORS with Spring" article to spring-boot-runtime (#15096) --- spring-boot-modules/spring-boot-runtime-2/README.md | 1 - spring-boot-modules/spring-boot-runtime/README.md | 1 + .../src/main/java/com/baeldung/cors/Account.java | 0 .../src/main/java/com/baeldung/cors/AccountController.java | 0 .../src/main/java/com/baeldung/cors/config/WebConfig.java | 0 5 files changed, 1 insertion(+), 1 deletion(-) rename spring-boot-modules/{spring-boot-runtime-2 => spring-boot-runtime}/src/main/java/com/baeldung/cors/Account.java (100%) rename spring-boot-modules/{spring-boot-runtime-2 => spring-boot-runtime}/src/main/java/com/baeldung/cors/AccountController.java (100%) rename spring-boot-modules/{spring-boot-runtime-2 => spring-boot-runtime}/src/main/java/com/baeldung/cors/config/WebConfig.java (100%) diff --git a/spring-boot-modules/spring-boot-runtime-2/README.md b/spring-boot-modules/spring-boot-runtime-2/README.md index f439b0d0bd..3ee05ccc83 100644 --- a/spring-boot-modules/spring-boot-runtime-2/README.md +++ b/spring-boot-modules/spring-boot-runtime-2/README.md @@ -4,5 +4,4 @@ This module contains articles about administering a Spring Boot runtime ### Relevant Articles: - [Configure the Heap Size When Starting a Spring Boot Application](https://www.baeldung.com/spring-boot-heap-size) - - [CORS with Spring](https://www.baeldung.com/spring-cors) - [Max-HTTP-Header-Size in Spring Boot 2](https://www.baeldung.com/spring-boot-max-http-header-size) diff --git a/spring-boot-modules/spring-boot-runtime/README.md b/spring-boot-modules/spring-boot-runtime/README.md index 6f21efe793..6463aaa6c3 100644 --- a/spring-boot-modules/spring-boot-runtime/README.md +++ b/spring-boot-modules/spring-boot-runtime/README.md @@ -10,3 +10,4 @@ This module contains articles about administering a Spring Boot runtime - [Project Configuration with Spring](https://www.baeldung.com/project-configuration-with-spring) - [Spring – Log Incoming Requests](https://www.baeldung.com/spring-http-logging) - [How to Configure Spring Boot Tomcat](https://www.baeldung.com/spring-boot-configure-tomcat) + - [CORS with Spring](https://www.baeldung.com/spring-cors) diff --git a/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/cors/Account.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/Account.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/cors/Account.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/Account.java diff --git a/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/cors/AccountController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/AccountController.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/cors/AccountController.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/AccountController.java diff --git a/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/cors/config/WebConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/config/WebConfig.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/cors/config/WebConfig.java rename to spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/cors/config/WebConfig.java From dc667e03f3b9d4b94466459fbbaec99840d51f00 Mon Sep 17 00:00:00 2001 From: timis1 Date: Mon, 6 Nov 2023 13:58:00 +0200 Subject: [PATCH 111/233] JAVA-27237 Change the logging level to WARN (spring-integration) --- spring-integration/src/test/resources/logback-test.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-integration/src/test/resources/logback-test.xml b/spring-integration/src/test/resources/logback-test.xml index 98bfc86d71..352dc719df 100644 --- a/spring-integration/src/test/resources/logback-test.xml +++ b/spring-integration/src/test/resources/logback-test.xml @@ -9,7 +9,7 @@ - + From fb2f90d88f540c2df051d318c8f176a643462bf0 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Mon, 6 Nov 2023 19:08:47 +0530 Subject: [PATCH 112/233] BAEL-7177 review comments implemented. --- .../modifystream/ModifyStreamUnitTest.java | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java index f5fab408b8..9da3beb40e 100644 --- a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/modifystream/ModifyStreamUnitTest.java @@ -95,15 +95,6 @@ public class ModifyStreamUnitTest { assertEquals(3, newPersonList.size()); } - @Test - void givenPersonList_whenRemovePersonWithRemoveIf_thenPersonRemoved() { - assertEquals(4, personList.size()); - - personList.removeIf(e -> e.getName().equals("John")); - - assertEquals(3, personList.size()); - } - @Test void givenPersonList_whenUpdatePersonEmailByInterferingWithForEach_thenPersonEmailUpdated() { personList.stream().forEach(e -> e.setEmail(e.getEmail().toUpperCase())); @@ -128,11 +119,12 @@ public class ModifyStreamUnitTest { newImmutablePersonList.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); } + @Test void givenPersonList_whenUpdatePersonEmailByInterferingWithPeek_thenPersonEmailUpdated() { personList.stream() - .peek(e -> e.setEmail(e.getEmail().toUpperCase())) - .collect(Collectors.toList()); + .peek(e -> e.setEmail(e.getEmail().toUpperCase())) + .collect(Collectors.toList()); personList.forEach(e -> assertEquals(e.getEmail(), e.getEmail().toUpperCase())); } From 9e3c735879388af7f39456972ed516d3518d291f Mon Sep 17 00:00:00 2001 From: Anastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com> Date: Mon, 6 Nov 2023 17:38:16 +0200 Subject: [PATCH 113/233] JAVA-22208 Fix port to 1030,1031 for jenkins (#15100) --- ...oadBalancerBooksClientIntegrationTest.java | 6 +++--- .../client/LoadBalancerIntegrationTest.java | 6 +++--- .../spring/cloud/client/TestConfig.java | 4 ++-- .../spring/cloud/client/WireMockConfig.java | 4 ++-- ...application-spring-cloud-balancer-test.yml | 19 ------------------- .../src/test/resources/application-test.yml | 4 ++-- 6 files changed, 12 insertions(+), 31 deletions(-) delete mode 100644 spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/resources/application-spring-cloud-balancer-test.yml diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/LoadBalancerBooksClientIntegrationTest.java b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/LoadBalancerBooksClientIntegrationTest.java index 5690c24d77..a70ae1ee22 100644 --- a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/LoadBalancerBooksClientIntegrationTest.java +++ b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/LoadBalancerBooksClientIntegrationTest.java @@ -63,12 +63,12 @@ class LoadBalancerBooksClientIntegrationTest { String serviceId = "books-service"; RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(ServiceInstanceListSuppliers - .toProvider(serviceId, instance(serviceId, "localhost", false), instance(serviceId, "localhost", true)), + .toProvider(serviceId, instance(serviceId, "localhost", 1030, false), instance(serviceId, "localhost", 1031, true)), serviceId, -1); } - private static DefaultServiceInstance instance(String serviceId, String host, boolean secure) { - return new DefaultServiceInstance(serviceId, serviceId, host, 80, secure); + private static DefaultServiceInstance instance(String serviceId, String host, int port, boolean secure) { + return new DefaultServiceInstance(serviceId, serviceId, host, port, secure); } @Test diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/LoadBalancerIntegrationTest.java b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/LoadBalancerIntegrationTest.java index eee4e7b860..9761b4eb64 100644 --- a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/LoadBalancerIntegrationTest.java +++ b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/LoadBalancerIntegrationTest.java @@ -80,13 +80,13 @@ class LoadBalancerIntegrationTest { void staticConfigurationWorks() { String serviceId = "test-book-service"; RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(ServiceInstanceListSuppliers - .toProvider(serviceId, instance(serviceId, "bookservice1", false), instance(serviceId, "bookservice2", false)), + .toProvider(serviceId, instance(serviceId, "bookservice1", 1030, false), instance(serviceId, "bookservice2", 1031, false)), serviceId, -1); assertLoadBalancer(loadBalancer, Arrays.asList("bookservice1", "bookservice2")); } - private static DefaultServiceInstance instance(String serviceId, String host, boolean secure) { - return new DefaultServiceInstance(serviceId, serviceId, host, 80, secure); + private static DefaultServiceInstance instance(String serviceId, String host, int port, boolean secure) { + return new DefaultServiceInstance(serviceId, serviceId, host, port, secure); } @EnableAutoConfiguration diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/TestConfig.java b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/TestConfig.java index b3770721b1..375c945054 100644 --- a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/TestConfig.java +++ b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/TestConfig.java @@ -14,11 +14,11 @@ public class TestConfig { @Bean(initMethod = "start", destroyMethod = "stop") public WireMockServer mockBooksService() { - return new WireMockServer(options().port(80)); + return new WireMockServer(options().port(1030)); } @Bean(name="secondMockBooksService", initMethod = "start", destroyMethod = "stop") public WireMockServer secondBooksMockService() { - return new WireMockServer(options().port(81)); + return new WireMockServer(options().port(1031)); } } diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/WireMockConfig.java b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/WireMockConfig.java index 3d4f2822f4..a41faa9c5c 100644 --- a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/WireMockConfig.java +++ b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/java/com/baeldung/spring/cloud/client/WireMockConfig.java @@ -11,11 +11,11 @@ public class WireMockConfig { @Bean(initMethod = "start", destroyMethod = "stop") public WireMockServer mockBooksService() { - return new WireMockServer(80); + return new WireMockServer(1030); } @Bean(initMethod = "start", destroyMethod = "stop") public WireMockServer mockBooksService2() { - return new WireMockServer(81); + return new WireMockServer(1031); } } diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/resources/application-spring-cloud-balancer-test.yml b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/resources/application-spring-cloud-balancer-test.yml deleted file mode 100644 index ad11d46ae8..0000000000 --- a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/resources/application-spring-cloud-balancer-test.yml +++ /dev/null @@ -1,19 +0,0 @@ -eureka: - client: - enabled: false - -spring: - application: - name: books-service - cloud: - loadbalancer: - ribbon: - enabled: false - discovery: - client: - simple: - instances: - books-service[0]: - uri: http://localhost:80 - books-service[1]: - uri: http://localhost:81 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/resources/application-test.yml b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/resources/application-test.yml index 231d45004f..6bd5b8efc7 100644 --- a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/resources/application-test.yml +++ b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/src/test/resources/application-test.yml @@ -14,6 +14,6 @@ spring: simple: instances: books-service[0]: - uri: http://localhost:80 + uri: http://localhost:1030 books-service[1]: - uri: http://localhost:81 + uri: http://localhost:1031 From 946f84976785a7942782d14fed6121ba48ec86ed Mon Sep 17 00:00:00 2001 From: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> Date: Mon, 6 Nov 2023 19:34:00 +0200 Subject: [PATCH 114/233] Update StreamToMapAndMultiMapUnitTest.java (#15146) --- .../StreamToMapAndMultiMapUnitTest.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streamtomapandmultimap/StreamToMapAndMultiMapUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streamtomapandmultimap/StreamToMapAndMultiMapUnitTest.java index 4d957fd704..f5da353551 100644 --- a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streamtomapandmultimap/StreamToMapAndMultiMapUnitTest.java +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streamtomapandmultimap/StreamToMapAndMultiMapUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.streamtomapandmultimap; -import com.google.common.collect.LinkedHashMultimap; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.ListMultimap; import org.junit.Test; import java.util.*; @@ -32,16 +33,16 @@ public class StreamToMapAndMultiMapUnitTest { public void givenStringStream_whenConvertingToMultimap_thenExpectedMultimapIsGenerated() { Stream stringStream = Stream.of("one", "two", "three", "two"); - LinkedHashMultimap multimap = LinkedHashMultimap.create(); + ListMultimap multimap = stringStream.collect( + ArrayListMultimap::create, + (map, element) -> map.put(element, element), + ArrayListMultimap::putAll + ); - stringStream.collect(Collectors.groupingBy( - s -> s, - Collectors.mapping(s -> s, Collectors.toList()) - )).forEach((key, value) -> multimap.putAll(key, value)); - - LinkedHashMultimap expectedMultimap = LinkedHashMultimap.create(); + ListMultimap expectedMultimap = ArrayListMultimap.create(); expectedMultimap.put("one", "one"); expectedMultimap.put("two", "two"); + expectedMultimap.put("two", "two"); expectedMultimap.put("three", "three"); assertEquals(expectedMultimap, multimap); @@ -97,4 +98,4 @@ public class StreamToMapAndMultiMapUnitTest { assertEquals(expectedMap, resultMap); } -} \ No newline at end of file +} From 4d7e5eb5c9a143afbe37833cb7a6296fd16b41b6 Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Mon, 6 Nov 2023 19:40:42 +0200 Subject: [PATCH 115/233] This commit is related to the article BAEL-6988 (#15149) This commit aims to add a test class "HexToIntConversionUnitTest.java" that provides several ways to convert Hex string into int. --- .../hextoint/HexToIntConversionUnitTest.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 core-java-modules/core-java-hex/test/java/com/baeldung/hextoint/HexToIntConversionUnitTest.java diff --git a/core-java-modules/core-java-hex/test/java/com/baeldung/hextoint/HexToIntConversionUnitTest.java b/core-java-modules/core-java-hex/test/java/com/baeldung/hextoint/HexToIntConversionUnitTest.java new file mode 100644 index 0000000000..c236f0a818 --- /dev/null +++ b/core-java-modules/core-java-hex/test/java/com/baeldung/hextoint/HexToIntConversionUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.hextoint; + +import org.junit.Test; + +import java.math.BigInteger; + +import static org.junit.Assert.assertEquals; + +public class HexToIntConversionUnitTest { + + @Test + public void givenValidHexString_whenUsingParseInt_thenExpectCorrectDecimalValue() { + String hexString = "0x00FF00"; + int expectedDecimalValue = 65280; + + int decimalValue = Integer.parseInt(hexString.substring(2), 16); + + assertEquals(expectedDecimalValue, decimalValue); + } + + @Test + public void givenValidHexString_whenUsingIntegerDecode_thenExpectCorrectDecimalValue() { + String hexString = "0x00FF00"; + int expectedDecimalValue = 65280; + + int decimalValue = Integer.decode(hexString); + + assertEquals(expectedDecimalValue, decimalValue); + } + + @Test + public void givenValidHexString_whenUsingBigInteger_thenExpectCorrectDecimalValue() { + String hexString = "0x00FF00"; + int expectedDecimalValue = 65280; + + BigInteger bigIntegerValue = new BigInteger(hexString.substring(2), 16); + int decimalValue = bigIntegerValue.intValue(); + assertEquals(expectedDecimalValue, decimalValue); + } + + +} From 03c615201fdad5e3bd54f7c701972bb248f7d2a7 Mon Sep 17 00:00:00 2001 From: Ulisses Lima Date: Mon, 6 Nov 2023 16:26:35 -0300 Subject: [PATCH 116/233] Update InterruptThread.java MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Based on a comment: Section 6 should be headlined with “Using System.exit()” since that’s what stops code execution, not the boolean variable (this is just a means to decide that execution should be stopped, like the negative array element in section 4. Also it’s unclear why we’d need the “if (isInterrupted())” statement in the while loop of the 8th section: how should isInterrupted() be true one line after we’ve checked in the while loop header that it’s false? Admittedly there’s a little chance that the interrupt status changed between these 2 lines, but this if statement would make much more sense somewhere in the business logic code where more time has passed since the evaluation of “while (!isInterrupted())”… and if that business code doesn’t have that complexity/length, one should omit this if statement altogether, since it creates more confusion than it helps for timely reaction on an interruption. --- .../main/java/com/baeldung/stopexecution/InterruptThread.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/InterruptThread.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/InterruptThread.java index 7964ad9f52..7fcb6185cc 100644 --- a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/InterruptThread.java +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/InterruptThread.java @@ -4,9 +4,7 @@ public class InterruptThread extends Thread { @Override public void run() { while (!isInterrupted()) { - if (isInterrupted()) { - break; - } + break; // business logic } } From 4ef6b9039f4e77075b6b199a5df9106da22f20ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bogdan=20Cardo=C5=9F?= <106325528+sodrac@users.noreply.github.com> Date: Mon, 6 Nov 2023 22:47:45 +0200 Subject: [PATCH 117/233] BAEL-6874 update test code for article (#15155) * BAEL-6819 convert from int to Long in Java * BAEL-6819 update package name * BAEL-6874 test code for article * BAEL-6874 rename test class * BAEL-6874 update test code for article --- .../GenericNumbersComparatorUnitTest.java | 40 ++----------------- 1 file changed, 4 insertions(+), 36 deletions(-) diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java index 37b971b5c5..0fcc0f3453 100644 --- a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java @@ -1,13 +1,12 @@ package com.baeldung.genericnumberscomparator; +import static org.assertj.core.api.Assertions.entry; import static org.junit.jupiter.api.Assertions.assertEquals; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Comparator; -import java.util.HashMap; import java.util.Map; -import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; @@ -25,6 +24,7 @@ class GenericNumbersComparatorUnitTest { assertEquals(0, compareDouble(5, 5.0)); } + // we create a method that compares Integer, but this could also be done for other types e.g. Double, BigInteger public int compareTo(Integer int1, Integer int2) { return int1.compareTo(int2); } @@ -34,11 +34,10 @@ class GenericNumbersComparatorUnitTest { assertEquals(-1, compareTo(5, 7)); } - Map, BiFunction> comparisonMap = new HashMap<>(); + // for this example, we create a function that compares Integer, but this could also be done for other types e.g. Double, BigInteger + Map, BiFunction> comparisonMap = Map.ofEntries(entry(Integer.class, (num1, num2) -> ((Integer) num1).compareTo((Integer) num2))); public int compareUsingMap(Number num1, Number num2) { - comparisonMap.put(Integer.class, (a, b) -> ((Integer) num1).compareTo((Integer) num2)); - return comparisonMap.get(num1.getClass()) .apply(num1, num2); } @@ -70,24 +69,6 @@ class GenericNumbersComparatorUnitTest { assertEquals(-1, compareUsingReflection(5, 7)); } - interface NumberComparatorFactory { - Comparator getComparator(); - } - - class IntegerComparatorFactory implements NumberComparatorFactory { - @Override - public Comparator getComparator() { - return (num1, num2) -> ((Integer) num1).compareTo((Integer) num2); - } - } - - @Test - void givenNumbers_whenUseComparatorFactory_thenWillExecuteComparison() { - NumberComparatorFactory factory = new IntegerComparatorFactory(); - Comparator comparator = factory.getComparator(); - assertEquals(-1, comparator.compare(5, 7)); - } - Function toDouble = Number::doubleValue; BiPredicate isEqual = (num1, num2) -> toDouble.apply(num1) .equals(toDouble.apply(num2)); @@ -97,19 +78,6 @@ class GenericNumbersComparatorUnitTest { assertEquals(true, isEqual.test(5, 5.0)); } - private Number someNumber = 5; - private Number anotherNumber = 5.0; - - Optional optNum1 = Optional.ofNullable(someNumber); - Optional optNum2 = Optional.ofNullable(anotherNumber); - int comparisonResult = optNum1.flatMap(n1 -> optNum2.map(n2 -> Double.compare(n1.doubleValue(), n2.doubleValue()))) - .orElse(0); - - @Test - void givenNumbers_whenUseComparisonResult_thenWillExecuteComparison() { - assertEquals(0, comparisonResult); - } - private boolean someCondition = true; Function dynamicFunction = someCondition ? Number::doubleValue : Number::intValue; Comparator dynamicComparator = (num1, num2) -> ((Comparable) dynamicFunction.apply(num1)).compareTo(dynamicFunction.apply(num2)); From 9e995c1e417a8fc2a9d3339bc64adf7568746353 Mon Sep 17 00:00:00 2001 From: Mateusz Szablak Date: Mon, 6 Nov 2023 22:38:36 +0100 Subject: [PATCH 118/233] BAEL-6489 Time Conversions Using TimeUnit (#14390) --- .../TimeUnitConversionsUnitTest.java | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/timeunitconversions/TimeUnitConversionsUnitTest.java diff --git a/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/timeunitconversions/TimeUnitConversionsUnitTest.java b/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/timeunitconversions/TimeUnitConversionsUnitTest.java new file mode 100644 index 0000000000..cbcbcd566b --- /dev/null +++ b/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/timeunitconversions/TimeUnitConversionsUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung.timeunitconversions; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +class TimeUnitConversionsUnitTest { + + + @Test + void givenSeconds_whenConvertToMinutes_thenCorrect() { + int input = 60; + + long minutes = TimeUnit.MINUTES.convert(input, TimeUnit.SECONDS); + + assertThat(minutes).isEqualTo(1); + } + + @Test + void givenMinutes_whenConvertToSeconds_thenCorrect() { + int input = 1; + + long seconds = TimeUnit.SECONDS.convert(input, TimeUnit.MINUTES); + + assertThat(seconds).isEqualTo(60); + } + + @Test + void givenSeconds_whenToMinutes_thenCorrect() { + int input = 60; + + long minutes = TimeUnit.SECONDS.toMinutes(input); + + assertThat(minutes).isEqualTo(1); + } + + @Test + void givenMinutes_whenToSeconds_thenCorrect() { + int input = 1; + + long seconds = TimeUnit.MINUTES.toSeconds(input); + + assertThat(seconds).isEqualTo(60); + } + + @Test + void givenNegativeInput_whenToMinutes_thenCorrect() { + int input = -60; + + long minutes = TimeUnit.SECONDS.toMinutes(input); + assertThat(minutes).isEqualTo(-1); + } + + @Test + void givenNonTotalInput_whenToMinutes_thenCorrectTotalResultWithDecimalTruncate() { + long positiveUnder = TimeUnit.SECONDS.toMinutes(59); + long positiveAbove = TimeUnit.SECONDS.toMinutes(61); + + assertThat(positiveUnder).isEqualTo(0); + assertThat(positiveAbove).isEqualTo(1); + } + + @Test + void givenNonTotalNegativeInput_whenToMinutes_thenCorrectTotalResultWithDecimalTruncate() { + long negativeUnder = TimeUnit.SECONDS.toMinutes(-59); + long negativeAbove = TimeUnit.SECONDS.toMinutes(-61); + + assertThat(negativeUnder).isEqualTo(0); + assertThat(negativeAbove).isEqualTo(-1); + } + + @Test + void givenOverflowInput_whenToMillis_thenTruncatedToLimit() { + long maxMillis = TimeUnit.DAYS.toMillis(Long.MAX_VALUE); + long minMillis = TimeUnit.DAYS.toMillis(Long.MIN_VALUE); + + assertThat(maxMillis).isEqualTo(Long.MAX_VALUE); + assertThat(minMillis).isEqualTo(Long.MIN_VALUE); + } + + @Test + void givenInput_whenExtractFineTimeUnits_thenCorrect() { + long inputSeconds = 3672; + + long hours = TimeUnit.SECONDS.toHours(inputSeconds); + + long secondsRemainingAfterHours = inputSeconds - TimeUnit.HOURS.toSeconds(hours); + long minutes = TimeUnit.SECONDS.toMinutes(secondsRemainingAfterHours); + + long seconds = secondsRemainingAfterHours - TimeUnit.MINUTES.toSeconds(minutes); + + + assertThat(hours).isEqualTo(1); + assertThat(minutes).isEqualTo(1); + assertThat(seconds).isEqualTo(12); + + assertThat(inputSeconds).isEqualTo( + (hours * 60 * 60) + + (minutes * 60) + + (seconds) + ); + } +} From 14070ec048db08590402f87ebc4bd9b2065d23ec Mon Sep 17 00:00:00 2001 From: Eugene Kovko <37694937+eukovko@users.noreply.github.com> Date: Tue, 7 Nov 2023 04:50:48 +0100 Subject: [PATCH 119/233] BAEL-6139: Added ThreadMonitorInfo (#15094) * BAEL-6139: Added ThreadMonitorInfo * BAEL-6139: Move ThreadMonitorInfo * BAEL-6139: Unsafe using park() and unpark(Thread) --- .../com/baeldung/park/ThreadMonitorInfo.java | 26 +++++++++ .../PreemptivePermitsBehaviorUnitTest.java | 27 +++++++++ ...atedPreemptivePermitsBehaviorUnitTest.java | 43 ++++++++++++++ .../ThreadInterruptedBehaviorUnitTest.java | 56 +++++++++++++++++++ .../park/TreadMonitorsBehaviorUnitTest.java | 51 +++++++++++++++++ 5 files changed, 203 insertions(+) create mode 100644 core-java-modules/core-java-sun/src/main/java/com/baeldung/park/ThreadMonitorInfo.java create mode 100644 core-java-modules/core-java-sun/src/test/java/com/baeldung/park/PreemptivePermitsBehaviorUnitTest.java create mode 100644 core-java-modules/core-java-sun/src/test/java/com/baeldung/park/RepeatedPreemptivePermitsBehaviorUnitTest.java create mode 100644 core-java-modules/core-java-sun/src/test/java/com/baeldung/park/ThreadInterruptedBehaviorUnitTest.java create mode 100644 core-java-modules/core-java-sun/src/test/java/com/baeldung/park/TreadMonitorsBehaviorUnitTest.java diff --git a/core-java-modules/core-java-sun/src/main/java/com/baeldung/park/ThreadMonitorInfo.java b/core-java-modules/core-java-sun/src/main/java/com/baeldung/park/ThreadMonitorInfo.java new file mode 100644 index 0000000000..948fb48fcb --- /dev/null +++ b/core-java-modules/core-java-sun/src/main/java/com/baeldung/park/ThreadMonitorInfo.java @@ -0,0 +1,26 @@ +package com.baeldung.park; + +import java.util.concurrent.locks.LockSupport; + +public class ThreadMonitorInfo { + private static final Object MONITOR = new Object(); + public static void main(String[] args) throws InterruptedException { + final Thread waitingThread = new Thread(() -> { + try { + synchronized (MONITOR) { + MONITOR.wait(); + } + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + }, "Waiting Thread"); + + final Thread parkedThread = new Thread(LockSupport::park, "Parked Thread"); + + waitingThread.start(); + parkedThread.start(); + + waitingThread.join(); + parkedThread.join(); + } +} diff --git a/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/PreemptivePermitsBehaviorUnitTest.java b/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/PreemptivePermitsBehaviorUnitTest.java new file mode 100644 index 0000000000..05bfa4ba0b --- /dev/null +++ b/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/PreemptivePermitsBehaviorUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.park; + +import static org.junit.jupiter.api.Assertions.*; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.concurrent.locks.LockSupport; +import org.junit.jupiter.api.Test; + +class PreemptivePermitsBehaviorUnitTest { + + private final Thread parkedThread = new Thread() { + @Override + public void run() { + LockSupport.unpark(this); + LockSupport.park(); + } + }; + + @Test + void givenThreadWhenPreemptivePermitShouldNotPark() { + assertTimeoutPreemptively(Duration.of(1, ChronoUnit.SECONDS), () -> { + parkedThread.start(); + parkedThread.join(); + }); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/RepeatedPreemptivePermitsBehaviorUnitTest.java b/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/RepeatedPreemptivePermitsBehaviorUnitTest.java new file mode 100644 index 0000000000..98be58e9d3 --- /dev/null +++ b/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/RepeatedPreemptivePermitsBehaviorUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.park; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.locks.LockSupport; +import org.junit.jupiter.api.Test; + +class RepeatedPreemptivePermitsBehaviorUnitTest { + + private final Thread parkedThread = new Thread() { + @Override + public void run() { + LockSupport.unpark(this); + LockSupport.unpark(this); + LockSupport.park(); + LockSupport.park(); + } + }; + + @Test + void givenThreadWhenRepeatedPreemptivePermitShouldPark() { + Callable callable = () -> { + parkedThread.start(); + parkedThread.join(); + return true; + }; + + boolean result = false; + final Future future = Executors.newSingleThreadExecutor().submit(callable); + try { + result = future.get(1, TimeUnit.SECONDS); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + // Expected the thread to be parked + } + assertFalse(result, "The thread should be parked"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/ThreadInterruptedBehaviorUnitTest.java b/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/ThreadInterruptedBehaviorUnitTest.java new file mode 100644 index 0000000000..da7b6ffbc9 --- /dev/null +++ b/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/ThreadInterruptedBehaviorUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.park; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +class ThreadInterruptedBehaviorUnitTest { + + @Test + @Timeout(3) + void givenParkedThreadWhenInterruptedShouldNotResetInterruptedFlag() throws InterruptedException { + final Thread thread = new Thread(LockSupport::park); + thread.start(); + thread.interrupt(); + assertTrue(thread.isInterrupted(), "The thread should have the interrupted flag"); + thread.join(); + } + + @Test + @Timeout(3) + void givenParkedThreadWhenNotInterruptedShouldNotHaveInterruptedFlag() throws InterruptedException { + final Thread thread = new Thread(LockSupport::park); + thread.start(); + Thread.sleep(TimeUnit.SECONDS.toMillis(1)); + LockSupport.unpark(thread); + assertFalse(thread.isInterrupted(), "The thread shouldn't have the interrupted flag"); + thread.join(); + } + + @Test + @Timeout(3) + void givenWaitingThreadWhenNotInterruptedShouldNotHaveInterruptedFlag() throws InterruptedException { + + final Thread thread = new Thread() { + @Override + public void run() { + synchronized (this) { + try { + this.wait(); + } catch (InterruptedException e) { + // The thread was interrupted + } + } + } + }; + + thread.start(); + Thread.sleep(TimeUnit.SECONDS.toMillis(1)); + thread.interrupt(); + thread.join(); + assertFalse(thread.isInterrupted(), "The thread shouldn't have the interrupted flag"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/TreadMonitorsBehaviorUnitTest.java b/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/TreadMonitorsBehaviorUnitTest.java new file mode 100644 index 0000000000..b14b674a19 --- /dev/null +++ b/core-java-modules/core-java-sun/src/test/java/com/baeldung/park/TreadMonitorsBehaviorUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.park; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.LockSupport; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + + +class TreadMonitorsBehaviorUnitTest { + + @Test + @Timeout(3) + void giveThreadWhenNotifyWithoutAcquiringMonitorThrowsException() { + final Thread thread = new Thread() { + @Override + public void run() { + synchronized (this) { + try { + this.wait(); + } catch (InterruptedException e) { + // The thread was interrupted + } + } + } + }; + + assertThrows(IllegalMonitorStateException.class, () -> { + thread.start(); + Thread.sleep(TimeUnit.SECONDS.toMillis(1)); + thread.notify(); + thread.join(); + }); + } + + @Test + @Timeout(3) + void giveThreadWhenUnparkWithoutAcquiringMonitor() { + final Thread thread = new Thread(LockSupport::park); + assertTimeoutPreemptively(Duration.of(2, ChronoUnit.SECONDS), () -> { + thread.start(); + LockSupport.unpark(thread); + }); + } +} From a7f39e4155917e732664262beaa686259add6321 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Tue, 7 Nov 2023 13:42:25 +0530 Subject: [PATCH 120/233] Spell mistake fix --- .../java/com/baledung/billpugh/BillPughSingletonUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/BillPughSingletonUnitTest.java b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/BillPughSingletonUnitTest.java index b42d36229f..dcf2098b4b 100644 --- a/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/BillPughSingletonUnitTest.java +++ b/patterns-modules/design-patterns-singleton/src/test/java/com/baledung/billpugh/BillPughSingletonUnitTest.java @@ -15,7 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class BillPughSingletonUnitTest { Logger logger = LoggerFactory.getLogger(BillPughSingletonUnitTest.class); @Test - void giveSynchronizedLazyLoadedImpl_whenCallgetInstance_thenReturnSingleton() { + void givenSynchronizedLazyLoadedImpl_whenCallgetInstance_thenReturnSingleton() { Set setHoldingSingletonObj = new HashSet<>(); List> futures = new ArrayList<>(); From f1424a62ef6f8bab13fee10463435d895de9da33 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Tue, 7 Nov 2023 15:52:43 +0530 Subject: [PATCH 121/233] JAVA-26556: Changes made for Adding missed modules (#15105) /core-java-modules/core-java-numbers-conversions /core-java-modules/core-java-datetime-conversion /di-modules/avaje/persistence-modules/spring-boot-persistence-4 /spring-boot-modules/spring-boot-security-2 /spring-boot-modules/spring-boot-ssl-bundles /spring-boot-modules/spring-boot-telegram --- ...nversionsTest.java => FloatDoubleConversionsUnitTest.java} | 2 +- core-java-modules/pom.xml | 4 +++- di-modules/pom.xml | 1 + persistence-modules/pom.xml | 1 + spring-boot-modules/pom.xml | 3 +++ 5 files changed, 9 insertions(+), 2 deletions(-) rename core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/{FloatDoubleConversionsTest.java => FloatDoubleConversionsUnitTest.java} (95%) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsUnitTest.java similarity index 95% rename from core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java rename to core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsUnitTest.java index 9da50276a9..2bddb6d8cd 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.floatdoubleconversions; import org.junit.Assert; import org.junit.Test; -public class FloatDoubleConversionsTest { +public class FloatDoubleConversionsUnitTest { @Test public void whenDoubleType_thenFloatTypeSuccess(){ diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 79596d2067..f4bda010e8 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -32,6 +32,7 @@ + core-java-numbers-conversions core-java-9-improvements core-java-9-streams core-java-9 @@ -195,9 +196,10 @@ core-java-records core-java-9-jigsaw + core-java-collections-set core-java-date-operations-1 - + core-java-datetime-conversion core-java-httpclient java-native diff --git a/di-modules/pom.xml b/di-modules/pom.xml index e6c86d48e6..984180cb28 100644 --- a/di-modules/pom.xml +++ b/di-modules/pom.xml @@ -18,6 +18,7 @@ dagger flyway-cdi-extension guice + avaje \ No newline at end of file diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index eb4b212771..8726b7ad87 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -120,6 +120,7 @@ scylladb spring-data-cassandra-2 spring-data-jpa-repo-3 + spring-boot-persistence-4 diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 259a40dc38..433f23f4ba 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -68,6 +68,9 @@ spring-boot-runtime spring-boot-runtime-2 spring-boot-security + spring-boot-security-2 + spring-boot-ssl-bundles + spring-boot-telegram spring-boot-springdoc spring-boot-swagger spring-boot-swagger-2 From 19e70b20a485c7abf466a7fd29557ed31787d601 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Tue, 7 Nov 2023 15:58:16 +0530 Subject: [PATCH 122/233] =?UTF-8?q?JAVA-26498:=20Changes=20made=20for=20ad?= =?UTF-8?q?ding=20missed=20module=20core-java-collectio=E2=80=A6=20(#15071?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /core-java-modules/core-java-collections-conversions-2 /core-java-modules/core-java-collections-conversions-3 /core-java-modules/core-java-concurrency-advanced-5 --- core-java-modules/pom.xml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index f4bda010e8..a237fe0ed6 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -21,7 +21,9 @@ - + core-java-collections-conversions-2 + core-java-collections-conversions-3 + core-java-concurrency-advanced-5 From 63758605c922c7daa0a8fa3413091967ff2dae5d Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Tue, 7 Nov 2023 16:45:05 +0530 Subject: [PATCH 123/233] JAVA-26557: Changes made for Adding missed modules (#15121) /libraries-ai /spring-pulsar /maven-modules/versions-maven-plugin/original --- maven-modules/versions-maven-plugin/original/pom.xml | 5 ----- maven-modules/versions-maven-plugin/pom.xml | 11 +++++++++++ pom.xml | 3 +++ spring-pulsar/pom.xml | 5 +---- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/maven-modules/versions-maven-plugin/original/pom.xml b/maven-modules/versions-maven-plugin/original/pom.xml index 2d81274611..6026dac9fe 100644 --- a/maven-modules/versions-maven-plugin/original/pom.xml +++ b/maven-modules/versions-maven-plugin/original/pom.xml @@ -18,11 +18,6 @@ commons-collections4 ${commons-collections4.version} - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - org.apache.commons commons-compress diff --git a/maven-modules/versions-maven-plugin/pom.xml b/maven-modules/versions-maven-plugin/pom.xml index 9c837cefa0..ec1e0ceaba 100644 --- a/maven-modules/versions-maven-plugin/pom.xml +++ b/maven-modules/versions-maven-plugin/pom.xml @@ -7,6 +7,17 @@ versions-maven-plugin 0.0.1-SNAPSHOT versions-maven-plugin + pom + + + maven-modules + com.baeldung + 0.0.1-SNAPSHOT + + + + original + diff --git a/pom.xml b/pom.xml index 12a8f3dc1d..a16fabebc5 100644 --- a/pom.xml +++ b/pom.xml @@ -860,6 +860,7 @@ libraries-http libraries-http-2 libraries-io + libraries-ai libraries-primitive libraries-rpc libraries-server @@ -930,6 +931,7 @@ spring-kafka-2 libraries-llms + spring-pulsar @@ -1212,6 +1214,7 @@ spring-kafka-2 libraries-llms + spring-pulsar diff --git a/spring-pulsar/pom.xml b/spring-pulsar/pom.xml index 05debcab1c..a1c834f830 100644 --- a/spring-pulsar/pom.xml +++ b/spring-pulsar/pom.xml @@ -15,10 +15,6 @@ ../parent-boot-3 - - 17 - 0.2.0 - org.springframework.boot @@ -47,6 +43,7 @@ + 17 0.2.0 From 270acf62e46bc420a0517d756fa63b1742b904b2 Mon Sep 17 00:00:00 2001 From: Niket Agrawal Date: Tue, 7 Nov 2023 21:49:49 +0530 Subject: [PATCH 124/233] Formatter Changes --- .../ResultSetToMapUnitTest.java | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java b/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java index c8a6351804..e449beb83a 100644 --- a/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java +++ b/persistence-modules/core-java-persistence-3/src/test/java/com/baeldung/resultsettomap/ResultSetToMapUnitTest.java @@ -45,7 +45,8 @@ public class ResultSetToMapUnitTest { @Test public void whenUsingContainsKey_thenConvertResultSetToMap() throws SQLException { - ResultSet resultSet = connection.prepareStatement("SELECT * FROM employee").executeQuery(); + ResultSet resultSet = connection.prepareStatement("SELECT * FROM employee") + .executeQuery(); Map> valueMap = new HashMap<>(); while (resultSet.next()) { @@ -54,22 +55,27 @@ public class ResultSetToMapUnitTest { if (!valueMap.containsKey(empCity)) { valueMap.put(empCity, new ArrayList<>()); } - valueMap.get(empCity).add(empName); + valueMap.get(empCity) + .add(empName); } - assertEquals(3, valueMap.get("London").size()); + assertEquals(3, valueMap.get("London") + .size()); } @Test public void whenUsingComputeIfAbsent_thenConvertResultSetToMap() throws SQLException { - ResultSet resultSet = connection.prepareStatement("SELECT * FROM employee").executeQuery(); + ResultSet resultSet = connection.prepareStatement("SELECT * FROM employee") + .executeQuery(); Map> valueMap = new HashMap<>(); while (resultSet.next()) { String empCity = resultSet.getString("empCity"); String empName = resultSet.getString("empName"); - valueMap.computeIfAbsent(empCity, data -> new ArrayList<>()).add(empName); + valueMap.computeIfAbsent(empCity, data -> new ArrayList<>()) + .add(empName); } - assertEquals(3, valueMap.get("London").size()); + assertEquals(3, valueMap.get("London") + .size()); } @Test @@ -81,15 +87,17 @@ public class ResultSetToMapUnitTest { while (resultSet.next()) { String empCity = resultSet.getString("empCity"); String empName = resultSet.getString("empName"); - result.computeIfAbsent(empCity, data -> new ArrayList<>()).add(empName); + result.computeIfAbsent(empCity, data -> new ArrayList<>()) + .add(empName); } return result; } }; - + QueryRunner run = new QueryRunner(); Map> valueMap = run.query(connection, "SELECT * FROM employee", handler); - assertEquals(3, valueMap.get("London").size()); + assertEquals(3, valueMap.get("London") + .size()); } @After From 362610ca587c741843e616d387f613acad3c1340 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Tue, 7 Nov 2023 19:21:46 +0100 Subject: [PATCH 125/233] BAEL-6776: Convert File to Byte Array in Java (#15123) --- .../FileToByteArrayUnitTest.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/filetofrombytearray/FileToByteArrayUnitTest.java diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/filetofrombytearray/FileToByteArrayUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/filetofrombytearray/FileToByteArrayUnitTest.java new file mode 100644 index 0000000000..1bbd958583 --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/filetofrombytearray/FileToByteArrayUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.filetofrombytearray; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; + +class FileToByteArrayUnitTest { + + private static final String FILE_NAME = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "sample.txt"; + private final byte[] expectedByteArray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 }; + + @Test + void givenFile_whenUsingFileInputStreamClass_thenConvert() throws IOException { + File myFile = new File(FILE_NAME); + byte[] byteArray = new byte[(int) myFile.length()]; + try (FileInputStream inputStream = new FileInputStream(myFile)) { + inputStream.read(byteArray); + } + + assertArrayEquals(expectedByteArray, byteArray); + } + + @Test + void givenFile_whenUsingNioApiFilesClass_thenConvert() throws IOException { + byte[] byteArray = Files.readAllBytes(Paths.get(FILE_NAME)); + + assertArrayEquals(expectedByteArray, byteArray); + } + + @Test + void givenFile_whenUsingApacheCommonsIOUtilsClass_thenConvert() throws IOException { + File myFile = new File(FILE_NAME); + byte[] byteArray = new byte[(int) myFile.length()]; + try (FileInputStream inputStream = new FileInputStream(myFile)) { + byteArray = IOUtils.toByteArray(inputStream); + } + + assertArrayEquals(expectedByteArray, byteArray); + } + + @Test + void givenFile_whenUsingApacheCommonsFileUtilsClass_thenConvert() throws IOException { + byte[] byteArray = FileUtils.readFileToByteArray(new File(FILE_NAME)); + + assertArrayEquals(expectedByteArray, byteArray); + } + + @Test + void givenFile_whenUsingGuavaFilesClass_thenConvert() throws IOException { + byte[] byteArray = com.google.common.io.Files.toByteArray(new File(FILE_NAME)); + + assertArrayEquals(expectedByteArray, byteArray); + } + +} From 9b28d7739aade6a5baad097206b655d4aa824025 Mon Sep 17 00:00:00 2001 From: Ehsan Sasanianno Date: Wed, 8 Nov 2023 10:26:53 +0100 Subject: [PATCH 126/233] java-26718: upgrade caffeine version to 3.x (#15138) --- libraries-5/pom.xml | 2 +- spring-5-webflux-2/pom.xml | 2 +- spring-boot-modules/spring-boot-libraries/pom.xml | 2 +- spring-boot-modules/spring-caching-2/pom.xml | 2 ++ spring-boot-modules/spring-caching/pom.xml | 2 ++ 5 files changed, 7 insertions(+), 3 deletions(-) diff --git a/libraries-5/pom.xml b/libraries-5/pom.xml index c98a66c094..a043b4bfa8 100644 --- a/libraries-5/pom.xml +++ b/libraries-5/pom.xml @@ -141,7 +141,7 @@ 2.5.11 0.8.1 3.0.14 - 2.5.5 + 3.1.8 3.0.2 4.5.1 1.0 diff --git a/spring-5-webflux-2/pom.xml b/spring-5-webflux-2/pom.xml index 68945138d4..34cbda6c18 100644 --- a/spring-5-webflux-2/pom.xml +++ b/spring-5-webflux-2/pom.xml @@ -100,7 +100,7 @@ 3.4.5 - 2.9.2 + 3.1.8 1.16.2 diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index d8ca53f013..b7b8ad17ad 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -228,7 +228,7 @@ 3.3.0 7.6.0 0.7.0 - 2.8.2 + 3.1.8 \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/pom.xml b/spring-boot-modules/spring-caching-2/pom.xml index 2239256630..ee28ac5ed5 100644 --- a/spring-boot-modules/spring-caching-2/pom.xml +++ b/spring-boot-modules/spring-caching-2/pom.xml @@ -47,6 +47,7 @@ com.github.ben-manes.caffeine caffeine + ${caffeine.version} it.ozimov @@ -64,6 +65,7 @@ 0.7.3 + 3.1.8 \ No newline at end of file diff --git a/spring-boot-modules/spring-caching/pom.xml b/spring-boot-modules/spring-caching/pom.xml index c27ccf3348..f3d9488b89 100644 --- a/spring-boot-modules/spring-caching/pom.xml +++ b/spring-boot-modules/spring-caching/pom.xml @@ -51,6 +51,7 @@ com.github.ben-manes.caffeine caffeine + ${caffeine.version} com.h2database @@ -78,6 +79,7 @@ 3.5.2 + 3.1.8 \ No newline at end of file From c7e2dc2a6ec7a54633ec4f4c988a7d970e656e56 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Wed, 8 Nov 2023 12:06:28 +0200 Subject: [PATCH 127/233] JAVA-27248 Align module names, folder names and artifact id - Week 44 - 2023 (conti-1) (#15147) Co-authored-by: timis1 --- .../core-java-conditionals/pom.xml | 2 +- core-java-modules/core-java-os-2/pom.xml | 4 ++-- di-modules/avaje/pom.xml | 17 ++++++++++------- spring-6-rsocket/pom.xml | 4 ++-- .../spring-boot-security-2/pom.xml | 2 +- .../spring-boot-ssl-bundles/pom.xml | 10 ++++++---- .../spring-reactive-2/pom.xml | 4 ++-- .../spring-reactive-3/pom.xml | 4 ++-- .../spring-reactive-data-couchbase/pom.xml | 2 +- .../spring-reactive-data/pom.xml | 2 +- 10 files changed, 28 insertions(+), 23 deletions(-) diff --git a/core-java-modules/core-java-conditionals/pom.xml b/core-java-modules/core-java-conditionals/pom.xml index 811f183e99..f2ad7df749 100644 --- a/core-java-modules/core-java-conditionals/pom.xml +++ b/core-java-modules/core-java-conditionals/pom.xml @@ -5,7 +5,7 @@ 4.0.0 core-java-conditionals 0.1.0-SNAPSHOT - core-java-compiler + core-java-conditionals jar diff --git a/core-java-modules/core-java-os-2/pom.xml b/core-java-modules/core-java-os-2/pom.xml index 53fdafa7d4..11b0585ae7 100644 --- a/core-java-modules/core-java-os-2/pom.xml +++ b/core-java-modules/core-java-os-2/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - core-java-os - core-java-os + core-java-os-2 + core-java-os-2 jar diff --git a/di-modules/avaje/pom.xml b/di-modules/avaje/pom.xml index 49162c518e..03d3902d5f 100644 --- a/di-modules/avaje/pom.xml +++ b/di-modules/avaje/pom.xml @@ -3,14 +3,11 @@ 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 - inject-intro + avaje 0.0.1-SNAPSHOT - avaje-inject-intro - - 11 - 11 - 9.5 - + avaje + Avaje Inject Intro + io.avaje @@ -34,4 +31,10 @@ true + + + 11 + 11 + 9.5 + \ No newline at end of file diff --git a/spring-6-rsocket/pom.xml b/spring-6-rsocket/pom.xml index 5d15a605ae..0f9e63bc7e 100644 --- a/spring-6-rsocket/pom.xml +++ b/spring-6-rsocket/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.bealdung - rsocket + spring-6-rsocket 0.0.1-SNAPSHOT - rsocket + spring-6-rsocket com.baeldung diff --git a/spring-boot-modules/spring-boot-security-2/pom.xml b/spring-boot-modules/spring-boot-security-2/pom.xml index db094f33a6..dd8cab81de 100644 --- a/spring-boot-modules/spring-boot-security-2/pom.xml +++ b/spring-boot-modules/spring-boot-security-2/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-security-2 - spring-boot-security-1 + spring-boot-security-2 jar Spring Boot Security Auto-Configuration diff --git a/spring-boot-modules/spring-boot-ssl-bundles/pom.xml b/spring-boot-modules/spring-boot-ssl-bundles/pom.xml index 4802e9ec58..770d8c2f01 100644 --- a/spring-boot-modules/spring-boot-ssl-bundles/pom.xml +++ b/spring-boot-modules/spring-boot-ssl-bundles/pom.xml @@ -3,16 +3,18 @@ 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 + spring-boot-ssl-bundles + spring-boot-ssl-bundles + Module for showing usage of SSL Bundles + jar + com.baeldung parent-boot-3 0.0.1-SNAPSHOT ../../parent-boot-3 - springbootsslbundles - spring-boot-ssl-bundles - jar - Module for showing usage of SSL Bundles + org.springframework.boot diff --git a/spring-reactive-modules/spring-reactive-2/pom.xml b/spring-reactive-modules/spring-reactive-2/pom.xml index 13970851cd..90c5300cc8 100644 --- a/spring-reactive-modules/spring-reactive-2/pom.xml +++ b/spring-reactive-modules/spring-reactive-2/pom.xml @@ -5,9 +5,9 @@ 4.0.0 spring-reactive-2 0.0.1-SNAPSHOT - spring-5-reactive-2 + spring-reactive-2 jar - spring 5 sample project about new features + spring sample project about new features com.baeldung.spring.reactive diff --git a/spring-reactive-modules/spring-reactive-3/pom.xml b/spring-reactive-modules/spring-reactive-3/pom.xml index 96f23f1339..bf2cdbbf2d 100644 --- a/spring-reactive-modules/spring-reactive-3/pom.xml +++ b/spring-reactive-modules/spring-reactive-3/pom.xml @@ -5,9 +5,9 @@ 4.0.0 spring-reactive-3 0.0.1-SNAPSHOT - spring-5-reactive-3 + spring-reactive-3 jar - spring 5 sample project about new features + spring sample project about new features com.baeldung.spring.reactive diff --git a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml index 52b10f39d9..a7481d8aca 100644 --- a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml +++ b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-reactive-data-couchbase - spring-data-couchbase + spring-reactive-data-couchbase jar diff --git a/spring-reactive-modules/spring-reactive-data/pom.xml b/spring-reactive-modules/spring-reactive-data/pom.xml index 03ea440b4f..a598315d5d 100644 --- a/spring-reactive-modules/spring-reactive-data/pom.xml +++ b/spring-reactive-modules/spring-reactive-data/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-reactive-data - spring-reactive-data-2 + spring-reactive-data jar From 7b6ba0e030db93e6faa5b84fe2fdd02a901a5f80 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 8 Nov 2023 15:54:10 +0530 Subject: [PATCH 128/233] JAVA-26729:Changes made for upgrade commons-validator to latest version (#15159) --- core-java-modules/core-java-datetime-string/pom.xml | 2 +- .../java/com/baeldung/formatinstant/FormatInstantUnitTest.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-datetime-string/pom.xml b/core-java-modules/core-java-datetime-string/pom.xml index a33114852c..292a38a5af 100644 --- a/core-java-modules/core-java-datetime-string/pom.xml +++ b/core-java-modules/core-java-datetime-string/pom.xml @@ -64,7 +64,7 @@ - 1.6 + 1.7 2.12.5 RELEASE 1.9 diff --git a/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/formatinstant/FormatInstantUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/formatinstant/FormatInstantUnitTest.java index ef273e4b81..1466fece46 100644 --- a/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/formatinstant/FormatInstantUnitTest.java +++ b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/formatinstant/FormatInstantUnitTest.java @@ -6,6 +6,7 @@ import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.UnsupportedTemporalTypeException; +import java.util.TimeZone; import org.joda.time.format.DateTimeFormat; import org.junit.Test; @@ -17,7 +18,7 @@ public class FormatInstantUnitTest { @Test public void givenInstant_whenUsingDateTimeFormatter_thenFormat() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT) - .withZone(ZoneId.systemDefault()); + .withZone(TimeZone.getTimeZone("UTC").toZoneId()); Instant instant = Instant.parse("2022-02-15T18:35:24.00Z"); String formattedInstant = formatter.format(instant); From 33fceb65a61e7f2f94586809d97911bc066031cb Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Wed, 8 Nov 2023 14:16:19 +0100 Subject: [PATCH 129/233] Using CriteriaDefinition Utility in Hibernate (#15128) * Using CriteriaDefinition Utility in Hibernate * Using CriteriaDefinition Utility in Hibernate * Using CriteriaDefinition Utility in Hibernate * Using CriteriaDefinition Utility in Hibernate * Using CriteriaDefinition Utility in Hibernate --- persistence-modules/hibernate-queries/pom.xml | 2 +- .../criteria/util/HibernateUtil.java | 7 + .../CriteriaDefinitionApplicationView.java | 126 ++++++++++++++++++ .../LocalDateStringJavaDescriptor.java | 11 ++ ...nateCriteriaDefinitionIntegrationTest.java | 77 +++++++++++ 5 files changed, 222 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/CriteriaDefinitionApplicationView.java create mode 100644 persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaDefinitionIntegrationTest.java diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml index bb60c7b83a..76f230a72d 100644 --- a/persistence-modules/hibernate-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -99,7 +99,7 @@ 8.0.32 2.6.0 2.1.214 - 6.1.7.Final + 6.3.1.Final 1.17.6 diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java index ff9ccb017b..f561a33f08 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java @@ -16,4 +16,11 @@ public class HibernateUtil { return session; } + public static SessionFactory getHibernateSessionFactory() { + + final SessionFactory sessionFactory = new Configuration().configure("criteria.cfg.xml").buildSessionFactory(); + + return sessionFactory; + } + } diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/CriteriaDefinitionApplicationView.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/CriteriaDefinitionApplicationView.java new file mode 100644 index 0000000000..9f32aa06e3 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/CriteriaDefinitionApplicationView.java @@ -0,0 +1,126 @@ +package com.baeldung.hibernate.criteria.view; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.query.criteria.CriteriaDefinition; +import org.hibernate.query.criteria.JpaRoot; + +import com.baeldung.hibernate.criteria.model.Item; +import com.baeldung.hibernate.criteria.util.HibernateUtil; + +public class CriteriaDefinitionApplicationView { + + public CriteriaDefinitionApplicationView() { + + } + + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final SessionFactory sessionFactory = HibernateUtil.getHibernateSessionFactory(); + + CriteriaDefinition query = new CriteriaDefinition<>(sessionFactory, Item.class) { + { + JpaRoot message = from(Item.class); + where(gt(message.get("itemPrice"), 1000)); + } + }; + + List items = session.createSelectionQuery(query).list(); + + final String greaterThanItems[] = new String[items.size()]; + for (int i = 0; i < items.size(); i++) { + greaterThanItems[i] = items.get(i).getItemName(); + } + + session.close(); + + return greaterThanItems; + } + + public String[] lessThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final SessionFactory sessionFactory = HibernateUtil.getHibernateSessionFactory(); + + CriteriaDefinition query = new CriteriaDefinition<>(sessionFactory, Item.class) { + { + JpaRoot message = from(Item.class); + where(lt(message.get("itemPrice"), 1000)); + } + }; + + List items = session.createSelectionQuery(query).list(); + final String lessThanItems[] = new String[items.size()]; + for (int i = 0; i < items.size(); i++) { + lessThanItems[i] = items.get(i).getItemName(); + } + + session.close(); + + return lessThanItems; + } + + public String[] likeCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final SessionFactory sessionFactory = HibernateUtil.getHibernateSessionFactory(); + + CriteriaDefinition query = new CriteriaDefinition<>(sessionFactory, Item.class) { + { + JpaRoot item = from(Item.class); + where(like(item.get("itemName"), "%chair%")); + } + }; + + List items = session.createSelectionQuery(query).list(); + + final String likeItems[] = new String[items.size()]; + for (int i = 0; i < items.size(); i++) { + likeItems[i] = items.get(i).getItemName(); + } + session.close(); + return likeItems; + } + + public String[] likeCaseCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final SessionFactory sessionFactory = HibernateUtil.getHibernateSessionFactory(); + + CriteriaDefinition query = new CriteriaDefinition<>(sessionFactory, Item.class) { + { + JpaRoot item = from(Item.class); + where(like(lower(item.get("itemName")), "%chair%")); + } + }; + + List items = session.createSelectionQuery(query).list(); + + final String likeItems[] = new String[items.size()]; + for (int i = 0; i < items.size(); i++) { + likeItems[i] = items.get(i).getItemName(); + } + session.close(); + return likeItems; + } + + public String[] betweenCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final SessionFactory sessionFactory = HibernateUtil.getHibernateSessionFactory(); + + CriteriaDefinition query = new CriteriaDefinition<>(sessionFactory, Item.class) { + { + JpaRoot item = from(Item.class); + where(between(item.get("itemPrice"), 100, 200)); + } + }; + + List items = session.createSelectionQuery(query).list(); + + final String betweenItems[] = new String[items.size()]; + for (int i = 0; i < items.size(); i++) { + betweenItems[i] = items.get(i).getItemName(); + } + session.close(); + return betweenItems; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java index 58d8e8628a..e9c7548c7d 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -4,8 +4,13 @@ package com.baeldung.hibernate.customtypes; import java.time.LocalDate; import java.time.format.DateTimeFormatter; +import org.hibernate.dialect.Dialect; +import org.hibernate.tool.schema.extract.spi.ColumnTypeInformation; +import org.hibernate.type.BasicType; import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; +import org.hibernate.type.descriptor.jdbc.JdbcTypeIndicators; +import org.hibernate.type.spi.TypeConfiguration; import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor; @@ -49,4 +54,10 @@ public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); + final String expectedLikeItems[] = new String[expectedLikeList.size()]; + for (int i = 0; i < expectedLikeList.size(); i++) { + expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLikeItems, criteriaDefinition.likeCriteria()); + } + + @Test + public void givenHibernateSession_whenExecutingCaseSensitiveLikeCriteriaQuery_thenExpectMatchingItems() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); + final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; + for (int i = 0; i < expectedChairCaseList.size(); i++) { + expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedChairCaseItems, criteriaDefinition.likeCaseCriteria()); + } + + @Test + public void givenHibernateSession_whenExecutingGreaterThanCriteriaQuery_thenExpectMatchingItems() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); + final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; + for (int i = 0; i < expectedGreaterThanList.size(); i++) { + expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedGreaterThanItems, criteriaDefinition.greaterThanCriteria()); + } + + @Test + public void givenHibernateSession_whenExecutingLessThanCriteriaQuery_thenExpectMatchingItems() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); + final String expectedLessThanItems[] = new String[expectedLessList.size()]; + for (int i = 0; i < expectedLessList.size(); i++) { + expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLessThanItems, criteriaDefinition.lessThanCriteria()); + } + + @Test + public void givenHibernateSession_whenExecutingBetweenCriteriaQuery_thenExpectMatchingItems() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200").list(); + final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; + for (int i = 0; i < expectedBetweenList.size(); i++) { + expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedPriceBetweenItems, criteriaDefinition.betweenCriteria()); + } + + +} From 7e81d666c9a10ca2bd3128f73c538f1832b46854 Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Thu, 9 Nov 2023 00:08:33 +0200 Subject: [PATCH 130/233] This commit related to BAEL-7103 (#15160) This commit aims to add a test class named "ConvertingHashSetToArrayUnitTest" that provides test methods to convert HashSet to an array. --- .../ConvertingHashSetToArrayUnitTest.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 core-java-modules/core-java-collections-5/toarraymethod/ConvertingHashSetToArrayUnitTest.java diff --git a/core-java-modules/core-java-collections-5/toarraymethod/ConvertingHashSetToArrayUnitTest.java b/core-java-modules/core-java-collections-5/toarraymethod/ConvertingHashSetToArrayUnitTest.java new file mode 100644 index 0000000000..420c1d25e6 --- /dev/null +++ b/core-java-modules/core-java-collections-5/toarraymethod/ConvertingHashSetToArrayUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.toarraymethod; + +import org.junit.Test; + +import java.util.HashSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class ConvertingHashSetToArrayUnitTest { + + @Test + public void givenStringHashSet_whenConvertedToArray_thenArrayContainsStringElements() { + HashSet stringSet = new HashSet<>(); + stringSet.add("Apple"); + stringSet.add("Banana"); + stringSet.add("Cherry"); + + // Convert the HashSet of Strings to an array of Strings + String[] stringArray = stringSet.toArray(new String[0]); + + // Test that the array is of the correct length + assertEquals(3, stringArray.length); + + for (String str : stringArray) { + assertTrue(stringSet.contains(str)); + } + } + + @Test + public void givenIntegerHashSet_whenConvertedToArray_thenArrayContainsIntegerElements() { + HashSet integerSet = new HashSet<>(); + integerSet.add(5); + integerSet.add(10); + integerSet.add(15); + + // Convert the HashSet of Integers to an array of Integers + Integer[] integerArray = integerSet.toArray(new Integer[0]); + + // Test that the array is of the correct length + assertEquals(3, integerArray.length); + + for (Integer num : integerArray) { + assertTrue(integerSet.contains(num)); + } + + assertTrue(integerSet.contains(5)); + assertTrue(integerSet.contains(10)); + assertTrue(integerSet.contains(15)); + } +} From 5b596e0c49cea6914ba563d15d116303c40670c2 Mon Sep 17 00:00:00 2001 From: Alexander Molochko Date: Wed, 8 Nov 2023 18:05:37 -0700 Subject: [PATCH 131/233] BAEL-7012: Splitting Streams in Kafka (#15029) * BAEL-7012: Splitting Streams in Kafka * Move sources to the spring-kafka module * Move sources to the spring-kafka-2 module --- spring-kafka-2/pom.xml | 2 + .../kafka/kafkasplitting/IotSensorData.java | 31 ++++++++++ .../kafkasplitting/KafkaConsumerConfig.java | 43 +++++++++++++ .../KafkaIotConsumerService.java | 28 +++++++++ .../kafkasplitting/KafkaStreamsConfig.java | 62 +++++++++++++++++++ .../SpringBootKafkaStreamsSplittingApp.java | 12 ++++ .../src/main/resources/application.properties | 4 ++ 7 files changed, 182 insertions(+) create mode 100644 spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/IotSensorData.java create mode 100644 spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaConsumerConfig.java create mode 100644 spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaIotConsumerService.java create mode 100644 spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaStreamsConfig.java create mode 100644 spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/SpringBootKafkaStreamsSplittingApp.java diff --git a/spring-kafka-2/pom.xml b/spring-kafka-2/pom.xml index 0bca20447d..fdf7da7438 100644 --- a/spring-kafka-2/pom.xml +++ b/spring-kafka-2/pom.xml @@ -65,6 +65,8 @@ 1.16.2 + 3.0.12 + 3.6.0 1.16.2 diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/IotSensorData.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/IotSensorData.java new file mode 100644 index 0000000000..350f6911f3 --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/IotSensorData.java @@ -0,0 +1,31 @@ +package com.baeldung.spring.kafka.kafkasplitting; + +public class IotSensorData { + private String sensorType; + private String value; + private String sensorId; + + public String getSensorType() { + return sensorType; + } + + public void setSensorType(String sensorType) { + this.sensorType = sensorType; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getSensorId() { + return sensorId; + } + + public void setSensorId(String sensorId) { + this.sensorId = sensorId; + } +} diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaConsumerConfig.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaConsumerConfig.java new file mode 100644 index 0000000000..70640cb582 --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaConsumerConfig.java @@ -0,0 +1,43 @@ +package com.baeldung.spring.kafka.kafkasplitting; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.config.KafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; +import org.springframework.kafka.support.serializer.JsonDeserializer; + +import java.util.HashMap; +import java.util.Map; + +@Configuration +class KafkaConsumerConfig { + + @Value("${spring.kafka.consumer.group-id}") + private String groupId; + @Value("${spring.kafka.bootstrap-servers}") + private String bootstrapServers; + + @Bean + public ConsumerFactory consumerFactory() { + Map props = new HashMap<>(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); + + return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), new JsonDeserializer<>(IotSensorData.class)); + } + + @Bean + KafkaListenerContainerFactory> kafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory()); + return factory; + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaIotConsumerService.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaIotConsumerService.java new file mode 100644 index 0000000000..bbd0c549ab --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaIotConsumerService.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.kafka.kafkasplitting; + +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Service; + +@Service +public class KafkaIotConsumerService { + + @KafkaListener(topics = "iot_sensor_data") + public void consumeIotData(IotSensorData item) { + System.out.println("Consumed Message in original \"iot_sensor_data\" topic :" + item.getSensorType()); + } + + @KafkaListener(topics = "iot_sensor_data_temp") + public void consumeIotTemperatureData(IotSensorData item) { + System.out.println("Consumed Temparature data :" + item.getValue()); + } + + @KafkaListener(topics = "iot_sensor_data_hum") + public void consumeIotHumidityData(IotSensorData item) { + System.out.println("Consumed Humidity data :" + item.getValue()); + } + + @KafkaListener(topics = "iot_sensor_data_move") + public void consumeIotMovementData(IotSensorData item) { + System.out.println("Consumed Movement data :" + item.getValue()); + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaStreamsConfig.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaStreamsConfig.java new file mode 100644 index 0000000000..c4eb1501fd --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/KafkaStreamsConfig.java @@ -0,0 +1,62 @@ +package com.baeldung.spring.kafka.kafkasplitting; + +import org.apache.kafka.common.serialization.Serde; +import org.apache.kafka.common.serialization.Serdes; +import org.apache.kafka.streams.StreamsBuilder; +import org.apache.kafka.streams.kstream.Branched; +import org.apache.kafka.streams.kstream.Consumed; +import org.apache.kafka.streams.kstream.KStream; +import org.apache.kafka.streams.processor.TopicNameExtractor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.annotation.EnableKafka; +import org.springframework.kafka.annotation.EnableKafkaStreams; +import org.springframework.kafka.support.KafkaStreamBrancher; +import org.springframework.kafka.support.serializer.JsonDeserializer; +import org.springframework.kafka.support.serializer.JsonSerializer; + +@Configuration +@EnableKafka +@EnableKafkaStreams +class KafkaStreamsConfig { + @Value("${kafka.topics.iot}") + private String iotTopicName; + + @Bean + public Serde iotSerde() { + return Serdes.serdeFrom(new JsonSerializer<>(), new JsonDeserializer<>(IotSensorData.class)); + } + + @Bean + public KStream iotStream(StreamsBuilder streamsBuilder) { + KStream stream = streamsBuilder.stream(iotTopicName, Consumed.with(Serdes.String(), iotSerde())); + stream.split() + .branch((key, value) -> value.getSensorType() != null, + Branched.withConsumer(ks -> ks.to((key, value, recordContext) -> String.format("%s_%s", iotTopicName, value.getSensorType())))) + .noDefaultBranch(); + return stream; + } + + @Bean + public KStream iotBrancher(StreamsBuilder streamsBuilder) { + KStream stream = streamsBuilder.stream(iotTopicName, Consumed.with(Serdes.String(), iotSerde())); + + new KafkaStreamBrancher() + .branch((key, value) -> "temp".equals(value.getSensorType()), (ks) -> ks.to(iotTopicName + "_temp")) + .branch((key, value) -> "move".equals(value.getSensorType()), (ks) -> ks.to(iotTopicName + "_move")) + .branch((key, value) -> "hum".equals(value.getSensorType()), (ks) -> ks.to(iotTopicName + "_hum")) + .defaultBranch(ks -> ks.to(String.format("%s_unknown", iotTopicName))) + .onTopOf(stream); + + return stream; + } + + @Bean + public KStream iotTopicExtractor(StreamsBuilder streamsBuilder) { + KStream stream = streamsBuilder.stream(iotTopicName, Consumed.with(Serdes.String(), iotSerde())); + TopicNameExtractor sensorTopicExtractor = (key, value, recordContext) -> String.format("%s_%s", iotTopicName, value.getSensorType()); + stream.to(sensorTopicExtractor); + return stream; + } +} diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/SpringBootKafkaStreamsSplittingApp.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/SpringBootKafkaStreamsSplittingApp.java new file mode 100644 index 0000000000..6101eeb13d --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/kafkasplitting/SpringBootKafkaStreamsSplittingApp.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.kafka.kafkasplitting; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootKafkaStreamsSplittingApp { + public static void main(String[] args) { + SpringApplication.run(SpringBootKafkaStreamsSplittingApp.class, args); + } + +} diff --git a/spring-kafka-2/src/main/resources/application.properties b/spring-kafka-2/src/main/resources/application.properties index ed844cadf8..9111491b58 100644 --- a/spring-kafka-2/src/main/resources/application.properties +++ b/spring-kafka-2/src/main/resources/application.properties @@ -19,4 +19,8 @@ kafka.backoff.max_failure=5 # multiple listeners properties multiple-listeners.books.topic.name=books +spring.kafka.streams.application-id=baeldung-streams +spring.kafka.consumer.group-id=baeldung-group +spring.kafka.streams.properties[default.key.serde]=org.apache.kafka.common.serialization.Serdes$StringSerde +kafka.topics.iot=iot_sensor_data From f33372e091a921a22e616f50e088820693130c79 Mon Sep 17 00:00:00 2001 From: hmdrz Date: Thu, 9 Nov 2023 11:21:54 +0330 Subject: [PATCH 132/233] #BAEL-7157: add one extra method --- .../test/java/com/baeldung/testsuite/ClassOneUnitTest.java | 4 ++++ .../com/baeldung/testsuite/subpackage/ClassTwoUnitTest.java | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/ClassOneUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/ClassOneUnitTest.java index 4ce092796e..cfb77c8d41 100644 --- a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/ClassOneUnitTest.java +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/ClassOneUnitTest.java @@ -10,4 +10,8 @@ public class ClassOneUnitTest { Assertions.assertTrue(true); } + @Test + public void whenFalse_thenFalse() { + Assertions.assertFalse(false); + } } diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/subpackage/ClassTwoUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/subpackage/ClassTwoUnitTest.java index bb63fcda63..be5b3380c7 100644 --- a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/subpackage/ClassTwoUnitTest.java +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/subpackage/ClassTwoUnitTest.java @@ -8,4 +8,9 @@ public class ClassTwoUnitTest { public void whenTrue_thenTrue() { Assertions.assertTrue(true); } + + @Test + public void whenFalse_thenFalse() { + Assertions.assertFalse(false); + } } From b6d28c44461e31609295637e87de8e7b463652fb Mon Sep 17 00:00:00 2001 From: hmdrz Date: Thu, 9 Nov 2023 11:22:14 +0330 Subject: [PATCH 133/233] #BAEL-7157: add main test suite --- .../testsuite/suites/JUnitSelectMethodsSuite.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/suites/JUnitSelectMethodsSuite.java diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/suites/JUnitSelectMethodsSuite.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/suites/JUnitSelectMethodsSuite.java new file mode 100644 index 0000000000..e0d17dc0e4 --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/testsuite/suites/JUnitSelectMethodsSuite.java @@ -0,0 +1,14 @@ +package com.baeldung.testsuite.suites; + +import com.baeldung.testsuite.ClassOneUnitTest; +import org.junit.platform.suite.api.SelectMethod; +import org.junit.platform.suite.api.Suite; +import org.junit.platform.suite.api.SuiteDisplayName; + +@Suite +@SuiteDisplayName("My Test Suite") +@SelectMethod(type = ClassOneUnitTest.class, name = "whenFalse_thenFalse") +@SelectMethod("com.baeldung.testsuite.subpackage.ClassTwoUnitTest#whenFalse_thenFalse") +public class JUnitSelectMethodsSuite { + // runs ClassOneUnitTest and ClassTwoUnitTest +} \ No newline at end of file From 75a64be865bd573134dce88a48582e44ebca7e1a Mon Sep 17 00:00:00 2001 From: hmdrz Date: Thu, 9 Nov 2023 11:22:48 +0330 Subject: [PATCH 134/233] #BAEL-7157: upgrade dependency version and add extra dependencies --- testing-modules/junit-5-advanced/pom.xml | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/testing-modules/junit-5-advanced/pom.xml b/testing-modules/junit-5-advanced/pom.xml index 3ae62eac2e..411f189638 100644 --- a/testing-modules/junit-5-advanced/pom.xml +++ b/testing-modules/junit-5-advanced/pom.xml @@ -45,7 +45,18 @@ ${junit-platform.version} test - + + org.junit.platform + junit-platform-launcher + ${junit-platform.version} + test + + + org.junit.platform + junit-platform-commons + ${junit-platform.version} + test + @@ -70,7 +81,7 @@ 1.49 3.24.2 - 1.9.2 + 1.10.1 3.0.0 From 781b7fde457d67c1549ec8f12d90c0dde15b6c05 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Thu, 9 Nov 2023 15:27:46 +0530 Subject: [PATCH 135/233] JAVA-27244: Changes made removing comment from modules that are added already (#15161) --- pom.xml | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/pom.xml b/pom.xml index a16fabebc5..ffd39b7ea2 100644 --- a/pom.xml +++ b/pom.xml @@ -362,7 +362,7 @@ web-modules/java-lite persistence-modules/deltaspike persistence-modules/hibernate-ogm - persistence-modules/spring-data-cassandra-reactive + persistence-modules/spring-data-cassandra-reactive java-nashorn jeromq spring-ejb-modules/ejb-beans @@ -533,7 +533,7 @@ web-modules/java-lite persistence-modules/deltaspike persistence-modules/hibernate-ogm - persistence-modules/spring-data-cassandra-reactive + persistence-modules/spring-data-cassandra-reactive java-nashorn jeromq spring-ejb-modules/ejb-beans @@ -854,7 +854,7 @@ libraries-apache-commons-2 libraries-apache-commons-collections libraries-apache-commons-io - libraries-data-2 + libraries-data-2 libraries-data-io libraries-files libraries-http @@ -929,7 +929,7 @@ gcp-firebase spring-di-4 spring-kafka-2 - + libraries-llms spring-pulsar @@ -1039,14 +1039,6 @@ core-java-modules gcp-firebase - - - - - - - - spring-aop spring-aop-2 custom-pmd @@ -1138,7 +1130,7 @@ libraries-apache-commons-2 libraries-apache-commons-collections libraries-apache-commons-io - libraries-data-2 + libraries-data-2 libraries-data-io libraries-files libraries-http @@ -1212,7 +1204,7 @@ spring-actuator spring-di-4 spring-kafka-2 - + libraries-llms spring-pulsar From 4145926d9421d1652383606066a2ee84cb398652 Mon Sep 17 00:00:00 2001 From: gaepi Date: Thu, 9 Nov 2023 11:55:32 +0100 Subject: [PATCH 136/233] JAVA-27245 - renamed modules. --- .../spring-cloud-bootstrap/README.md | 2 +- .../spring-cloud-bootstrap/pom.xml | 4 ++-- .../{svc-book => zipkin-log-svc-book}/pom.xml | 4 ++-- .../bootstrap/svcbook/BookServiceApplication.java | 0 .../cloud/bootstrap/svcbook/CookieConfig.java | 0 .../spring/cloud/bootstrap/svcbook/DataLoader.java | 0 .../cloud/bootstrap/svcbook/SecurityConfig.java | 0 .../cloud/bootstrap/svcbook/SessionConfig.java | 0 .../spring/cloud/bootstrap/svcbook/book/Book.java | 0 .../bootstrap/svcbook/book/BookController.java | 0 .../svcbook/book/BookNotFoundException.java | 0 .../bootstrap/svcbook/book/BookRepository.java | 0 .../cloud/bootstrap/svcbook/book/BookService.java | 0 .../src/main/resources/bootstrap.properties | 0 .../src/main/resources/logback.xml | 0 .../java/com/baeldung/SpringContextLiveTest.java | 0 .../src/test/resources/bootstrap.properties | 0 .../{svc-rating => zipkin-log-svc-rating}/pom.xml | 4 ++-- .../cloud/bootstrap/svcrating/CookieConfig.java | 0 .../cloud/bootstrap/svcrating/DataLoader.java | 0 .../svcrating/RatingServiceApplication.java | 0 .../cloud/bootstrap/svcrating/SecurityConfig.java | 0 .../cloud/bootstrap/svcrating/SessionConfig.java | 0 .../cloud/bootstrap/svcrating/rating/Rating.java | 0 .../svcrating/rating/RatingCacheRepository.java | 0 .../svcrating/rating/RatingController.java | 0 .../svcrating/rating/RatingNotFoundException.java | 0 .../svcrating/rating/RatingRepository.java | 0 .../bootstrap/svcrating/rating/RatingService.java | 0 .../src/main/resources/bootstrap.properties | 0 .../src/main/resources/logback.xml | 0 .../java/com/baeldung/SpringContextLiveTest.java | 0 .../src/test/resources/bootstrap.properties | 0 .../.gitignore | 0 .../Dockerfile | 2 +- .../pom.xml | 4 ++-- .../backend/KubernetesBackendApplication.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/logback.xml | 0 .../test/java/com/baeldung/SpringContextTest.java | 0 .../.gitignore | 0 .../Dockerfile | 2 +- .../pom.xml | 4 ++-- .../frontend/KubernetesFrontendApplication.java | 2 +- .../src/main/resources/application.properties | 0 .../src/main/resources/logback.xml | 0 .../test/java/com/baeldung/SpringContextTest.java | 0 .../object-configurations/backend-deployment.yaml | 14 +++++++------- .../object-configurations/frontend-deployment.yaml | 14 +++++++------- .../kubernetes-minikube/pom.xml | 4 ++-- 50 files changed, 30 insertions(+), 30 deletions(-) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/pom.xml (97%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/CookieConfig.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/DataLoader.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SessionConfig.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/resources/bootstrap.properties (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/main/resources/logback.xml (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/test/java/com/baeldung/SpringContextLiveTest.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-book => zipkin-log-svc-book}/src/test/resources/bootstrap.properties (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/pom.xml (97%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/CookieConfig.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/DataLoader.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingCacheRepository.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/resources/bootstrap.properties (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/main/resources/logback.xml (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/test/java/com/baeldung/SpringContextLiveTest.java (100%) rename spring-cloud-modules/spring-cloud-bootstrap/{svc-rating => zipkin-log-svc-rating}/src/test/resources/bootstrap.properties (100%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-backend => minikube-demo-backend}/.gitignore (100%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-backend => minikube-demo-backend}/Dockerfile (62%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-frontend => minikube-demo-backend}/pom.xml (92%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-backend => minikube-demo-backend}/src/main/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplication.java (100%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-backend => minikube-demo-backend}/src/main/resources/application.properties (100%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-backend => minikube-demo-backend}/src/main/resources/logback.xml (100%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-backend => minikube-demo-backend}/src/test/java/com/baeldung/SpringContextTest.java (100%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-frontend => minikube-demo-frontend}/.gitignore (100%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-frontend => minikube-demo-frontend}/Dockerfile (59%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-backend => minikube-demo-frontend}/pom.xml (92%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-frontend => minikube-demo-frontend}/src/main/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplication.java (95%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-frontend => minikube-demo-frontend}/src/main/resources/application.properties (100%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-frontend => minikube-demo-frontend}/src/main/resources/logback.xml (100%) rename spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/{demo-frontend => minikube-demo-frontend}/src/test/java/com/baeldung/SpringContextTest.java (100%) diff --git a/spring-cloud-modules/spring-cloud-bootstrap/README.md b/spring-cloud-modules/spring-cloud-bootstrap/README.md index 252058be1f..661dd7c647 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/README.md +++ b/spring-cloud-modules/spring-cloud-bootstrap/README.md @@ -21,4 +21,4 @@ This module contains articles about bootstrapping Spring Cloud applications that - git commit -m "First commit" - start the config server - start the discovery server - - start all the other servers in any order (gateway, svc-book, svc-rating, zipkin) + - start all the other servers in any order (gateway, zipkin-log-svc-book, zipkin-log-svc-rating, zipkin) diff --git a/spring-cloud-modules/spring-cloud-bootstrap/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/pom.xml index f4d4073ef1..73b07c826f 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/pom.xml @@ -19,8 +19,8 @@ discovery gateway gateway-2 - svc-book - svc-rating + zipkin-log-svc-book + zipkin-log-svc-rating customer-service order-service diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/pom.xml similarity index 97% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/pom.xml rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/pom.xml index c973968a70..2a6196b92b 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud - svc-book + zipkin-log-svc-book 1.0.0-SNAPSHOT - svc-book + zipkin-log-svc-book com.baeldung diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/CookieConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/CookieConfig.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/CookieConfig.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/CookieConfig.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/DataLoader.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/DataLoader.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/DataLoader.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/DataLoader.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SessionConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SessionConfig.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SessionConfig.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SessionConfig.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/resources/bootstrap.properties b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/resources/bootstrap.properties rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/resources/bootstrap.properties diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/resources/logback.xml b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/resources/logback.xml similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/resources/logback.xml rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/resources/logback.xml diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/test/java/com/baeldung/SpringContextLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/test/java/com/baeldung/SpringContextLiveTest.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/test/java/com/baeldung/SpringContextLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/test/resources/bootstrap.properties b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/test/resources/bootstrap.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/test/resources/bootstrap.properties rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/test/resources/bootstrap.properties diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/pom.xml similarity index 97% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/pom.xml rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/pom.xml index 29ebb4c4bc..54572eeea2 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud - svc-rating + zipkin-log-svc-rating 1.0.0-SNAPSHOT - svc-rating + zipkin-log-svc-rating com.baeldung diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/CookieConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/CookieConfig.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/CookieConfig.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/CookieConfig.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/DataLoader.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/DataLoader.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/DataLoader.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/DataLoader.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingCacheRepository.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingCacheRepository.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingCacheRepository.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingCacheRepository.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/resources/bootstrap.properties diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/resources/logback.xml b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/resources/logback.xml similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/resources/logback.xml rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/resources/logback.xml diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/test/java/com/baeldung/SpringContextLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/test/java/com/baeldung/SpringContextLiveTest.java rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/test/java/com/baeldung/SpringContextLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/test/resources/bootstrap.properties b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/test/resources/bootstrap.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/test/resources/bootstrap.properties rename to spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/test/resources/bootstrap.properties diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/.gitignore b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/.gitignore similarity index 100% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/.gitignore rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/.gitignore diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/Dockerfile b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/Dockerfile similarity index 62% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/Dockerfile rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/Dockerfile index a0a9d57662..fad9c11a73 100644 --- a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/Dockerfile +++ b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/Dockerfile @@ -1,5 +1,5 @@ FROM openjdk:8-jdk-alpine VOLUME /tmp -COPY target/demo-backend-1.0-SNAPSHOT.jar app.jar +COPY target/minikube-demo-backend-1.0-SNAPSHOT.jar app.jar ENV JAVA_OPTS="" ENTRYPOINT exec java -jar /app.jar --debug \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/pom.xml b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/pom.xml similarity index 92% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/pom.xml rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/pom.xml index 85eb944b27..c08c6a5a9d 100644 --- a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/pom.xml +++ b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - demo-frontend - demo-frontend + minikube-demo-backend + minikube-demo-backend com.baeldung.spring.cloud diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/main/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplication.java b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/src/main/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplication.java similarity index 100% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/main/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplication.java rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/src/main/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplication.java diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/src/main/resources/application.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/main/resources/application.properties rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/src/main/resources/application.properties diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/main/resources/logback.xml b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/src/main/resources/logback.xml similarity index 100% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/main/resources/logback.xml rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/src/main/resources/logback.xml diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/src/test/java/com/baeldung/SpringContextTest.java rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-backend/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/.gitignore b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/.gitignore similarity index 100% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/.gitignore rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/.gitignore diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/Dockerfile b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/Dockerfile similarity index 59% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/Dockerfile rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/Dockerfile index 69adb03a17..207114b1b5 100644 --- a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/Dockerfile +++ b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/Dockerfile @@ -1,5 +1,5 @@ FROM openjdk:8-jdk-alpine VOLUME /tmp -COPY target/demo-frontend-1.0-SNAPSHOT.jar app.jar +COPY target/minikube-demo-frontend-1.0-SNAPSHOT.jar app.jar ENV JAVA_OPTS="" ENTRYPOINT exec java -jar /app.jar \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/pom.xml b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/pom.xml similarity index 92% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/pom.xml rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/pom.xml index 2b3f849145..8140807606 100644 --- a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-backend/pom.xml +++ b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - demo-backend - demo-backend + minikube-demo-frontend + minikube-demo-frontend com.baeldung.spring.cloud diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/main/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplication.java b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/src/main/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplication.java similarity index 95% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/main/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplication.java rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/src/main/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplication.java index 635a79e8bb..d76fcdfd5d 100644 --- a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/main/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplication.java +++ b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/src/main/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplication.java @@ -22,7 +22,7 @@ public class KubernetesFrontendApplication { RestTemplate restTemplate = new RestTemplate(); String resourceUrl - = "http://demo-backend:8080"; + = "http://minikube-demo-backend:8080"; ResponseEntity response = restTemplate.getForEntity(resourceUrl, String.class); return "Message from backend is: " + response.getBody(); diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/src/main/resources/application.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/main/resources/application.properties rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/src/main/resources/application.properties diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/main/resources/logback.xml b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/src/main/resources/logback.xml similarity index 100% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/main/resources/logback.xml rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/src/main/resources/logback.xml diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/demo-frontend/src/test/java/com/baeldung/SpringContextTest.java rename to spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/minikube-demo-frontend/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/object-configurations/backend-deployment.yaml b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/object-configurations/backend-deployment.yaml index a7e26a6ec5..bcfa80cd7f 100644 --- a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/object-configurations/backend-deployment.yaml +++ b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/object-configurations/backend-deployment.yaml @@ -1,10 +1,10 @@ kind: Service apiVersion: v1 metadata: - name: demo-backend + name: minikube-demo-backend spec: selector: - app: demo-backend + app: minikube-demo-backend tier: backend ports: - protocol: TCP @@ -14,22 +14,22 @@ spec: apiVersion: apps/v1 kind: Deployment metadata: - name: demo-backend + name: dminikube-demo-backend spec: selector: matchLabels: - app: demo-backend + app: minikube-demo-backend tier: backend replicas: 3 template: metadata: labels: - app: demo-backend + app: minikube-demo-backend tier: backend spec: containers: - - name: demo-backend - image: demo-backend:latest + - name: minikube-demo-backend + image: minikube-demo-backend:latest imagePullPolicy: Never ports: - containerPort: 8080 diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/object-configurations/frontend-deployment.yaml b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/object-configurations/frontend-deployment.yaml index bf44dce21c..f96c7a1a9c 100644 --- a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/object-configurations/frontend-deployment.yaml +++ b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/object-configurations/frontend-deployment.yaml @@ -1,10 +1,10 @@ kind: Service apiVersion: v1 metadata: - name: demo-frontend + name: minikube-demo-frontend spec: selector: - app: demo-frontend + app: minikube-demo-frontend ports: - protocol: TCP port: 8081 @@ -14,20 +14,20 @@ spec: apiVersion: apps/v1 kind: Deployment metadata: - name: demo-frontend + name: minikube-demo-frontend spec: selector: matchLabels: - app: demo-frontend + app: minikube-demo-frontend replicas: 3 template: metadata: labels: - app: demo-frontend + app: minikube-demo-frontend spec: containers: - - name: demo-frontend - image: demo-frontend:latest + - name: minikube-demo-frontend + image: minikube-demo-frontend:latest imagePullPolicy: Never ports: - containerPort: 8081 diff --git a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/pom.xml b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/pom.xml index b778ee1b57..1c7456d007 100644 --- a/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/pom.xml +++ b/spring-cloud-modules/spring-cloud-kubernetes/kubernetes-minikube/pom.xml @@ -14,8 +14,8 @@ - demo-backend - demo-frontend + minikube-demo-backend + minikube-demo-frontend \ No newline at end of file From d1685c42bd9f2692f16dd5f86f837d4c9714f051 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Thu, 9 Nov 2023 16:47:34 +0530 Subject: [PATCH 137/233] JAVA-26001_D_M: Fix formatting of POMs for modules D to M (#14958) --- google-auto-project/pom.xml | 1 - json-modules/json-2/pom.xml | 4 ++-- .../jacoco-coverage-services-example/pom.xml | 7 +++---- maven-modules/jacoco-coverage-aggregation/pom.xml | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/google-auto-project/pom.xml b/google-auto-project/pom.xml index 034fea5aad..175e0c20c6 100644 --- a/google-auto-project/pom.xml +++ b/google-auto-project/pom.xml @@ -8,7 +8,6 @@ google-auto-project pom - com.baeldung parent-modules diff --git a/json-modules/json-2/pom.xml b/json-modules/json-2/pom.xml index 6cca576fb1..b9a75e8aff 100644 --- a/json-modules/json-2/pom.xml +++ b/json-modules/json-2/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 json-2 0.0.1-SNAPSHOT diff --git a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml index 2c06694b46..223689f8ff 100644 --- a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml @@ -13,8 +13,7 @@ jacoco-coverage-aggregation 1.0 - - + org.springframework @@ -28,7 +27,7 @@ test - + @@ -43,7 +42,7 @@ - + 5.9.2 6.0.11 diff --git a/maven-modules/jacoco-coverage-aggregation/pom.xml b/maven-modules/jacoco-coverage-aggregation/pom.xml index 70243973e8..6d1aab3c3d 100644 --- a/maven-modules/jacoco-coverage-aggregation/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/pom.xml @@ -21,7 +21,7 @@ jacoco-coverage-controllers-example jacoco-coverage-aggregate-report - + From 3fbd2eaab9561c4fa34d3b982c349e66c24de632 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Thu, 9 Nov 2023 16:48:02 +0530 Subject: [PATCH 138/233] JAVA-26001_Q_Z: Fix formatting of POMs for modules Q to Z (#14960) --- pom.xml | 4 +- spring-6-rsocket/pom.xml | 7 +- spring-aop-2/pom.xml | 94 +++++++++---------- .../spring-boot-3-testcontainers/pom.xml | 5 +- .../spring-boot-graalvm-docker/pom.xml | 61 ++++++------ .../spring-boot-jasypt/pom.xml | 3 +- .../spring-boot-ssl-bundles/pom.xml | 4 +- .../spring-boot-telegram/pom.xml | 4 +- .../spring-5-reactive/pom.xml | 0 .../spring-reactive-data-couchbase/pom.xml | 4 +- testing-modules/junit-5-basics-2/pom.xml | 9 +- 11 files changed, 100 insertions(+), 95 deletions(-) create mode 100644 spring-reactive-modules/spring-5-reactive/pom.xml diff --git a/pom.xml b/pom.xml index ffd39b7ea2..bb5a0c9e7b 100644 --- a/pom.xml +++ b/pom.xml @@ -344,7 +344,7 @@ core-java-modules/core-java-security core-java-modules/core-java-lang core-java-modules/core-java-lang-math-3 - + core-java-modules/core-java-streams-2 @@ -517,7 +517,7 @@ core-java-modules/core-java-security core-java-modules/core-java-lang core-java-modules/core-java-lang-math-3 - + core-java-modules/core-java-streams-2 diff --git a/spring-6-rsocket/pom.xml b/spring-6-rsocket/pom.xml index 0f9e63bc7e..7f88df01e2 100644 --- a/spring-6-rsocket/pom.xml +++ b/spring-6-rsocket/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.bealdung spring-6-rsocket @@ -16,7 +16,6 @@ - org.springframework.boot spring-boot-starter-rsocket @@ -66,9 +65,11 @@ + 3.1.3 1.4.11 2.0.9 + diff --git a/spring-aop-2/pom.xml b/spring-aop-2/pom.xml index 206e1d7d7c..f1257369e0 100644 --- a/spring-aop-2/pom.xml +++ b/spring-aop-2/pom.xml @@ -74,54 +74,54 @@ - - compile-time-weaving + + compile-time-weaving - - - org.springframework - spring-aspects - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - com.baeldung.selfinvocation.CompileTimeWeavingIntegrationTest - - - - - org.codehaus.mojo - aspectj-maven-plugin - ${aspectj-plugin.version} - - ${java.version} - ${java.version} - ${java.version} - ignore - UTF-8 - - - org.springframework - spring-aspects - - - - - - - compile - - - - - - - + + + org.springframework + spring-aspects + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + com.baeldung.selfinvocation.CompileTimeWeavingIntegrationTest + + + + + org.codehaus.mojo + aspectj-maven-plugin + ${aspectj-plugin.version} + + ${java.version} + ${java.version} + ${java.version} + ignore + UTF-8 + + + org.springframework + spring-aspects + + + + + + + compile + + + + + + + load-time-weaving diff --git a/spring-boot-modules/spring-boot-3-testcontainers/pom.xml b/spring-boot-modules/spring-boot-3-testcontainers/pom.xml index 173fb8795c..d24da58742 100644 --- a/spring-boot-modules/spring-boot-3-testcontainers/pom.xml +++ b/spring-boot-modules/spring-boot-3-testcontainers/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 spring-boot-3-testcontainers 0.0.1-SNAPSHOT @@ -16,7 +16,6 @@ - org.springframework.boot spring-boot-starter diff --git a/spring-boot-modules/spring-boot-graalvm-docker/pom.xml b/spring-boot-modules/spring-boot-graalvm-docker/pom.xml index a3a1b148c2..253e8fceb6 100644 --- a/spring-boot-modules/spring-boot-graalvm-docker/pom.xml +++ b/spring-boot-modules/spring-boot-graalvm-docker/pom.xml @@ -1,41 +1,44 @@ - + 4.0.0 - - - com.baeldung - parent-boot-3 - 0.0.1-SNAPSHOT - ../../parent-boot-3 - - com.baeldung spring-boot-graalvm-docker 1.0.0 spring-boot-graalvm-docker Spring Boot GrralVM with Docker + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + - - - org.graalvm.buildtools - native-maven-plugin - - - org.springframework.boot - spring-boot-maven-plugin - - + + + org.graalvm.buildtools + native-maven-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/spring-boot-modules/spring-boot-jasypt/pom.xml b/spring-boot-modules/spring-boot-jasypt/pom.xml index 70bbe35319..0f9ad72b64 100644 --- a/spring-boot-modules/spring-boot-jasypt/pom.xml +++ b/spring-boot-modules/spring-boot-jasypt/pom.xml @@ -27,7 +27,7 @@ com.github.ulisesbocchio - jasypt-spring-boot-starter + jasypt-spring-boot-starter ${jasypt.version} @@ -49,4 +49,5 @@ 3.0.5 + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-ssl-bundles/pom.xml b/spring-boot-modules/spring-boot-ssl-bundles/pom.xml index 770d8c2f01..1f4e58f21f 100644 --- a/spring-boot-modules/spring-boot-ssl-bundles/pom.xml +++ b/spring-boot-modules/spring-boot-ssl-bundles/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 spring-boot-ssl-bundles spring-boot-ssl-bundles diff --git a/spring-boot-modules/spring-boot-telegram/pom.xml b/spring-boot-modules/spring-boot-telegram/pom.xml index 67fdf197f8..9077e90400 100644 --- a/spring-boot-modules/spring-boot-telegram/pom.xml +++ b/spring-boot-modules/spring-boot-telegram/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.baelding spring-boot-telegram diff --git a/spring-reactive-modules/spring-5-reactive/pom.xml b/spring-reactive-modules/spring-5-reactive/pom.xml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml index a7481d8aca..2ac8ad19ac 100644 --- a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml +++ b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-reactive-data-couchbase spring-reactive-data-couchbase diff --git a/testing-modules/junit-5-basics-2/pom.xml b/testing-modules/junit-5-basics-2/pom.xml index 85b6c707fb..b430161380 100644 --- a/testing-modules/junit-5-basics-2/pom.xml +++ b/testing-modules/junit-5-basics-2/pom.xml @@ -1,16 +1,16 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + junit-5-basics-2 + com.baeldung parent-modules 1.0.0-SNAPSHOT - junit-5-basics-2 - commons-cli @@ -30,6 +30,7 @@ test + From bf5328c3970a508bbbb47257e5ea222363b27fa8 Mon Sep 17 00:00:00 2001 From: timis1 Date: Thu, 9 Nov 2023 14:39:49 +0200 Subject: [PATCH 139/233] JAVA-27237 Review log statements for projects | Week 44 | Manually Created (conti-1) --- .../src/main/resources/logback.xml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/src/main/resources/logback.xml b/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/src/main/resources/logback.xml index d944288ca4..1533b49c06 100644 --- a/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/src/main/resources/logback.xml +++ b/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/src/main/resources/logback.xml @@ -8,7 +8,9 @@ - + + + From 4cf46ce71908be7608b8a707feaca7e49f0213d3 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Thu, 9 Nov 2023 19:19:22 +0530 Subject: [PATCH 140/233] JAVA-27190 Upgrade hibernate validator version --- .../custom-validations-opeanpi-codegen/pom.xml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml index b57a014a8f..573b132467 100644 --- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml +++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml @@ -27,15 +27,10 @@ test - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} - - javax.validation - validation-api - ${validation-api.version} - org.openapitools openapi-generator @@ -97,8 +92,7 @@ 3.0.0 2.17.1 1.7.0 - 6.0.10.Final - 2.0.1.Final + 8.0.1.Final 3.3.4 2.10.0.pr3 5.1.0 From 52197768be4b9d9bf325a46eee5de4fde180984a Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Thu, 9 Nov 2023 19:23:42 +0530 Subject: [PATCH 141/233] JAVA-27190 Remove code overriding parent-boot-version of hibernate-validator --- .../custom-validations-opeanpi-codegen/pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml index 573b132467..95d3239b96 100644 --- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml +++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml @@ -26,11 +26,6 @@ spring-boot-starter-test test - - org.hibernate.validator - hibernate-validator - ${hibernate-validator.version} - org.openapitools openapi-generator @@ -92,7 +87,6 @@ 3.0.0 2.17.1 1.7.0 - 8.0.1.Final 3.3.4 2.10.0.pr3 5.1.0 From 499ed4bbbd64a3e778a908f1a218df18cb974479 Mon Sep 17 00:00:00 2001 From: Paul Greer Date: Thu, 9 Nov 2023 21:52:12 +0000 Subject: [PATCH 142/233] BAEL-6943: Difference between String and StringBuffer in Java (#14815) * Add files via upload * Add files via upload * Add files via upload * Add files via upload * Add files via upload * Add files via upload * Add files via upload * Delete core-java-modules/core-java-lang-6/src/main/java/com/baeldung/intposneg directory * Delete core-java-modules/core-java-lang-6/src/test/java/com/baeldung/intposneg directory * Add files via upload * Delete core-java-modules/core-java-numbers-conversions/src/main/java/com/baeldung/stringtoint/intposneg directory * Add files via upload * Add files via upload * Delete core-java-modules/core-java-numbers-conversions/src/main/java/com/baeldung/intposneg directory * Delete core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/intposneg directory * Add files via upload * Add files via upload * Delete core-java-modules/core-java-lang-6/src/main/java/com/baeldung/diffstringstringbuffer directory * Delete core-java-modules/core-java-lang-6/src/test/java/com/baeldung/diffstringstringbuffer directory * Delete core-java-modules/core-java-string-apis-2/src/main/java/com/baeldung/diffstringstringbuffer directory * Delete core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/diffstringstringbuffer directory * Add files via upload * Add files via upload --- .../diffstringstringbuffer/MemoryAddress.java | 33 +++++++++++++++++++ .../StringBufferUnitTest.java | 18 ++++++++++ .../StringUnitTest.java | 29 ++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 core-java-modules/core-java-string-apis-2/src/main/java/com/baeldung/diffstringstringbuffer/MemoryAddress.java create mode 100644 core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/diffstringstringbuffer/StringBufferUnitTest.java create mode 100644 core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/diffstringstringbuffer/StringUnitTest.java diff --git a/core-java-modules/core-java-string-apis-2/src/main/java/com/baeldung/diffstringstringbuffer/MemoryAddress.java b/core-java-modules/core-java-string-apis-2/src/main/java/com/baeldung/diffstringstringbuffer/MemoryAddress.java new file mode 100644 index 0000000000..42a4d9d4b4 --- /dev/null +++ b/core-java-modules/core-java-string-apis-2/src/main/java/com/baeldung/diffstringstringbuffer/MemoryAddress.java @@ -0,0 +1,33 @@ +package com.baeldung.diffstringstringbuffer; + +import java.lang.reflect.Field; + +import sun.misc.Unsafe; + +public class MemoryAddress { + public long getMemoryAddress(Object object) { + Object[] arrayOfObject = new Object[]{object}; + Unsafe unsafe = null; + try { + Field field = Unsafe.class.getDeclaredField("theUnsafe"); + field.setAccessible(true); + unsafe = (Unsafe) field.get(null); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + assert unsafe != null; + long arrayBaseOffset = unsafe.arrayBaseOffset(Object[].class); + int addressSize = unsafe.addressSize(); + long objectAddress; + if (addressSize == 4) { + objectAddress = unsafe.getInt(arrayOfObject, arrayBaseOffset); + } else { + if (addressSize == 8) { + objectAddress = unsafe.getLong(arrayOfObject, arrayBaseOffset); + } else { + throw new Error("Error: Size not supported: " + addressSize); + } + } + return objectAddress; + } +} diff --git a/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/diffstringstringbuffer/StringBufferUnitTest.java b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/diffstringstringbuffer/StringBufferUnitTest.java new file mode 100644 index 0000000000..adbe69b65e --- /dev/null +++ b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/diffstringstringbuffer/StringBufferUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.diffstringstringbuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class StringBufferUnitTest { + @Test + void whenStringBufferVariableIsReassigned_thenVariableRetainsOriginalMemoryAddress() { + MemoryAddress memoryAddress = new MemoryAddress(); + StringBuffer stringBuffer = new StringBuffer("DownTown"); + long address1 = memoryAddress.getMemoryAddress(stringBuffer); + stringBuffer.insert(0, "Coder"); + assertEquals(stringBuffer.toString(), "CoderDownTown"); + long address2 = memoryAddress.getMemoryAddress(stringBuffer); + assertEquals(address1, address2); + } +} diff --git a/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/diffstringstringbuffer/StringUnitTest.java b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/diffstringstringbuffer/StringUnitTest.java new file mode 100644 index 0000000000..bf1fcfeaf1 --- /dev/null +++ b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/diffstringstringbuffer/StringUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.diffstringstringbuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.Test; + +public class StringUnitTest { + @Test + void whenStringVariableIsReassigned_thenVariableGetsNewMemoryAddress() { + MemoryAddress memoryAddress = new MemoryAddress(); + String s1 = "DownTown"; + long address1 = memoryAddress.getMemoryAddress(s1); + s1 = "Coder"; + long address2 = memoryAddress.getMemoryAddress(s1); + assertNotEquals(address1, address2); + } + + @Test + void whenStringsAreIncludedInAStringBuffer_thenThoseStringsRemainImmutable() { + String s1 = "TopCat"; + StringBuffer stringBuffer = new StringBuffer("DownTown"); + stringBuffer.append(s1); + stringBuffer.reverse(); + assertNotEquals(s1, "taCpoT"); + stringBuffer.delete(0, 3); + assertEquals(s1, "TopCat"); + } +} From 0b0db24ebb0e028008722d698716e9d0a17452b8 Mon Sep 17 00:00:00 2001 From: psevestre Date: Thu, 9 Nov 2023 18:56:11 -0300 Subject: [PATCH 143/233] [BAEL-7044] Shared Memory Between Two JVMs (#15162) * [BAEL-4849] Article code * [BAEL-4968] Article code * [BAEL-4968] Article code * [BAEL-4968] Article code * [BAEL-4968] Remove extra comments * [BAEL-5258] Article Code * [BAEL-2765] PKCE Support for Secret Clients * [BAEL-5698] Article code * [BAEL-5698] Article code * [BAEL-5905] Initial code * [BAEL-5905] Article code * [BAEL-5905] Relocate article code to new module * [BAEL-6275] PostgreSQL NOTIFY/LISTEN * [BAEL-6275] Minor correction * BAEL-6138 * [BAEL-6138] WIP - LiveTest * [BAEL-6138] Tutorial Code * [BAEL-6138] Tutorial Code * [BAEL-6694] Article Code * [BAEL-7044] Tutorial code --------- Co-authored-by: Philippe Sevestre --- .../core-java-sun/shared-mem-test1.bat | 8 ++ .../core-java-sun/shared-mem-test2.bat | 10 ++ .../com/baeldung/sharedmem/ConsumerApp.java | 94 ++++++++++++++ .../sharedmem/ConsumerAppWithSpinLock.java | 119 ++++++++++++++++++ .../com/baeldung/sharedmem/ProducerApp.java | 89 +++++++++++++ .../sharedmem/ProducerAppWithSpinLock.java | 117 +++++++++++++++++ .../java/com/baeldung/sharedmem/SpinLock.java | 43 +++++++ 7 files changed, 480 insertions(+) create mode 100644 core-java-modules/core-java-sun/shared-mem-test1.bat create mode 100644 core-java-modules/core-java-sun/shared-mem-test2.bat create mode 100644 core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ConsumerApp.java create mode 100644 core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ConsumerAppWithSpinLock.java create mode 100644 core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ProducerApp.java create mode 100644 core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ProducerAppWithSpinLock.java create mode 100644 core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/SpinLock.java diff --git a/core-java-modules/core-java-sun/shared-mem-test1.bat b/core-java-modules/core-java-sun/shared-mem-test1.bat new file mode 100644 index 0000000000..148c51eb36 --- /dev/null +++ b/core-java-modules/core-java-sun/shared-mem-test1.bat @@ -0,0 +1,8 @@ +@rem This bat file starts the consumer and producer (more or less) at the same time +cd target\classes +rem start java --add-opens java.base/java.nio=ALL-UNNAMED com.baeldung.sharedmem.ProducerApp c:\lixo\sharedmem.bin 65536 +rem start java --add-opens java.base/java.nio=ALL-UNNAMED com.baeldung.sharedmem.ConsumerApp c:\lixo\sharedmem.bin 65536 +start %JAVA_HOME%\bin\java com.baeldung.sharedmem.ProducerApp c:\lixo\sharedmem.bin 65536 +start %JAVA_HOME%\bin\java com.baeldung.sharedmem.ConsumerApp c:\lixo\sharedmem.bin 65536 +cd .. +cd .. diff --git a/core-java-modules/core-java-sun/shared-mem-test2.bat b/core-java-modules/core-java-sun/shared-mem-test2.bat new file mode 100644 index 0000000000..7a7f8f7caa --- /dev/null +++ b/core-java-modules/core-java-sun/shared-mem-test2.bat @@ -0,0 +1,10 @@ +@rem This bat file starts the consumer and producer (more or less) at the same time +del target\sharedmem.bin +echo "" > target\sharedmem.bin +cd target\classes +rem start java --add-opens java.base/java.nio=ALL-UNNAMED com.baeldung.sharedmem.ProducerAppWithSpinLock ..\sharedmem.bin 65536 +rem start java --add-opens java.base/java.nio=ALL-UNNAMED com.baeldung.sharedmem.ConsumerAppWithSpinLock ..\sharedmem.bin 65536 +start %JAVA_HOME%\bin\java com.baeldung.sharedmem.ProducerAppWithSpinLock ..\sharedmem.bin 65536 +start %JAVA_HOME%\bin\java com.baeldung.sharedmem.ConsumerAppWithSpinLock ..\sharedmem.bin 65536 +cd .. +cd .. diff --git a/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ConsumerApp.java b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ConsumerApp.java new file mode 100644 index 0000000000..1fbc02bee9 --- /dev/null +++ b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ConsumerApp.java @@ -0,0 +1,94 @@ +package com.baeldung.sharedmem; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.Random; + +public class ConsumerApp { + + public static void main(String[] args) throws Exception { + + MessageDigest digest = MessageDigest.getInstance("SHA1"); + digest.digest(new byte[256]); + byte[] dummy = digest.digest(); + int hashLen = dummy.length; + + System.out.println("Starting consumer iterations..."); + + long size = Long.parseLong(args[1]); + MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen); + long start = System.currentTimeMillis(); + long iterations = 0; + int capacity = shm.capacity(); + + long matchCount = 0; + long mismatchCount = 0; + byte[] expectedHash = new byte[hashLen]; + + while (System.currentTimeMillis() - start < 30_000) { + + for (int i = 0; i < capacity - hashLen; i++) { + byte value = shm.get(i); + digest.update(value); + } + + byte[] hash = digest.digest(); + shm.position(capacity-hashLen); + shm.get(expectedHash); + + if (Arrays.equals(hash, expectedHash)) { + matchCount++; + } else { + mismatchCount++; + } + + iterations++; + } + + System.out.printf("%d iterations run. matches=%d, mismatches=%d\n", iterations, matchCount, mismatchCount); + System.out.println("Press to exit"); + System.console() + .readLine(); + } + + private static MappedByteBuffer createSharedMemory(String path, long size) { + + try (FileChannel fc = (FileChannel) Files.newByteChannel( + new File(path).toPath(), + EnumSet.of( + StandardOpenOption.CREATE, + StandardOpenOption.SPARSE, + StandardOpenOption.WRITE, + StandardOpenOption.READ))) { + return fc.map(FileChannel.MapMode.READ_WRITE, 0, size); + + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } + + private static long getBufferAddress(MappedByteBuffer shm) { + try { + Class cls = shm.getClass(); + Method maddr = cls.getMethod("address"); + maddr.setAccessible(true); + Long addr = (Long) maddr.invoke(shm); + if (addr == null) { + throw new RuntimeException("Unable to retrieve buffer's address"); + } + return addr; + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + throw new RuntimeException(ex); + } + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ConsumerAppWithSpinLock.java b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ConsumerAppWithSpinLock.java new file mode 100644 index 0000000000..fa91edda40 --- /dev/null +++ b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ConsumerAppWithSpinLock.java @@ -0,0 +1,119 @@ +package com.baeldung.sharedmem; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.Random; + +public class ConsumerAppWithSpinLock { + + public static void main(String[] args) { + try { + // Small wait to ensure the Producer gets the first round. Otherwise the hash will be invalid + Thread.sleep(1000); + run(args); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + System.console() + .printf("Press to continue"); + System.console() + .readLine(); + } + } + + private static void run(String args[]) throws Exception { + + MessageDigest digest = MessageDigest.getInstance("SHA1"); + digest.digest(new byte[256]); + byte[] dummy = digest.digest(); + int hashLen = dummy.length; + + long size = Long.parseLong(args[1]); + MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen); + long addr = getBufferAddress(shm); + + System.out.printf("Buffer address: 0x%08x\n", addr); + + Random rnd = new Random(); + + long start = System.currentTimeMillis(); + long iterations = 0; + int capacity = shm.capacity(); + System.out.println("Starting consumer iterations..."); + + long matchCount = 0; + long mismatchCount = 0; + byte[] expectedHash = new byte[hashLen]; + SpinLock lock = new SpinLock(addr); + + while (System.currentTimeMillis() - start < 30_000) { + + if (!lock.tryLock(5_000)) { + throw new RuntimeException("Unable to acquire lock"); + } + + try { + for (int i = 4; i < capacity - hashLen; i++) { + byte value = shm.get(i); + digest.update(value); + } + + byte[] hash = digest.digest(); + shm.position(capacity-hashLen); + shm.get(expectedHash); + + if (Arrays.equals(hash, expectedHash)) { + matchCount++; + } else { + mismatchCount++; + } + + iterations++; + } finally { + lock.unlock(); + } + } + + System.out.printf("%d iteractions run. matches=%d, mismatches=%d\n", iterations, matchCount, mismatchCount); + } + + private static MappedByteBuffer createSharedMemory(String path, long size) { + + try (FileChannel fc = (FileChannel) Files.newByteChannel( + new File(path).toPath(), + EnumSet.of( + StandardOpenOption.CREATE, + StandardOpenOption.SPARSE, + StandardOpenOption.WRITE, + StandardOpenOption.READ))) { + return fc.map(FileChannel.MapMode.READ_WRITE, 0, size); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } + + private static long getBufferAddress(MappedByteBuffer shm) { + try { + Class cls = shm.getClass(); + Method maddr = cls.getMethod("address"); + maddr.setAccessible(true); + Long addr = (Long) maddr.invoke(shm); + if (addr == null) { + throw new RuntimeException("Unable to retrieve buffer's address"); + } + return addr; + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + throw new RuntimeException(ex); + } + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ProducerApp.java b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ProducerApp.java new file mode 100644 index 0000000000..ab7ca4d859 --- /dev/null +++ b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ProducerApp.java @@ -0,0 +1,89 @@ +package com.baeldung.sharedmem; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.util.EnumSet; +import java.util.Random; + +public class ProducerApp { + + + public static void main(String[] args) throws Exception { + + MessageDigest digest = MessageDigest.getInstance("SHA1"); + digest.digest(new byte[256]); + byte[] dummy = digest.digest(); + int hashLen = dummy.length; + + + long size = Long.parseLong(args[1]); + MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen); + + System.out.println("Starting producer iterations..."); + + long start = System.currentTimeMillis(); + long iterations = 0; + int capacity = shm.capacity(); + Random rnd = new Random(); + + while(System.currentTimeMillis() - start < 30000) { + + for (int i = 0; i < capacity - hashLen; i++) { + byte value = (byte) (rnd.nextInt(256) & 0x00ff); + digest.update(value); + shm.put(i, value); + } + + // Write hash at the end + byte[] hash = digest.digest(); + shm.position(capacity - hashLen); + shm.put(hash); + iterations++; + } + + System.out.printf("%d iterations run\n", iterations); + System.out.println("Press to exit"); + System.console().readLine(); + + } + + private static long getBufferAddress(MappedByteBuffer shm) { + try { + Class cls = shm.getClass(); + Method maddr = cls.getMethod("address"); + maddr.setAccessible(true); + Long addr = (Long) maddr.invoke(shm); + if ( addr == null ) { + throw new RuntimeException("Unable to retrieve buffer's address"); + } + return addr; + } + catch( NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + throw new RuntimeException(ex); + } + } + + private static MappedByteBuffer createSharedMemory(String path, long size) { + + try (FileChannel fc = (FileChannel)Files.newByteChannel(new File(path).toPath(), + EnumSet.of( + StandardOpenOption.CREATE, + StandardOpenOption.SPARSE, + StandardOpenOption.WRITE, + StandardOpenOption.READ))) { + + return fc.map(FileChannel.MapMode.READ_WRITE, 0, size); + } + catch( IOException ioe) { + throw new RuntimeException(ioe); + } + } + +} diff --git a/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ProducerAppWithSpinLock.java b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ProducerAppWithSpinLock.java new file mode 100644 index 0000000000..619955eb2d --- /dev/null +++ b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/ProducerAppWithSpinLock.java @@ -0,0 +1,117 @@ +package com.baeldung.sharedmem; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.util.EnumSet; +import java.util.Random; + +public class ProducerAppWithSpinLock { + + public static void main(String[] args) { + try { + run(args); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + System.console() + .printf("Press to continue"); + System.console() + .readLine(); + } + } + + + public static void run(String[] args) throws Exception { + + MessageDigest digest = MessageDigest.getInstance("SHA1"); + digest.digest(new byte[256]); + byte[] dummy = digest.digest(); + int hashLen = dummy.length; + + + long size = Long.parseLong(args[1]); + MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen); + + // Cleanup lock area + shm.putInt(0,0); + + long addr = getBufferAddress(shm); + System.out.printf("Buffer address: 0x%08x\n",addr); + Random rnd = new Random(); + + long start = System.currentTimeMillis(); + long iterations = 0; + int capacity = shm.capacity(); + System.out.println("Starting producer iterations..."); + SpinLock lock = new SpinLock(addr); + while(System.currentTimeMillis() - start < 30000) { + + if(!lock.tryLock(5000)) { + throw new RuntimeException("Unable to acquire lock"); + } + + try { + // Skip the first 4 bytes, as they're used by the lock + for (int i = 4; i < capacity - hashLen; i++) { + byte value = (byte) (rnd.nextInt(256) & 0x00ff); + digest.update(value); + shm.put(i, value); + } + + // Write hash at the end + byte[] hash = digest.digest(); + shm.position(capacity-hashLen); + shm.put(hash); + iterations++; + } + finally { + lock.unlock(); + } + } + + System.out.printf("%d iterations run\n", iterations); + + } + + private static long getBufferAddress(MappedByteBuffer shm) { + try { + Class cls = shm.getClass(); + Method maddr = cls.getMethod("address"); + maddr.setAccessible(true); + Long addr = (Long) maddr.invoke(shm); + if ( addr == null ) { + throw new RuntimeException("Unable to retrieve buffer's address"); + } + return addr; + } + catch( NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + throw new RuntimeException(ex); + } + } + + private static MappedByteBuffer createSharedMemory(String path, long size) { + + try (FileChannel fc = (FileChannel)Files.newByteChannel(new File(path).toPath(), + EnumSet.of( + StandardOpenOption.CREATE, + StandardOpenOption.SPARSE, + StandardOpenOption.WRITE, + StandardOpenOption.READ))) { + + return fc.map(FileChannel.MapMode.READ_WRITE, 0, size); + + } + catch( IOException ioe) { + throw new RuntimeException(ioe); + } + + } + +} diff --git a/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/SpinLock.java b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/SpinLock.java new file mode 100644 index 0000000000..145ac1e121 --- /dev/null +++ b/core-java-modules/core-java-sun/src/main/java/com/baeldung/sharedmem/SpinLock.java @@ -0,0 +1,43 @@ +package com.baeldung.sharedmem; + +//import sun.misc.Unsafe; + +import java.lang.reflect.Field; + +import sun.misc.Unsafe; + +public class SpinLock { + private static final Unsafe unsafe; + + static { + try { + Field f = Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + unsafe = (Unsafe) f.get(null); + } + catch(NoSuchFieldException | IllegalAccessException ex) { + throw new RuntimeException(ex); + } + } + + private final long addr; + + public SpinLock(long addr) { + this.addr = addr; + } + + public boolean tryLock(long maxWait) { + long deadline = System.currentTimeMillis() + maxWait; + while(System.currentTimeMillis() < deadline ) { + if ( unsafe.compareAndSwapInt(null,addr,0,1)) { + return true; + } + } + return false; + } + + public void unlock() { + unsafe.putInt(addr,0); + } + +} From 63679af8caa320ea547baa97a1d0c1e94fe69773 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bogdan=20Cardo=C5=9F?= <106325528+sodrac@users.noreply.github.com> Date: Fri, 10 Nov 2023 00:01:10 +0200 Subject: [PATCH 144/233] BAEL-6874 update test code for article (#15164) * BAEL-6819 convert from int to Long in Java * BAEL-6819 update package name * BAEL-6874 test code for article * BAEL-6874 rename test class * BAEL-6874 update test code for article * BAEL-6874 update test code for article --- .../GenericNumbersComparatorUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java index 0fcc0f3453..0b0295c2db 100644 --- a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java @@ -78,7 +78,7 @@ class GenericNumbersComparatorUnitTest { assertEquals(true, isEqual.test(5, 5.0)); } - private boolean someCondition = true; + private boolean someCondition; Function dynamicFunction = someCondition ? Number::doubleValue : Number::intValue; Comparator dynamicComparator = (num1, num2) -> ((Comparable) dynamicFunction.apply(num1)).compareTo(dynamicFunction.apply(num2)); From 1f609d3aafe8149885b06db927912d10e01a0362 Mon Sep 17 00:00:00 2001 From: Dmytro Budym <46810751+dbudim@users.noreply.github.com> Date: Fri, 10 Nov 2023 04:08:28 +0100 Subject: [PATCH 145/233] =?UTF-8?q?Code=20examples=20for=20article:=20Swit?= =?UTF-8?q?ching=20Between=20Frames=20Using=20Selenium=20We=E2=80=A6=20(#1?= =?UTF-8?q?4973)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Code examples for article: Switching Between Frames Using Selenium WebDriver in Java * continuation indent 2 * moved to selenium-2 package --- .../selenium/iframe/IframeManualTest.java | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 testing-modules/selenium-2/src/test/java/com/baeldung/selenium/iframe/IframeManualTest.java diff --git a/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/iframe/IframeManualTest.java b/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/iframe/IframeManualTest.java new file mode 100644 index 0000000000..bc617a4777 --- /dev/null +++ b/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/iframe/IframeManualTest.java @@ -0,0 +1,120 @@ +package com.baeldung.selenium.iframe; + +import io.github.bonigarcia.wdm.WebDriverManager; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.time.Duration; + + +public class IframeManualTest { + + private WebDriver driver; + private static final int TIMEOUT = 10; + + @BeforeMethod + public void init() { + WebDriverManager.chromedriver().setup(); + driver = new ChromeDriver(); + } + + @Test + public void whenSwitchToFrameUsingWebElement_thenSwitched() { + openDemoPage(); + WebElement iframeElement = driver.findElement(By.cssSelector("#myFrame2")); + + new WebDriverWait(driver, Duration.ofSeconds(10)) + .until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(iframeElement)); + waitForTextInFrame(); + } + + @Test + public void whenSwitchToFrameUsingName_thenSwitched() { + openDemoPage(); + new WebDriverWait(driver, Duration.ofSeconds(10)) + .until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("frameName2")); + waitForTextInFrame(); + } + + @Test + public void whenSwitchToFrameUsingId_thenSwitched() { + openDemoPage(); + new WebDriverWait(driver, Duration.ofSeconds(10)) + .until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("myFrame2")); + waitForTextInFrame(); + } + + @Test + public void whenSwitchToInnerFrameFromOuter_thenSwitched() { + openPageWithNestedFrames(); + switchToNestedFrame(); + waitForLinkInNestedFrame(); + } + + @Test + public void whenSwitchToParentFrame_thenSwitched() { + openPageWithNestedFrames(); + switchToNestedFrame(); + driver.switchTo().parentFrame(); + waitForTextInParentFrame(); + } + + @Test + public void whenSwitchToDefaultContent_thenSwitched() { + openPageWithNestedFrames(); + switchToNestedFrame(); + driver.switchTo().defaultContent(); + waitForElementInDefaultContent(); + } + + @AfterMethod + public void tearDown() { + driver.quit(); + } + + + private void openDemoPage() { + driver.get("https://seleniumbase.io/demo_page"); + new WebDriverWait(driver, Duration.ofSeconds(10)) + .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#myForm"))); + } + + private void openPageWithNestedFrames() { + driver.get("https://seleniumbase.io/w3schools/iframes"); + new WebDriverWait(driver, Duration.ofSeconds(10)) + .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#runbtn"))); + } + + private void switchToNestedFrame() { + driver.switchTo().frame("iframeResult"); + WebElement innerFrame = driver.findElement(By.cssSelector("[src='./demo_iframe.htm']")); + driver.switchTo().frame(innerFrame); + } + + private void waitForTextInFrame() { + new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT)) + .until(ExpectedConditions.textToBePresentInElementLocated(By.cssSelector("h4"), "iFrame Text")); + } + + private void waitForLinkInNestedFrame() { + new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT)) + .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("[href='https://seleniumbase.io/w3schools/iframes.html']"))); + } + + private void waitForTextInParentFrame() { + new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT)) + .until(ExpectedConditions.textToBePresentInElementLocated(By.cssSelector("h2"), "HTML Iframes (nested iframes)")); + } + + private void waitForElementInDefaultContent() { + new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT)) + .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#runbtn"))); + } +} From 0ce0a647a112de2828e049762affbede65132b85 Mon Sep 17 00:00:00 2001 From: Ulisses Lima Date: Fri, 10 Nov 2023 04:10:03 -0300 Subject: [PATCH 146/233] MongoDbHashMapIntegrationTest - Changing to LiveTest (#15013) * changing to LiveTest Prevent integration tests from failing after spring boot upgrade. * Update MongoDbHashMapLiveTest.java Including docs. * Update MongoDbHashMapLiveTest.java removing instructions from atlas search. --- ...nTest.java => MongoDbHashMapLiveTest.java} | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) rename persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/hashmap/{MongoDbHashMapIntegrationTest.java => MongoDbHashMapLiveTest.java} (76%) diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/hashmap/MongoDbHashMapIntegrationTest.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/hashmap/MongoDbHashMapLiveTest.java similarity index 76% rename from persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/hashmap/MongoDbHashMapIntegrationTest.java rename to persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/hashmap/MongoDbHashMapLiveTest.java index bbf425f277..29588df8a9 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/hashmap/MongoDbHashMapIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/hashmap/MongoDbHashMapLiveTest.java @@ -13,21 +13,35 @@ import java.util.Map; import java.util.Set; import org.bson.Document; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; import com.mongodb.BasicDBObject; -@SpringBootTest +/** + * Steps to run locally: + * - Open embedded.properties and include: + * - spring.data.mongodb.uri= + * - spring.data.mongodb.database=sample_mflix + * + * Pre-requisites: + * - Following the steps to import the sample_mflix database + */ @DirtiesContext +@RunWith(SpringRunner.class) @TestPropertySource("/embedded.properties") -class MongoDbHashMapIntegrationTest { +@SpringBootTest(classes = SpringBootHashMapApplication.class) +class MongoDbHashMapLiveTest { + private static final String COLLECTION_NAME = "hashmap-test-collection"; private static final Map MAP = new HashMap<>(); private static final Set> MAP_SET = new HashSet<>(); @@ -52,17 +66,22 @@ class MongoDbHashMapIntegrationTest { MAP_SET.add(MAP); MAP_SET.add(otherMap); } + + @AfterEach + void destroy() { + mongo.dropCollection(COLLECTION_NAME); + } @Test void whenUsingMap_thenInsertSucceeds() { - Map saved = mongo.insert(MAP, "map-collection"); + Map saved = mongo.insert(MAP, COLLECTION_NAME); assertHasMongoId(saved); } @Test void whenMapSet_thenInsertSucceeds() { - Collection> saved = mongo.insert(MAP_SET, "map-set"); + Collection> saved = mongo.insert(MAP_SET, COLLECTION_NAME); saved.forEach(this::assertHasMongoId); assertEquals(2, saved.size()); @@ -72,7 +91,7 @@ class MongoDbHashMapIntegrationTest { void givenMap_whenDocumentConstructed_thenInsertSucceeds() { Document document = new Document(MAP); - Document saved = mongo.insert(document, "doc-collection"); + Document saved = mongo.insert(document, COLLECTION_NAME); assertHasMongoId(saved); } @@ -81,7 +100,7 @@ class MongoDbHashMapIntegrationTest { void givenMap_whenBasicDbObjectConstructed_thenInsertSucceeds() { BasicDBObject dbObject = new BasicDBObject(MAP); - BasicDBObject saved = mongo.insert(dbObject, "db-collection"); + BasicDBObject saved = mongo.insert(dbObject, COLLECTION_NAME); assertHasMongoId(saved); } @@ -114,7 +133,7 @@ class MongoDbHashMapIntegrationTest { set.add(document); }, Set::addAll); - Collection saved = mongo.insert(docs, "custom-set"); + Collection saved = mongo.insert(docs, COLLECTION_NAME); saved.forEach(this::assertHasMongoId); } } From ac0fa6ff7883a610297aa7eb5561536a5e0e079f Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 10 Nov 2023 18:46:51 +0800 Subject: [PATCH 147/233] Update README.md [skip ci] --- core-java-modules/core-java-date-operations-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-date-operations-3/README.md b/core-java-modules/core-java-date-operations-3/README.md index 9d16d1f71c..48b68189fa 100644 --- a/core-java-modules/core-java-date-operations-3/README.md +++ b/core-java-modules/core-java-date-operations-3/README.md @@ -11,4 +11,5 @@ This module contains articles about date operations in Java. - [Getting Yesterday’s Date in Java](https://www.baeldung.com/java-find-yesterdays-date) - [How to Get the Start and End Dates of a Year Using Java](https://www.baeldung.com/java-date-year-start-end) - [Convert Between Java LocalDate and Epoch](https://www.baeldung.com/java-localdate-epoch) +- [Get First Date of Current Month in Java](https://www.baeldung.com/java-current-month-start-date) - [[<-- Prev]](/core-java-modules/core-java-date-operations-2) From 732c2255b294a38182581f016c31d524fa43f8eb Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 10 Nov 2023 19:22:40 +0800 Subject: [PATCH 148/233] Update README.md [skip ci] --- spring-boot-modules/spring-boot-mvc/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index f45feb6169..9257d6eba1 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -10,4 +10,5 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) - [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) +- [Localized Validation Messages in REST](https://www.baeldung.com/rest-localized-validation-messages) - More articles: [[next -->]](/spring-boot-modules/spring-boot-mvc-2) From 77c7186351207bedb51336cce9d47cb06a93c693 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 10 Nov 2023 19:27:58 +0800 Subject: [PATCH 149/233] Update README.md [skip ci] --- spring-boot-modules/spring-boot-3-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-3-2/README.md b/spring-boot-modules/spring-boot-3-2/README.md index c176de2310..27f9281725 100644 --- a/spring-boot-modules/spring-boot-3-2/README.md +++ b/spring-boot-modules/spring-boot-3-2/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Spring Boot 3.1’s ConnectionDetails Abstraction](https://www.baeldung.com/spring-boot-3-1-connectiondetails-abstraction) +- [@ConditionalOnThreading Annotation Spring](https://www.baeldung.com/spring-conditionalonthreading) From a2ad229e4e901972a6b8d7ca0b94b9f1837c4b3c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 10 Nov 2023 19:37:26 +0800 Subject: [PATCH 150/233] Update README.md [skip ci] --- core-java-modules/core-java-collections-maps-7/README.md | 1 + 1 file changed, 1 insertion(+) 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 5599187cd8..84cc94ad3c 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -1,3 +1,4 @@ ## Relevant Articles - [Difference Between putIfAbsent() and computeIfAbsent() in Java’s Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent) - [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) From 9109481ecbcfcb4afc6b970debb02d3d2b5dbc9f Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Fri, 10 Nov 2023 11:51:11 +0000 Subject: [PATCH 151/233] =?UTF-8?q?[JAVA-26045]=20Upgraded=20spring-boot-t?= =?UTF-8?q?esting=20module=20to=20spring-boot=203=20ver=E2=80=A6=20(#14990?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spring-boot-modules/spring-boot-testing/pom.xml | 13 +++++++++---- .../boot/configurationproperties/MailServer.java | 10 +++++----- .../configuration/RedisProperties.java | 2 +- .../java/com/baeldung/boot/testing/Employee.java | 12 ++++++------ .../src/main/resources/application.properties | 4 ++-- .../exclude/ExcludeAutoConfig1IntegrationTest.java | 2 +- .../exclude/ExcludeAutoConfig2IntegrationTest.java | 2 +- .../exclude/ExcludeAutoConfig3IntegrationTest.java | 2 +- .../exclude/ExcludeAutoConfig4IntegrationTest.java | 2 +- .../boot/autoconfig/AutoConfigIntegrationTest.java | 2 +- .../PropertyValidationUnitTest.java | 4 ++-- .../boot/embeddedRedis/TestRedisConfiguration.java | 4 ++-- .../src/test/resources/application.properties | 4 ++-- 13 files changed, 34 insertions(+), 29 deletions(-) diff --git a/spring-boot-modules/spring-boot-testing/pom.xml b/spring-boot-modules/spring-boot-testing/pom.xml index 257260fc3f..23277d11f3 100644 --- a/spring-boot-modules/spring-boot-testing/pom.xml +++ b/spring-boot-modules/spring-boot-testing/pom.xml @@ -9,9 +9,10 @@ This is simple boot application for demonstrating testing features. - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -67,6 +68,11 @@ ${embedded-redis.version} test + + io.rest-assured + rest-assured + test + @@ -122,7 +128,6 @@ 2.4-M1-groovy-4.0 3.0.0 0.7.2 - 2.5.0 2.17.1 diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java index e23b30759b..3f5ea64d24 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java @@ -2,11 +2,11 @@ package com.baeldung.boot.configurationproperties; import java.util.Map; -import javax.validation.Valid; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotEmpty; -import javax.validation.constraints.NotNull; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java index 76f2e1bbfe..4e06548d79 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java @@ -8,7 +8,7 @@ public class RedisProperties { private final int redisPort; private final String redisHost; - public RedisProperties(@Value("${spring.redis.port}") final int redisPort, @Value("${spring.redis.host}") final String redisHost) { + public RedisProperties(@Value("${spring.data.redis.port}") final int redisPort, @Value("${spring.data.redis.host}") final String redisHost) { this.redisPort = redisPort; this.redisHost = redisHost; } diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java index 2921ecc609..cf68c45793 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java @@ -1,11 +1,11 @@ package com.baeldung.boot.testing; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.validation.constraints.Size; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.Size; import java.util.Date; @Entity diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties index 70cae370a4..e3fe989efd 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties @@ -1,6 +1,6 @@ # embedded redis -spring.redis.host= localhost -spring.redis.port= 6379 +spring.data.redis.host= localhost +spring.data.redis.port= 6379 # security spring.security.user.name=john diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java index 2ca0c74901..a8a322df44 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java index c0bd6570a1..6a9e157827 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java index 1642d4b932..9d4d9759d6 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java index 1aa453348b..f28929fbef 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java index 44a02c0c80..447d174fb5 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java index 939471dd67..5e70bcb45f 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java @@ -2,8 +2,8 @@ package com.baeldung.boot.configurationproperties; import static org.junit.jupiter.api.Assertions.assertEquals; -import javax.validation.Validation; -import javax.validation.Validator; +import jakarta.validation.Validation; +import jakarta.validation.Validator; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java index c265d99c9b..10e5d56857 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java @@ -4,8 +4,8 @@ import com.baeldung.boot.embeddedRedis.configuration.RedisProperties; import org.springframework.boot.test.context.TestConfiguration; import redis.embedded.RedisServer; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; @TestConfiguration public class TestRedisConfiguration { diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties index 1810c7b1eb..bc31991329 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties +++ b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties @@ -1,6 +1,6 @@ #embedded redis -spring.redis.host= localhost -spring.redis.port= 6370 +spring.data.redis.host= localhost +spring.data.redis.port= 6370 # security spring.security.user.name=john spring.security.user.password=123 From 277001771c776c3f5c97d421339edf127ae4383e Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 10 Nov 2023 21:06:56 +0800 Subject: [PATCH 152/233] Update README.md [skip ci] --- core-java-modules/core-java-jndi/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-jndi/README.md b/core-java-modules/core-java-jndi/README.md index 9c6f489841..cdb1b34ca9 100644 --- a/core-java-modules/core-java-jndi/README.md +++ b/core-java-modules/core-java-jndi/README.md @@ -4,3 +4,4 @@ - [Java Naming and Directory Interface Overview](https://www.baeldung.com/jndi) - [LDAP Authentication Using Pure Java](https://www.baeldung.com/java-ldap-auth) - [Testing LDAP Connections With Java](https://www.baeldung.com/java-test-ldap-connections) +- [JNDI – What Is java:comp/env?](https://www.baeldung.com/java-jndi-comp-env) From c7883a6d5cd680bcc39cb23cfc924bb23a7ad03e Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 10 Nov 2023 21:10:20 +0800 Subject: [PATCH 153/233] Update README.md [skip ci] --- core-java-modules/core-java-documentation/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-documentation/README.md b/core-java-modules/core-java-documentation/README.md index 972e76c165..9fa48dc09e 100644 --- a/core-java-modules/core-java-documentation/README.md +++ b/core-java-modules/core-java-documentation/README.md @@ -4,3 +4,4 @@ - [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [Code Snippets in Java API Documentation](https://www.baeldung.com/java-doc-code-snippets) +- [How to Document Generic Type Parameters in Javadoc](https://www.baeldung.com/java-javadoc-generic-type-parameters) From 2e330d6f34016e25e451e97df3cc190a6c52e565 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 10 Nov 2023 21:12:41 +0800 Subject: [PATCH 154/233] Update README.md [skip ci] --- core-java-modules/core-java-records/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-records/README.md b/core-java-modules/core-java-records/README.md index 86d3579c76..7b4df6f15c 100644 --- a/core-java-modules/core-java-records/README.md +++ b/core-java-modules/core-java-records/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Overriding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records) +- [Optional as a Record Parameter in Java](https://www.baeldung.com/java-record-optional-param) From 4c87707c9057af9dc58a4443065a245c743c44e6 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 10 Nov 2023 21:16:16 +0800 Subject: [PATCH 155/233] Update README.md [skip ci] --- core-java-modules/core-java-string-operations-7/README.md | 1 + 1 file changed, 1 insertion(+) 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 6c4fab384b..28e2dccd39 100644 --- a/core-java-modules/core-java-string-operations-7/README.md +++ b/core-java-modules/core-java-string-operations-7/README.md @@ -2,3 +2,4 @@ ### Relevant Articles: - [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output) - [Capitalize the First Letter of Each Word in a String](https://www.baeldung.com/java-string-initial-capital-letter-every-word) +- [Check if a String Contains Only Unicode Letters](https://www.baeldung.com/java-string-all-unicode-characters) From 47c755435251a26f72cdf64ed8d04b5c84aa3954 Mon Sep 17 00:00:00 2001 From: luca Date: Fri, 10 Nov 2023 14:30:22 +0100 Subject: [PATCH 156/233] feat: override spring bean --- .../com/baeldung/overridebean/Endpoint.java | 19 ++++++++++ .../com/baeldung/overridebean/Service.java | 5 +++ .../baeldung/overridebean/ServiceImpl.java | 8 ++++ .../overridebean/basic/Application.java | 14 +++++++ .../baeldung/overridebean/basic/Config.java | 16 ++++++++ .../overridebean/conditional/Application.java | 14 +++++++ .../conditional/ConditionalConfig.java | 18 +++++++++ .../overridebean/profile/Application.java | 14 +++++++ .../overridebean/profile/ProfileConfig.java | 18 +++++++++ .../src/main/resources/application.properties | 1 + .../conditional/ConditionIntegrationTest.java | 29 +++++++++++++++ .../conditional/ConditionalStub.java | 10 +++++ .../conditional/ConditionalTestConfig.java | 17 +++++++++ .../mockbean/MockBeanIntegrationTest.java | 37 +++++++++++++++++++ ...OverrideBeanDefinitionIntegrationTest.java | 31 ++++++++++++++++ .../OverrideBeanDefinitionServiceStub.java | 10 +++++ .../OverrideBeanDefinitionTestConfig.java | 15 ++++++++ .../primary/PrimaryIntegrationTest.java | 31 ++++++++++++++++ .../primary/PrimaryServiceStub.java | 10 +++++ .../primary/PrimaryTestConfig.java | 17 +++++++++ .../profile/ProfileIntegrationTest.java | 29 +++++++++++++++ .../profile/ProfileServiceStub.java | 10 +++++ .../profile/ProfileTestConfig.java | 15 ++++++++ 23 files changed, 388 insertions(+) create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Endpoint.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Service.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/ServiceImpl.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Application.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Config.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/Application.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/ConditionalConfig.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/Application.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/ProfileConfig.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalStub.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalTestConfig.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionServiceStub.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionTestConfig.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryServiceStub.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryTestConfig.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileServiceStub.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileTestConfig.java diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Endpoint.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Endpoint.java new file mode 100644 index 0000000000..e199d1f25b --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Endpoint.java @@ -0,0 +1,19 @@ +package com.baeldung.overridebean; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class Endpoint { + + private final Service service; + + public Endpoint(Service service) { + this.service = service; + } + + @GetMapping("/hello") + public String helloWorldEndpoint() { + return service.helloWorld(); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Service.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Service.java new file mode 100644 index 0000000000..0872fcc372 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Service.java @@ -0,0 +1,5 @@ +package com.baeldung.overridebean; + +public interface Service { + String helloWorld(); +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/ServiceImpl.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/ServiceImpl.java new file mode 100644 index 0000000000..4d4b5582e6 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/ServiceImpl.java @@ -0,0 +1,8 @@ +package com.baeldung.overridebean; + +public class ServiceImpl implements Service { + + public String helloWorld() { + return "hello world"; + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Application.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Application.java new file mode 100644 index 0000000000..6f9acde3d8 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Application.java @@ -0,0 +1,14 @@ +package com.baeldung.overridebean.basic; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class }) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Config.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Config.java new file mode 100644 index 0000000000..67d999958d --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Config.java @@ -0,0 +1,16 @@ +package com.baeldung.overridebean.basic; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.overridebean.Service; +import com.baeldung.overridebean.ServiceImpl; + +@Configuration +public class Config { + + @Bean + public Service helloWorld() { + return new ServiceImpl(); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/Application.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/Application.java new file mode 100644 index 0000000000..9c4cdbf8ec --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/Application.java @@ -0,0 +1,14 @@ +package com.baeldung.overridebean.conditional; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class }) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/ConditionalConfig.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/ConditionalConfig.java new file mode 100644 index 0000000000..e18689e042 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/ConditionalConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.overridebean.conditional; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.overridebean.Service; +import com.baeldung.overridebean.ServiceImpl; + +@Configuration +public class ConditionalConfig { + + @Bean + @ConditionalOnProperty(name = "service.stub", havingValue = "false") + public Service helloWorld() { + return new ServiceImpl(); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/Application.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/Application.java new file mode 100644 index 0000000000..d3298b2eb4 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/Application.java @@ -0,0 +1,14 @@ +package com.baeldung.overridebean.profile; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class }) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/ProfileConfig.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/ProfileConfig.java new file mode 100644 index 0000000000..64cdfff8a5 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/ProfileConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.overridebean.profile; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import com.baeldung.overridebean.Service; +import com.baeldung.overridebean.ServiceImpl; + +@Configuration +@Profile("prod") +public class ProfileConfig { + + @Bean + public Service helloWorld() { + return new ServiceImpl(); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-testing-2/src/main/resources/application.properties index b628a708bd..0982b7bac0 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-testing-2/src/main/resources/application.properties @@ -1,2 +1,3 @@ keycloak.enabled=true spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8180/auth/realms/baeldung-api +service.stub=false \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionIntegrationTest.java new file mode 100644 index 0000000000..5f6b1d128f --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionIntegrationTest.java @@ -0,0 +1,29 @@ +package com.baeldung.overridebean.conditional; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.overridebean.Endpoint; + +@SpringBootTest(classes = { Application.class, ConditionalConfig.class, Endpoint.class, ConditionalTestConfig.class }, properties = "service.stub=true") +@AutoConfigureMockMvc +class ConditionIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + void givenConditionalConfig_whenServiceStubIsTrue_thenStubOk() throws Exception { + this.mockMvc.perform(get("/hello")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("hello conditional stub"))); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalStub.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalStub.java new file mode 100644 index 0000000000..6b3e447108 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalStub.java @@ -0,0 +1,10 @@ +package com.baeldung.overridebean.conditional; + +import com.baeldung.overridebean.Service; + +public class ConditionalStub implements Service { + + public String helloWorld() { + return "hello conditional stub"; + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalTestConfig.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalTestConfig.java new file mode 100644 index 0000000000..c48c4e2266 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalTestConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.overridebean.conditional; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; + +import com.baeldung.overridebean.Service; + +@TestConfiguration +public class ConditionalTestConfig { + + @ConditionalOnProperty(name = "service.stub", havingValue = "true") + @Bean + public Service helloWorld() { + return new ConditionalStub(); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java new file mode 100644 index 0000000000..6a7be1cbda --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java @@ -0,0 +1,37 @@ +package com.baeldung.overridebean.mockbean; + +import static org.hamcrest.Matchers.containsString; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +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.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.overridebean.Endpoint; +import com.baeldung.overridebean.Service; +import com.baeldung.overridebean.basic.Application; + +@SpringBootTest(classes = { Application.class, Endpoint.class }) +@AutoConfigureMockMvc +class MockBeanIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private Service serviceExample; + + @Test + void givenServiceMockBean_whenGetHelloEndpoint_thenMockOk() throws Exception { + when(serviceExample.helloWorld()).thenReturn("hello mock bean"); + this.mockMvc.perform(get("/hello")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("hello mock bean"))); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionIntegrationTest.java new file mode 100644 index 0000000000..0f3753ef34 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.overridebean.overridebeandefinition; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.overridebean.Endpoint; +import com.baeldung.overridebean.basic.Application; +import com.baeldung.overridebean.basic.Config; + +@SpringBootTest(classes = { Application.class, Config.class, Endpoint.class, OverrideBeanDefinitionTestConfig.class }, properties = "spring.main.allow-bean-definition-overriding=true") +@AutoConfigureMockMvc +class OverrideBeanDefinitionIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + void givenNoProfile_whenAllowBeanDefinitionOverriding_thenStubOk() throws Exception { + this.mockMvc.perform(get("/hello")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("hello no profile stub"))); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionServiceStub.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionServiceStub.java new file mode 100644 index 0000000000..d06b43cf24 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionServiceStub.java @@ -0,0 +1,10 @@ +package com.baeldung.overridebean.overridebeandefinition; + +import com.baeldung.overridebean.Service; + +public class OverrideBeanDefinitionServiceStub implements Service { + + public String helloWorld() { + return "hello no profile stub"; + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionTestConfig.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionTestConfig.java new file mode 100644 index 0000000000..5c35304296 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionTestConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.overridebean.overridebeandefinition; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; + +import com.baeldung.overridebean.Service; + +@TestConfiguration +public class OverrideBeanDefinitionTestConfig { + + @Bean + public Service helloWorld() { + return new OverrideBeanDefinitionServiceStub(); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryIntegrationTest.java new file mode 100644 index 0000000000..2bddfd4637 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.overridebean.primary; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.overridebean.Endpoint; +import com.baeldung.overridebean.basic.Application; +import com.baeldung.overridebean.basic.Config; + +@SpringBootTest(classes = { Application.class, Config.class, Endpoint.class, PrimaryTestConfig.class }) +@AutoConfigureMockMvc +class PrimaryIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + void givenTestConfiguration_whenPrimaryBeanIsDefined_thenStubOk() throws Exception { + this.mockMvc.perform(get("/hello")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("hello primary stub"))); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryServiceStub.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryServiceStub.java new file mode 100644 index 0000000000..1d3d887f99 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryServiceStub.java @@ -0,0 +1,10 @@ +package com.baeldung.overridebean.primary; + +import com.baeldung.overridebean.Service; + +public class PrimaryServiceStub implements Service { + + public String helloWorld() { + return "hello primary stub"; + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryTestConfig.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryTestConfig.java new file mode 100644 index 0000000000..3765377b41 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryTestConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.overridebean.primary; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; + +import com.baeldung.overridebean.Service; + +@TestConfiguration +public class PrimaryTestConfig { + + @Primary + @Bean("service.stub") + public Service helloWorld() { + return new PrimaryServiceStub(); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java new file mode 100644 index 0000000000..deabfea9e5 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java @@ -0,0 +1,29 @@ +package com.baeldung.overridebean.profile; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.overridebean.Endpoint; + +@SpringBootTest(classes = { Application.class, ProfileConfig.class, Endpoint.class, ProfileTestConfig.class }) +@AutoConfigureMockMvc +class ProfileIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + void givenConfigurationWithProfile_whenNoProductionProfileIsActive_thenStubOk() throws Exception { + this.mockMvc.perform(get("/hello")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("hello profile stub"))); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileServiceStub.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileServiceStub.java new file mode 100644 index 0000000000..ef1f2e7a22 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileServiceStub.java @@ -0,0 +1,10 @@ +package com.baeldung.overridebean.profile; + +import com.baeldung.overridebean.Service; + +public class ProfileServiceStub implements Service { + + public String helloWorld() { + return "hello profile stub"; + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileTestConfig.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileTestConfig.java new file mode 100644 index 0000000000..edd33162e0 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileTestConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.overridebean.profile; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; + +import com.baeldung.overridebean.Service; + +@TestConfiguration +public class ProfileTestConfig { + + @Bean + public Service helloWorld() { + return new ProfileServiceStub(); + } +} From 1e13611b4de219f646c491eeb382e5a04bfac856 Mon Sep 17 00:00:00 2001 From: luca Date: Fri, 10 Nov 2023 15:09:18 +0100 Subject: [PATCH 157/233] Trigger Jenkins From 7c1065b494a05299addb9f0ada8fdba786ac91e4 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Fri, 10 Nov 2023 14:15:28 +0000 Subject: [PATCH 158/233] [JAVA-26439] Moved code related to "Guide to Stream.reduce()" to ebook module (#15170) --- .../streamreduce/application/Application.java | 62 ------------------- .../streamreduce/entities/Rating.java | 39 ------------ .../streamreduce/entities/Review.java | 28 --------- .../baeldung/streamreduce/entities/User.java | 30 --------- .../streamreduce/utilities/NumberUtils.java | 52 ---------------- .../streams/reduce/entities/User.java | 7 ++- .../reduce}/StreamReduceManualTest.java | 15 +++-- 7 files changed, 15 insertions(+), 218 deletions(-) delete mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java delete mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/Rating.java delete mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/Review.java delete mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java delete mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java rename core-java-modules/{core-java-8/src/test/java/com/baeldung/streamreduce/tests => core-java-streams-simple/src/test/java/com/baeldung/streams/reduce}/StreamReduceManualTest.java (95%) diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java deleted file mode 100644 index 00fc45ccae..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.streamreduce.application; - -import com.baeldung.streamreduce.entities.User; -import com.baeldung.streamreduce.utilities.NumberUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class Application { - - public static void main(String[] args) { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result1 = numbers.stream().reduce(0, (a, b) -> a + b); - System.out.println(result1); - - int result2 = numbers.stream().reduce(0, Integer::sum); - System.out.println(result2); - - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result3 = letters.stream().reduce("", (a, b) -> a + b); - System.out.println(result3); - - String result4 = letters.stream().reduce("", String::concat); - System.out.println(result4); - - String result5 = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase()); - System.out.println(result5); - - List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); - int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result6); - - String result7 = letters.parallelStream().reduce("", String::concat); - System.out.println(result7); - - int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result8); - - List userList = new ArrayList<>(); - for (int i = 0; i <= 1000000; i++) { - userList.add(new User("John" + i, i)); - } - - long t1 = System.currentTimeMillis(); - int result9 = userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - long t2 = System.currentTimeMillis(); - System.out.println(result9); - System.out.println("Sequential stream time: " + (t2 - t1) + "ms"); - - long t3 = System.currentTimeMillis(); - int result10 = userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - long t4 = System.currentTimeMillis(); - System.out.println(result10); - System.out.println("Parallel stream time: " + (t4 - t3) + "ms"); - - int result11 = NumberUtils.divideListElements(numbers, 1); - System.out.println(result11); - - int result12 = NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0); - System.out.println(result12); - } -} diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/Rating.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/Rating.java deleted file mode 100644 index c4d0276256..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/Rating.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.streamreduce.entities; - -import java.util.ArrayList; -import java.util.List; - -public class Rating { - - double points; - List reviews = new ArrayList<>(); - - public Rating() {} - - public void add(Review review) { - reviews.add(review); - computeRating(); - } - - private double computeRating() { - double totalPoints = reviews.stream().map(Review::getPoints).reduce(0, Integer::sum); - this.points = totalPoints / reviews.size(); - return this.points; - } - - public static Rating average(Rating r1, Rating r2) { - Rating combined = new Rating(); - combined.reviews = new ArrayList<>(r1.reviews); - combined.reviews.addAll(r2.reviews); - combined.computeRating(); - return combined; - } - - public double getPoints() { - return points; - } - - public List getReviews() { - return reviews; - } -} diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/Review.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/Review.java deleted file mode 100644 index 03cde8a9c8..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/Review.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.streamreduce.entities; - -public class Review { - - int points; - String review; - - public Review(int points, String review) { - this.points = points; - this.review = review; - } - - public int getPoints() { - return points; - } - - public void setPoints(int points) { - this.points = points; - } - - public String getReview() { - return review; - } - - public void setReview(String review) { - this.review = review; - } -} diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java deleted file mode 100644 index 20c12d7920..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.streamreduce.entities; - -public class User { - - private final String name; - private final int age; - private final Rating rating = new Rating(); - - public User(String name, int age) { - this.name = name; - this.age = age; - } - - public String getName() { - return name; - } - - public int getAge() { - return age; - } - - public Rating getRating() { - return rating; - } - - @Override - public String toString() { - return "User{" + "name=" + name + ", age=" + age + '}'; - } -} diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java deleted file mode 100644 index a2325cc701..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.streamreduce.utilities; - -import java.util.List; -import java.util.function.BiFunction; -import java.util.logging.Level; -import java.util.logging.Logger; - -public abstract class NumberUtils { - - private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); - - public static int divideListElements(List values, Integer divider) { - return values.stream() - .reduce(0, (a, b) -> { - try { - return a / divider + b / divider; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return 0; - }); - } - - public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { - return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); - } - - public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { - BiFunction division = (a, b) -> a / b; - return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); - } - - private static int divide(int value, int factor) { - int result = 0; - try { - result = value / factor; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return result; - } - - private static int applyFunction(BiFunction function, int a, int b) { - try { - return function.apply(a, b); - } - catch(Exception e) { - LOGGER.log(Level.INFO, "Exception occurred!"); - } - return 0; - } -} diff --git a/core-java-modules/core-java-streams-simple/src/main/java/com/baeldung/streams/reduce/entities/User.java b/core-java-modules/core-java-streams-simple/src/main/java/com/baeldung/streams/reduce/entities/User.java index 610bd93b22..07c627005a 100644 --- a/core-java-modules/core-java-streams-simple/src/main/java/com/baeldung/streams/reduce/entities/User.java +++ b/core-java-modules/core-java-streams-simple/src/main/java/com/baeldung/streams/reduce/entities/User.java @@ -4,6 +4,7 @@ public class User { private final String name; private final int age; + private final Rating rating = new Rating(); public User(String name, int age) { this.name = name; @@ -17,7 +18,11 @@ public class User { public int getAge() { return age; } - + + public Rating getRating() { + return rating; + } + @Override public String toString() { return "User{" + "name=" + name + ", age=" + age + '}'; diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/streamreduce/tests/StreamReduceManualTest.java b/core-java-modules/core-java-streams-simple/src/test/java/com/baeldung/streams/reduce/StreamReduceManualTest.java similarity index 95% rename from core-java-modules/core-java-8/src/test/java/com/baeldung/streamreduce/tests/StreamReduceManualTest.java rename to core-java-modules/core-java-streams-simple/src/test/java/com/baeldung/streams/reduce/StreamReduceManualTest.java index 602bdd069e..2931384c94 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/streamreduce/tests/StreamReduceManualTest.java +++ b/core-java-modules/core-java-streams-simple/src/test/java/com/baeldung/streams/reduce/StreamReduceManualTest.java @@ -1,15 +1,18 @@ -package com.baeldung.streamreduce.tests; +package com.baeldung.streams.reduce; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.streamreduce.entities.Rating; -import com.baeldung.streamreduce.entities.Review; -import com.baeldung.streamreduce.entities.User; -import com.baeldung.streamreduce.utilities.NumberUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; +import com.baeldung.streams.reduce.entities.Rating; +import com.baeldung.streams.reduce.entities.Review; +import com.baeldung.streams.reduce.entities.User; +import com.baeldung.streams.reduce.utilities.NumberUtils; + public class StreamReduceManualTest { @Test From 75828dbf491f828d41ba87e40461e0f566f38d62 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 07:29:30 +0800 Subject: [PATCH 159/233] Update README.md [skip ci] --- core-java-modules/core-java-collections-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-5/README.md b/core-java-modules/core-java-collections-5/README.md index 1939e5ca3f..4869158d2b 100644 --- a/core-java-modules/core-java-collections-5/README.md +++ b/core-java-modules/core-java-collections-5/README.md @@ -8,4 +8,5 @@ - [Difference Between Arrays.sort() and Collections.sort()](https://www.baeldung.com/java-arrays-collections-sort-methods) - [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration) - [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) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-4) From 373a0cc89552d42db973e41bf75166643e360c0b Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 07:33:19 +0800 Subject: [PATCH 160/233] Update README.md [skip ci] --- reactor-core/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/reactor-core/README.md b/reactor-core/README.md index dccf1fa85c..96355ad703 100644 --- a/reactor-core/README.md +++ b/reactor-core/README.md @@ -13,3 +13,4 @@ This module contains articles about Reactor Core. - [Handling Exceptions in Project Reactor](https://www.baeldung.com/reactor-exceptions) - [Difference Between Flux.create and Flux.generate](https://www.baeldung.com/java-flux-create-generate) - [Difference Between Flux and Mono](https://www.baeldung.com/java-reactor-flux-vs-mono) +- [Working With MathFlux](https://www.baeldung.com/java-reactor-mathflux) From bb31624bb418edc1de9b99e67e25466d09a2b5f9 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 07:43:24 +0800 Subject: [PATCH 161/233] Update README.md [skip ci] --- core-java-modules/core-java-collections-maps-7/README.md | 1 + 1 file changed, 1 insertion(+) 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 84cc94ad3c..2e1531050e 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -2,3 +2,4 @@ - [Difference Between putIfAbsent() and computeIfAbsent() in Java’s Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent) - [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) From 2c26effb6418f05b56dab0fc8c4a3d08714f2ea0 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 07:49:53 +0800 Subject: [PATCH 162/233] Update README.md [skip ci] --- core-java-modules/core-java-8-datetime-2/README.md | 1 + 1 file changed, 1 insertion(+) 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 ac1e1ca81f..462a4be6f1 100644 --- a/core-java-modules/core-java-8-datetime-2/README.md +++ b/core-java-modules/core-java-8-datetime-2/README.md @@ -6,4 +6,5 @@ - [How Many Days Are There in a Particular Month of a Given Year?](https://www.baeldung.com/days-particular-month-given-year) - [Difference Between Instant and LocalDateTime](https://www.baeldung.com/java-instant-vs-localdatetime) - [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) - [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1) From d6638d328fd53d2ea1caddf767adbe461bf89416 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 07:57:45 +0800 Subject: [PATCH 163/233] Update README.md [skip ci] --- jersey/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jersey/README.md b/jersey/README.md index aa5a6a3b28..24e39f02a2 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -12,3 +12,4 @@ This module contains articles about Jersey. - [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers) - [Exception Handling With Jersey](https://www.baeldung.com/java-exception-handling-jersey) - [@FormDataParam vs. @FormParam in Jersey](https://www.baeldung.com/jersey-formdataparam-vs-formparam) +- [Add a List as Query Parameter in Jersey](https://www.baeldung.com/java-jersey-list-query-param) From 4e5f7adc81c748340b02d24f351b24fb15284b9f Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 08:10:55 +0800 Subject: [PATCH 164/233] Update README.md [skip ci] --- core-java-modules/core-java-string-apis-2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-apis-2/README.md b/core-java-modules/core-java-string-apis-2/README.md index 38bfb70ef1..57106b7151 100644 --- a/core-java-modules/core-java-string-apis-2/README.md +++ b/core-java-modules/core-java-string-apis-2/README.md @@ -6,4 +6,5 @@ This module contains articles about string APIs. - [Retain Only Digits and Decimal Separator in String](https://www.baeldung.com/java-string-retain-digits-decimal) - [Difference Between null and Empty String in Java](https://www.baeldung.com/java-string-null-vs-empty) - [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) -- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) \ No newline at end of file +- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) +- [Compare StringBuilder Objects in Java](https://www.baeldung.com/java-stringbuilder-objects-comparison) From 3d8d1ad9044b88604fbb961290816ec675ce588d Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 08:16:39 +0800 Subject: [PATCH 165/233] Update README.md [skip ci] --- core-java-modules/core-java-streams-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-5/README.md b/core-java-modules/core-java-streams-5/README.md index 629d52f0a9..82a13a1eb6 100644 --- a/core-java-modules/core-java-streams-5/README.md +++ b/core-java-modules/core-java-streams-5/README.md @@ -5,3 +5,4 @@ - [Streams vs. Loops in Java](https://www.baeldung.com/java-streams-vs-loops) - [Partition a Stream in Java](https://www.baeldung.com/java-partition-stream) - [Taking Every N-th Element from Finite and Infinite Streams in Java](https://www.baeldung.com/java-nth-element-finite-infinite-streams) +- [Modifying Objects Within Stream While Iterating](https://www.baeldung.com/java-stream-modify-objects-during-iteration) From c523d5b2019d1b7116c2182ff52da50c7825c486 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 08:21:22 +0800 Subject: [PATCH 166/233] Update README.md [skip ci] --- core-java-modules/core-java-streams-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-5/README.md b/core-java-modules/core-java-streams-5/README.md index 82a13a1eb6..64bc4e6b7a 100644 --- a/core-java-modules/core-java-streams-5/README.md +++ b/core-java-modules/core-java-streams-5/README.md @@ -6,3 +6,4 @@ - [Partition a Stream in Java](https://www.baeldung.com/java-partition-stream) - [Taking Every N-th Element from Finite and Infinite Streams in Java](https://www.baeldung.com/java-nth-element-finite-infinite-streams) - [Modifying Objects Within Stream While Iterating](https://www.baeldung.com/java-stream-modify-objects-during-iteration) +- [Convert a Stream into a Map or Multimap in Java](https://www.baeldung.com/java-convert-stream-map-multimap) From 12fa2a39612a2c840d6262190e6e29767775ed2a Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 08:27:08 +0800 Subject: [PATCH 167/233] Update README.md [skip ci] --- core-java-modules/core-java-date-operations-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-date-operations-3/README.md b/core-java-modules/core-java-date-operations-3/README.md index 48b68189fa..d8c321deab 100644 --- a/core-java-modules/core-java-date-operations-3/README.md +++ b/core-java-modules/core-java-date-operations-3/README.md @@ -12,4 +12,5 @@ This module contains articles about date operations in Java. - [How to Get the Start and End Dates of a Year Using Java](https://www.baeldung.com/java-date-year-start-end) - [Convert Between Java LocalDate and Epoch](https://www.baeldung.com/java-localdate-epoch) - [Get First Date of Current Month in Java](https://www.baeldung.com/java-current-month-start-date) +- [Time Conversions Using TimeUnit](https://www.baeldung.com/java-timeunit-conversion) - [[<-- Prev]](/core-java-modules/core-java-date-operations-2) From a6bed1817696343168204da250d308b200be4279 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sat, 11 Nov 2023 08:31:26 +0800 Subject: [PATCH 168/233] Update README.md [skip ci] --- core-java-modules/core-java-string-apis-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-apis-2/README.md b/core-java-modules/core-java-string-apis-2/README.md index 57106b7151..c0b313d3b3 100644 --- a/core-java-modules/core-java-string-apis-2/README.md +++ b/core-java-modules/core-java-string-apis-2/README.md @@ -8,3 +8,4 @@ This module contains articles about string APIs. - [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) - [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) - [Compare StringBuilder Objects in Java](https://www.baeldung.com/java-stringbuilder-objects-comparison) +- [Finding the N-th Occurrence of a Substring in a String in Java](https://www.baeldung.com/java-locate-nth-match-substring) From 87018d44aedd2f215c1598aec8c782c01d38adbb Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 11 Nov 2023 06:55:11 +0200 Subject: [PATCH 169/233] [JAVA-26715] Upgraded pdfbox to latest version --- pdf-2/pom.xml | 2 +- .../pdfinfo/PdfInfoITextUnitTest.java | 22 ++++++++++--------- .../pdfinfo/PdfInfoPdfBoxUnitTest.java | 22 ++++++++++--------- pdf/pom.xml | 2 +- 4 files changed, 26 insertions(+), 22 deletions(-) diff --git a/pdf-2/pom.xml b/pdf-2/pom.xml index ccbb5c9693..2079ff70e5 100644 --- a/pdf-2/pom.xml +++ b/pdf-2/pom.xml @@ -51,7 +51,7 @@ 5.5.13.3 7.2.3 3.0.1 - 3.0.0-RC1 + 3.0.0 \ No newline at end of file diff --git a/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoITextUnitTest.java b/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoITextUnitTest.java index 422858d659..f54405a533 100644 --- a/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoITextUnitTest.java +++ b/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoITextUnitTest.java @@ -1,29 +1,31 @@ package com.baeldung.pdfinfo; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.io.IOException; import java.util.Map; -public class PdfInfoITextUnitTest { +import org.junit.jupiter.api.Test; + +class PdfInfoITextUnitTest { private static final String PDF_FILE = "src/test/resources/input.pdf"; @Test - public void givenPdf_whenGetNumberOfPages_thenOK() throws IOException { - Assert.assertEquals(4, PdfInfoIText.getNumberOfPages(PDF_FILE)); + void givenPdf_whenGetNumberOfPages_thenOK() throws IOException { + assertEquals(4, PdfInfoIText.getNumberOfPages(PDF_FILE)); } @Test - public void givenPdf_whenIsPasswordRequired_thenOK() throws IOException { - Assert.assertFalse(PdfInfoIText.isPasswordRequired(PDF_FILE)); + void givenPdf_whenIsPasswordRequired_thenOK() throws IOException { + assertFalse(PdfInfoIText.isPasswordRequired(PDF_FILE)); } @Test - public void givenPdf_whenGetInfo_thenOK() throws IOException { + void givenPdf_whenGetInfo_thenOK() throws IOException { Map info = PdfInfoIText.getInfo(PDF_FILE); - Assert.assertEquals("LibreOffice 4.2", info.get("Producer")); - Assert.assertEquals("Writer", info.get("Creator")); + assertEquals("LibreOffice 4.2", info.get("Producer")); + assertEquals("Writer", info.get("Creator")); } } diff --git a/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java b/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java index 0fcbc7ee3c..5c4e5fc30d 100644 --- a/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java +++ b/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java @@ -1,29 +1,31 @@ package com.baeldung.pdfinfo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + import org.apache.pdfbox.pdmodel.PDDocumentInformation; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -public class PdfInfoPdfBoxUnitTest { +class PdfInfoPdfBoxUnitTest { private static final String PDF_FILE = "src/test/resources/input.pdf"; @Test - public void givenPdf_whenGetNumberOfPages_thenOK() throws IOException { - Assert.assertEquals(4, PdfInfoPdfBox.getNumberOfPages(PDF_FILE)); + void givenPdf_whenGetNumberOfPages_thenOK() throws IOException { + assertEquals(4, PdfInfoPdfBox.getNumberOfPages(PDF_FILE)); } @Test - public void givenPdf_whenIsPasswordRequired_thenOK() throws IOException { - Assert.assertFalse(PdfInfoPdfBox.isPasswordRequired(PDF_FILE)); + void givenPdf_whenIsPasswordRequired_thenOK() throws IOException { + assertFalse(PdfInfoPdfBox.isPasswordRequired(PDF_FILE)); } @Test - public void givenPdf_whenGetInfo_thenOK() throws IOException { + void givenPdf_whenGetInfo_thenOK() throws IOException { PDDocumentInformation info = PdfInfoPdfBox.getInfo(PDF_FILE); - Assert.assertEquals("LibreOffice 4.2", info.getProducer()); - Assert.assertEquals("Writer", info.getCreator()); + assertEquals("LibreOffice 4.2", info.getProducer()); + assertEquals("Writer", info.getCreator()); } } diff --git a/pdf/pom.xml b/pdf/pom.xml index cead1b2ded..0fe90b6eb5 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -104,7 +104,7 @@ - 2.0.25 + 3.0.0 2.0.1 5.5.13.3 5.5.10 From 4062f3a1193017941523176517a90b94fcd1f707 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 11 Nov 2023 11:50:24 +0530 Subject: [PATCH 170/233] backlink updated --- spring-5-webflux-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-5-webflux-2/README.md b/spring-5-webflux-2/README.md index 1b01f519a4..a0fafd903e 100644 --- a/spring-5-webflux-2/README.md +++ b/spring-5-webflux-2/README.md @@ -6,4 +6,4 @@ This module contains articles about Spring 5 WebFlux - [Spring Webflux and @Cacheable Annotation](https://www.baeldung.com/spring-webflux-cacheable) - [Comparison Between Mono’s doOnNext() and doOnSuccess()](https://www.baeldung.com/mono-doonnext-doonsuccess) - [How to Access the First Element of a Flux](https://www.baeldung.com/java-flux-first-element) -- [Using zipWhen() with Mono](https://www.baeldung.com/java-mono-zipwhen) +- [Using zipWhen() With Mono](https://www.baeldung.com/java-mono-zipwhen) From 173dd4bac3d78e7897274cd1a8625cad251846ff Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 11 Nov 2023 11:52:02 +0530 Subject: [PATCH 171/233] backlink updated --- persistence-modules/spring-data-jpa-query/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-data-jpa-query/README.md b/persistence-modules/spring-data-jpa-query/README.md index 27443c2026..27e7087592 100644 --- a/persistence-modules/spring-data-jpa-query/README.md +++ b/persistence-modules/spring-data-jpa-query/README.md @@ -5,7 +5,7 @@ This module contains articles about querying data using Spring Data JPA ### Relevant Articles: - [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query) - [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions) -- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) +- [Limiting Query Results With JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) - [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting) - [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) - [JPA Join Types](https://www.baeldung.com/jpa-join-types) From b87609265da2f584dddb8eddfb830650c635655a Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 11 Nov 2023 08:29:09 +0200 Subject: [PATCH 172/233] [JAVA-26709] Upgraded modelmapper to latest version --- .../pom.xml | 2 +- .../modelmapper/UsersListMappingUnitTest.java | 39 +++++++------------ libraries-6/pom.xml | 14 ++++--- parent-java/pom.xml | 2 +- performance-tests/pom.xml | 2 +- .../spring-boot-libraries/pom.xml | 2 +- spring-boot-rest/pom.xml | 2 +- 7 files changed, 28 insertions(+), 35 deletions(-) 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 7b7533fc39..da6b6a564a 100644 --- a/core-java-modules/core-java-collections-conversions-2/pom.xml +++ b/core-java-modules/core-java-collections-conversions-2/pom.xml @@ -44,6 +44,6 @@ 0.10.3 11 - 3.1.1 + 3.2.0 \ No newline at end of file diff --git a/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java index a8a72b12f7..c71f655044 100644 --- a/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java +++ b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/modelmapper/UsersListMappingUnitTest.java @@ -1,8 +1,9 @@ package com.baeldung.modelmapper; import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.modelmapper.ModelMapper; import org.modelmapper.TypeMap; import org.modelmapper.TypeToken; @@ -10,11 +11,10 @@ import org.modelmapper.TypeToken; import java.util.ArrayList; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasProperty; -import static org.junit.Assert.assertThat; - /** * This class has test methods of mapping Integer to Character list, @@ -22,12 +22,12 @@ import static org.junit.Assert.assertThat; * * @author Sasa Milenkovic */ -public class UsersListMappingUnitTest { +class UsersListMappingUnitTest { private ModelMapper modelMapper; private List users; - @Before + @BeforeEach public void init() { modelMapper = new ModelMapper(); @@ -35,18 +35,16 @@ public class UsersListMappingUnitTest { TypeMap typeMap = modelMapper.createTypeMap(UserList.class, UserListDTO.class); typeMap.addMappings(mapper -> mapper.using(new UsersListConverter()) - .map(UserList::getUsers, UserListDTO::setUsernames)); + .map(UserList::getUsers, UserListDTO::setUsernames)); - users = new ArrayList(); + users = new ArrayList<>(); users.add(new User("b100", "user1", "user1@baeldung.com", "111-222", "USER")); users.add(new User("b101", "user2", "user2@baeldung.com", "111-333", "USER")); users.add(new User("b102", "user3", "user3@baeldung.com", "111-444", "ADMIN")); - } @Test - public void whenInteger_thenMapToCharacter() { - + void whenInteger_thenMapToCharacter() { List integers = new ArrayList(); integers.add(1); @@ -57,36 +55,27 @@ public class UsersListMappingUnitTest { }.getType()); assertThat(characters, hasItems('1', '2', '3')); - } @Test - public void givenUsersList_whenUseGenericType_thenMapToUserDTO() { - + void givenUsersList_whenUseGenericType_thenMapToUserDTO() { // Mapping lists using custom (generic) type mapping - List userDtoList = MapperUtil.mapList(users, UserDTO.class); - assertThat(userDtoList, Matchers.hasItem( - Matchers.both(hasProperty("userId", equalTo("b100"))) - .and(hasProperty("email", equalTo("user1@baeldung.com"))) - .and(hasProperty("username", equalTo("user1"))))); - - + assertThat(userDtoList, Matchers. hasItem(Matchers.both(hasProperty("userId", equalTo("b100"))) + .and(hasProperty("email", equalTo("user1@baeldung.com"))) + .and(hasProperty("username", equalTo("user1"))))); } @Test - public void givenUsersList_whenUseConverter_thenMapToUsernames() { - + void givenUsersList_whenUseConverter_thenMapToUsernames() { // Mapping lists using property mapping and converter - UserList userList = new UserList(); userList.setUsers(users); UserListDTO dtos = new UserListDTO(); modelMapper.map(userList, dtos); assertThat(dtos.getUsernames(), hasItems("user1", "user2", "user3")); - } } \ No newline at end of file diff --git a/libraries-6/pom.xml b/libraries-6/pom.xml index 139edab34f..9fa44d3a32 100644 --- a/libraries-6/pom.xml +++ b/libraries-6/pom.xml @@ -108,7 +108,7 @@ org.agrona agrona - 1.17.1 + ${agrona.version} @@ -126,7 +126,7 @@ org.codehaus.mojo exec-maven-plugin - 1.6.0 + ${exec-maven-plugin.version} generate-sources @@ -154,14 +154,14 @@ uk.co.real-logic sbe-tool - 1.27.0 + ${sbe-tool.version} org.codehaus.mojo build-helper-maven-plugin - 3.0.0 + ${build-helper-maven-plugin.version} add-source @@ -204,7 +204,11 @@ 3.0 1.8.1 8.12.9 - 2.4.4 + 3.2.0 + 1.17.1 + 1.6.0 + 1.27.0 + 3.0.0 \ No newline at end of file diff --git a/parent-java/pom.xml b/parent-java/pom.xml index b08925e040..03cafac55b 100644 --- a/parent-java/pom.xml +++ b/parent-java/pom.xml @@ -40,7 +40,7 @@ - 2.3.7 + 3.2.0 \ No newline at end of file diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index 542a505b16..9f57a1a90c 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -152,7 +152,7 @@ 1.5.4 6.5.2 1.5.2.Final - 3.1.0 + 3.2.0 1.6.1.CR2 1.8 diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index b7b8ad17ad..ed9a414a60 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -219,7 +219,7 @@ 5.0.2 5.2.4 2.2.4 - 2.3.2 + 3.2.0 0.23.0 2.1.0 1.5-beta1 diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index db646899ad..71916900a4 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -162,7 +162,7 @@ com.baeldung.SpringBootRestApplication 1.4.11.1 - 3.1.0 + 3.2.0 3.3.0 2.3.7 From 62b0d3def765c37d9082415d5411980dff8d3493 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 11 Nov 2023 12:17:46 +0530 Subject: [PATCH 173/233] JAVA-27185 Upgrade hibernate validator in spring-cloud-gateway-2 --- spring-cloud-modules/spring-cloud-gateway-2/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-cloud-modules/spring-cloud-gateway-2/pom.xml b/spring-cloud-modules/spring-cloud-gateway-2/pom.xml index 22182e8c78..4228c72d37 100644 --- a/spring-cloud-modules/spring-cloud-gateway-2/pom.xml +++ b/spring-cloud-modules/spring-cloud-gateway-2/pom.xml @@ -57,7 +57,7 @@ test - org.hibernate + org.hibernate.validator hibernate-validator-cdi ${hibernate-validator.version} @@ -116,7 +116,7 @@ - 6.0.2.Final + 8.0.1.Final 0.7.2 9.19 From df9e040b765b8ac8e59e911d8ef170b1b8269682 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 11 Nov 2023 12:59:42 +0530 Subject: [PATCH 174/233] JAVA-27186 Upgrade hibernate validator version in spring-cloud-gateway --- spring-cloud-modules/spring-cloud-gateway/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-cloud-modules/spring-cloud-gateway/pom.xml b/spring-cloud-modules/spring-cloud-gateway/pom.xml index 76072a59ac..0287ab7588 100644 --- a/spring-cloud-modules/spring-cloud-gateway/pom.xml +++ b/spring-cloud-modules/spring-cloud-gateway/pom.xml @@ -62,7 +62,7 @@ test - org.hibernate + org.hibernate.validator hibernate-validator-cdi ${hibernate-validator.version} @@ -185,7 +185,7 @@ - 6.0.2.Final + 8.0.1.Final 0.7.2 9.19 From 3435cd06509844c366a0d06a811bb967fc52ab2e Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 11 Nov 2023 13:43:35 +0530 Subject: [PATCH 175/233] JAVA-27187 Upgrade hibernate validator version in spring-core-2 --- spring-core-2/pom.xml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index 2d11cc2124..f27b16acc3 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -88,9 +88,8 @@ - org.hibernate + org.hibernate.validator hibernate-validator - ${hibernate.version} @@ -160,8 +159,6 @@ com.baeldung.sample.App 1.3.2 - - 5.2.5.Final 3.6 2.1.0 From 3d5b1cff86e129f3cd33b934967d30e0b5cefc53 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 11 Nov 2023 14:11:32 +0530 Subject: [PATCH 176/233] JAVA-27188 Upgrade hibernate-validator version in spring-exceptions --- spring-exceptions/pom.xml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index 49c44f88f2..e0071a4206 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -72,7 +72,7 @@ - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} @@ -108,11 +108,6 @@ ${org.springframework.version} test - - javax.el - el-api - ${javax.el.version} - org.apache.derby derby @@ -171,8 +166,7 @@ 7.0.73 10.13.1.1 - 5.3.3.Final - 2.2 + 8.0.1.Final 2.3.0 4.4.5 From 8fff0f323cb8b949b31ef47177c1e1035d4a03bc Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Sat, 11 Nov 2023 10:53:34 +0000 Subject: [PATCH 177/233] [JAVA-20077] Sorted modules in alphabetical order (#15168) * [JAVA-20077] Sorted modules in alphabetical order * [JAVA-2007] --- pom.xml | 680 ++++++++++++++++++++++++++------------------------------ 1 file changed, 310 insertions(+), 370 deletions(-) diff --git a/pom.xml b/pom.xml index bb5a0c9e7b..47c566023d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,8 +1,8 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung parent-modules @@ -690,35 +690,157 @@ - parent-boot-3 - lombok-modules - osgi - spring-katharsis - logging-modules - spring-boot-modules - apache-httpclient - apache-httpclient4 + akka-modules + algorithms-modules + antlr + apache-cxf-modules apache-httpclient-2 - spring-mobile - microservices-modules - spring-ejb-modules - spring-di - spring-di-2 - spring-jinq - vavr-modules - java-websocket + apache-httpclient4 + apache-httpclient + apache-kafka-2 + apache-kafka + apache-libraries-2 + apache-libraries + apache-olingo + apache-poi-2 + apache-poi-3 + apache-poi + apache-thrift + apache-tika + apache-velocity + asciidoctor + asm + atomikos + atomix + aws-modules azure - netflix-modules - spf4j - spring-jersey - jersey - jaxb - + bazel + checker-framework + core-groovy-modules + core-java-modules + custom-pmd + data-structures + deeplearning4j + di-modules + disruptor + docker-modules + dozer + drools + dubbo + + gcp-firebase + geotools + google-auto-project + google-cloud + gradle-modules/gradle/maven-to-gradle + graphql-modules + grpc + guava-modules + hazelcast + httpclient-simple + hystrix + image-compressing + image-processing + jackson-modules + jackson-simple + java-blockchain + java-jdi + + java-rmi + java-spi + java-websocket javafx - spring-batch + javax-sound + javaxval-2 + javaxval + jaxb + jersey + jetbrains + jgit + jhipster-6 + jib + jmeter + jmh + jsf + json-modules + jsoup + jws + ksqldb + kubernetes-modules + language-interop + libraries-2 + libraries-3 + libraries-4 + libraries-5 + libraries-6 + libraries-ai + libraries-apache-commons-2 + libraries-apache-commons-collections + libraries-apache-commons-io + libraries-apache-commons + libraries-concurrency + libraries-data-2 + libraries-data-db + libraries-data-io + libraries-data + libraries-files + libraries-http-2 + libraries-http + libraries-io + libraries-llms + libraries-primitive + libraries-rpc + libraries-security + libraries-server-2 + libraries-server + libraries-testing + libraries-transform + libraries + lightrun + logging-modules + lombok-modules + lucene + mapstruct + maven-modules + mesos-marathon + messaging-modules + metrics + microservices-modules + mustache + mybatis + netflix-modules + optaplanner + orika + osgi + parent-boot-3 + patterns-modules + pdf-2 + pdf + performance-tests + persistence-modules + persistence-modules/spring-data-neo4j + protobuffer + quarkus-modules + reactive-systems + reactor-core + rsocket + rule-engines-modules + rxjava-modules + saas-modules + security-modules + server-modules + spf4j + spring-5-webflux-2 + spring-5-webflux + spring-5 + spring-activiti + spring-actuator + spring-aop-2 + spring-aop spring-batch-2 + spring-batch + spring-boot-modules spring-boot-rest - spring-drools spring-cloud-modules/spring-cloud-azure spring-cloud-modules/spring-cloud-circuit-breaker spring-cloud-modules/spring-cloud-contract @@ -728,210 +850,58 @@ spring-cloud-modules/spring-cloud-security spring-cloud-modules/spring-cloud-stream-starters spring-cloud-modules/spring-cloud-zuul-eureka-integration - - spring-exceptions - spring-jenkins-pipeline - spring-core - spring-core-4 - spring-integration - spring-remoting-modules - libraries-security - libraries-data-db - - performance-tests - security-modules - libraries-server-2 - orika - patterns-modules - json-modules - libraries-data - saas-modules - server-modules - apache-cxf-modules - - spring-aop - jmeter - spring-aop-2 - - algorithms-modules - apache-libraries - apache-libraries-2 - apache-poi - apache-velocity - di-modules - asciidoctor - aws-modules - - checker-framework - core-groovy-modules - - core-java-modules - custom-pmd - data-structures - jackson-modules - jmh - deeplearning4j - docker-modules - drools - guava-modules - kubernetes-modules - libraries-concurrency - jhipster-6 - libraries-testing - maven-modules - optaplanner - persistence-modules - quarkus-modules - spring-reactive-modules - spring-swagger-codegen/custom-validations-opeanpi-codegen - testing-modules - testing-modules/mockito-simple - - rule-engines-modules - - reactive-systems - rxjava-modules - - lightrun - tablesaw - image-compressing - geotools - - jws - - - - akka-modules - httpclient-simple - antlr - apache-kafka - apache-kafka-2 - apache-olingo - - apache-poi-2 - apache-poi-3 - apache-thrift - apache-tika - - asm - atomikos - atomix - - bazel - google-auto-project - disruptor - dozer - dubbo - - google-cloud - graphql-modules - grpc - hazelcast - hystrix - jackson-simple - java-blockchain - java-jdi - java-rmi - java-spi - javax-sound - javaxval - javaxval-2 - jetbrains - jgit - jib - - jsoup - ksqldb - jsf - - libraries - libraries-2 - libraries-4 - libraries-5 - libraries-6 - - libraries-apache-commons - libraries-apache-commons-2 - libraries-apache-commons-collections - libraries-apache-commons-io - libraries-data-2 - libraries-data-io - libraries-files - libraries-http - libraries-http-2 - libraries-io - libraries-ai - libraries-primitive - libraries-rpc - libraries-server - libraries-transform - - lucene - mapstruct - mesos-marathon - metrics - mustache - mybatis - pdf - pdf-2 - protobuffer - reactor-core - rsocket - - - spring-5 - spring-5-webflux - spring-5-webflux-2 - spring-6-rsocket - spring-activiti - spring-actuator spring-core-2 spring-core-3 + spring-core-4 + spring-core spring-credhub - spring-di-3 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 - + spring-katharsis + spring-mobile spring-native - spring-soap - spring-security-modules spring-protobuf + spring-pulsar spring-quartz - + spring-reactive-modules + spring-remoting-modules spring-scheduling - - spring-state-machine + spring-security-modules spring-shell + spring-soap spring-spel + spring-state-machine spring-static-resources + spring-swagger-codegen/custom-validations-opeanpi-codegen spring-threads spring-vault - spring-websockets spring-web-modules + spring-websockets static-analysis + tablesaw tensorflow-java - vertx-modules - xstream - webrtc - - messaging-modules - + testing-modules + testing-modules/mockito-simple vaadin - libraries-3 + vavr-modules + vertx-modules web-modules - xml + webrtc xml-2 - image-processing - language-interop - gradle-modules/gradle/maven-to-gradle - persistence-modules/spring-data-neo4j - gcp-firebase - spring-di-4 - spring-kafka-2 - - libraries-llms - spring-pulsar + xml + xstream @@ -965,248 +935,218 @@ - parent-boot-3 - lombok-modules - osgi - spring-katharsis - logging-modules - spring-boot-modules - apache-httpclient - apache-httpclient4 - apache-httpclient-2 - spring-mobile - microservices-modules - spring-ejb-modules - spring-di - spring-di-2 - spring-jinq - vavr-modules - java-websocket - azure - netflix-modules - spf4j - spring-jersey - jersey - jaxb - - javafx - spring-batch - spring-batch-2 - spring-boot-rest - spring-drools - spring-cloud-modules/spring-cloud-azure - spring-cloud-modules/spring-cloud-circuit-breaker - spring-cloud-modules/spring-cloud-eureka - spring-cloud-modules/spring-cloud-contract - spring-cloud-modules/spring-cloud-data-flow - spring-cloud-modules/spring-cloud-netflix-feign - spring-cloud-modules/spring-cloud-stream-starters - spring-cloud-modules/spring-cloud-security - spring-cloud-modules/spring-cloud-zuul-eureka-integration - - spring-exceptions - spring-jenkins-pipeline - spring-core - spring-core-4 - spring-integration - spring-remoting-modules - libraries-security - libraries-data-db - - performance-tests - security-modules - libraries-server-2 - orika - patterns-modules - json-modules - libraries-data - saas-modules - server-modules - apache-cxf-modules - - algorithms-modules - apache-libraries - apache-libraries-2 - apache-poi - apache-velocity - di-modules - asciidoctor - aws-modules - - checker-framework - - core-groovy-modules - - core-java-modules - gcp-firebase - spring-aop - spring-aop-2 - custom-pmd - data-structures - jackson-modules - jmh - deeplearning4j - jmeter - docker-modules - drools - guava-modules - kubernetes-modules - libraries-concurrency - jhipster-6 - libraries-testing - maven-modules - optaplanner - persistence-modules - quarkus-modules - spring-reactive-modules - spring-swagger-codegen/custom-validations-opeanpi-codegen - testing-modules - testing-modules/mockito-simple - - rule-engines-modules - - reactive-systems - rxjava-modules - - lightrun - tablesaw - image-compressing - geotools - - jws - - - akka-modules + algorithms-modules antlr - apache-kafka + apache-cxf-modules + apache-httpclient-2 + apache-httpclient4 + apache-httpclient apache-kafka-2 + apache-kafka + apache-libraries-2 + apache-libraries apache-olingo - apache-poi-2 apache-poi-3 + apache-poi apache-thrift apache-tika - + apache-velocity + asciidoctor asm atomikos atomix - + aws-modules + azure bazel - google-auto-project + checker-framework + core-groovy-modules + core-java-modules + custom-pmd + data-structures + deeplearning4j + di-modules disruptor + docker-modules dozer - + drools dubbo + gcp-firebase + geotools + google-auto-project google-cloud + gradle-modules/gradle/maven-to-gradle graphql-modules grpc + guava-modules hazelcast httpclient-simple hystrix + image-compressing + image-processing + jackson-modules jackson-simple java-blockchain java-jdi + java-rmi java-spi + java-websocket + javafx javax-sound - javaxval javaxval-2 + javaxval + jaxb + jersey jetbrains jgit + jhipster-6 jib - - jsoup + jmeter + jmh jsf + json-modules + jsoup + jws ksqldb - - libraries + kubernetes-modules + language-interop libraries-2 + libraries-3 libraries-4 libraries-5 libraries-6 - libraries-apache-commons + libraries-ai libraries-apache-commons-2 libraries-apache-commons-collections libraries-apache-commons-io + libraries-apache-commons + libraries-concurrency libraries-data-2 + libraries-data-db libraries-data-io + libraries-data libraries-files - libraries-http libraries-http-2 + libraries-http libraries-io - libraries-ai + libraries-llms libraries-primitive libraries-rpc + libraries-security + libraries-server-2 libraries-server + libraries-testing libraries-transform - + libraries + lightrun + logging-modules + lombok-modules lucene mapstruct + maven-modules mesos-marathon + messaging-modules metrics + microservices-modules mustache mybatis - pdf + netflix-modules + optaplanner + orika + osgi + parent-boot-3 + patterns-modules pdf-2 + pdf + performance-tests + persistence-modules + persistence-modules/spring-data-neo4j protobuffer + quarkus-modules + reactive-systems reactor-core rsocket - - - - spring-5 - spring-5-webflux + rule-engines-modules + rxjava-modules + saas-modules + security-modules + server-modules + spf4j spring-5-webflux-2 + spring-5-webflux + spring-5 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 + spring-core-4 + spring-core spring-credhub - spring-di-3 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 - + spring-katharsis + spring-mobile spring-native - spring-soap - spring-security-modules spring-protobuf + spring-pulsar spring-quartz - + spring-reactive-modules + spring-remoting-modules spring-scheduling - - spring-state-machine + spring-security-modules spring-shell + spring-soap spring-spel + spring-state-machine spring-static-resources + spring-swagger-codegen/custom-validations-opeanpi-codegen spring-threads spring-vault - spring-websockets spring-web-modules + spring-websockets static-analysis + tablesaw tensorflow-java - vertx-modules - xstream - webrtc - - messaging-modules - + testing-modules + testing-modules/mockito-simple vaadin - libraries-3 + vavr-modules + vertx-modules web-modules - xml + webrtc xml-2 - image-processing - language-interop - gradle-modules/gradle/maven-to-gradle - persistence-modules/spring-data-neo4j - spring-actuator - spring-di-4 - spring-kafka-2 - - libraries-llms - spring-pulsar + xml + xstream From 3f850f7d00d6bb52046edb1b502062ae18c816cd Mon Sep 17 00:00:00 2001 From: Gaetano Piazzolla Date: Sat, 11 Nov 2023 12:05:30 +0100 Subject: [PATCH 178/233] JAVA-26728 | update sshj lib (#15144) * JAVA-26728 | update sshj lib * JAVA-26728 | added compression --- libraries-io/pom.xml | 2 +- .../io/remote/SftpFileTransferLiveTest.java | 17 +++++++++-------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/libraries-io/pom.xml b/libraries-io/pom.xml index 08ad0afc3f..7464b9a507 100644 --- a/libraries-io/pom.xml +++ b/libraries-io/pom.xml @@ -56,7 +56,7 @@ 0.1.55 - 0.27.0 + 0.37.0 2.4 2.9.0 5.8 diff --git a/libraries-io/src/test/java/com/baeldung/java/io/remote/SftpFileTransferLiveTest.java b/libraries-io/src/test/java/com/baeldung/java/io/remote/SftpFileTransferLiveTest.java index 5846128082..81c6cb556c 100644 --- a/libraries-io/src/test/java/com/baeldung/java/io/remote/SftpFileTransferLiveTest.java +++ b/libraries-io/src/test/java/com/baeldung/java/io/remote/SftpFileTransferLiveTest.java @@ -20,14 +20,14 @@ import net.schmizz.sshj.transport.verification.PromiscuousVerifier; public class SftpFileTransferLiveTest { - private String remoteHost = "HOST_NAME_HERE"; - private String username = "USERNAME_HERE"; - private String password = "PASSWORD_HERE"; - private String localFile = "src/main/resources/input.txt"; - private String remoteFile = "welcome.txt"; - private String localDir = "src/main/resources/"; - private String remoteDir = "remote_sftp_test/"; - private String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample"; + private final String remoteHost = "HOST_NAME_HERE"; + private final String username = "USERNAME_HERE"; + private final String password = "PASSWORD_HERE"; + private final String localFile = "src/main/resources/input.txt"; + private final String remoteFile = "welcome.txt"; + private final String localDir = "src/main/resources/"; + private final String remoteDir = "remote_sftp_test/"; + private final String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample"; @Test public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException { @@ -100,6 +100,7 @@ public class SftpFileTransferLiveTest { client.addHostKeyVerifier(new PromiscuousVerifier()); client.connect(remoteHost); client.authPassword(username, password); + client.useCompression(); return client; } From 47f7b926e60709efe74245b33a37a3cb0c2f7db0 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 07:32:39 +0200 Subject: [PATCH 179/233] [JAVA-26774] Upgraded mapstruct library to latest version --- core-java-modules/core-java-lang-6/pom.xml | 3 +-- jhipster-6/bookstore-monolith/pom.xml | 2 +- jhipster-modules/jhipster-microservice/car-app/pom.xml | 2 +- jhipster-modules/jhipster-microservice/dealer-app/pom.xml | 2 +- jhipster-modules/jhipster-microservice/gateway-app/pom.xml | 2 +- jhipster-modules/jhipster-monolithic/pom.xml | 2 +- jhipster-modules/jhipster-uaa/gateway/pom.xml | 2 +- jhipster-modules/jhipster-uaa/quotes/pom.xml | 2 +- jhipster-modules/jhipster-uaa/uaa/pom.xml | 2 +- mapstruct/pom.xml | 2 +- performance-tests/pom.xml | 2 +- persistence-modules/spring-data-jpa-enterprise/pom.xml | 4 ++-- spring-boot-modules/spring-boot-3-2/pom.xml | 2 +- spring-boot-modules/spring-boot-3/pom.xml | 4 ++-- 14 files changed, 16 insertions(+), 17 deletions(-) diff --git a/core-java-modules/core-java-lang-6/pom.xml b/core-java-modules/core-java-lang-6/pom.xml index 6561c4fdcc..54035c1eb0 100644 --- a/core-java-modules/core-java-lang-6/pom.xml +++ b/core-java-modules/core-java-lang-6/pom.xml @@ -29,7 +29,6 @@ org.apache.maven.plugins maven-compiler-plugin - 3.5.1 17 17 @@ -50,7 +49,7 @@ 17 17 UTF-8 - 1.5.5.Final + 1.6.0.Beta1 \ No newline at end of file diff --git a/jhipster-6/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml index a35abb9c19..26a1ff6214 100644 --- a/jhipster-6/bookstore-monolith/pom.xml +++ b/jhipster-6/bookstore-monolith/pom.xml @@ -1159,7 +1159,7 @@ 5.1.5.RELEASE 2.0.1.Final 2.3.2 - 1.3.0.Final + 1.6.0.Beta1 3.1.0 diff --git a/jhipster-modules/jhipster-microservice/car-app/pom.xml b/jhipster-modules/jhipster-microservice/car-app/pom.xml index f345688939..3789dc35c1 100644 --- a/jhipster-modules/jhipster-microservice/car-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/car-app/pom.xml @@ -36,7 +36,7 @@ 3.6.2 4.8 jdt_apt - 1.1.0.Final + 1.6.0.Beta1 2.10 1.4.1 3.0.1 diff --git a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml index 056bd60f33..5d588e8dcb 100644 --- a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml @@ -35,7 +35,7 @@ 3.6.2 4.8 jdt_apt - 1.1.0.Final + 1.6.0.Beta1 2.10 1.4.1 3.0.1 diff --git a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml index b90f22f009..26c621bb57 100644 --- a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml @@ -39,7 +39,7 @@ 4.8 1.3.0 jdt_apt - 1.1.0.Final + 1.6.0.Beta1 2.10 1.4.1 3.0.1 diff --git a/jhipster-modules/jhipster-monolithic/pom.xml b/jhipster-modules/jhipster-monolithic/pom.xml index fbcee8f1ff..a8b93b5514 100644 --- a/jhipster-modules/jhipster-monolithic/pom.xml +++ b/jhipster-modules/jhipster-monolithic/pom.xml @@ -904,7 +904,7 @@ 3.6.2 4.8 jdt_apt - 1.1.0.Final + 1.6.0.Beta1 1.4.1 3.0.1 2.10 diff --git a/jhipster-modules/jhipster-uaa/gateway/pom.xml b/jhipster-modules/jhipster-uaa/gateway/pom.xml index 13652575cd..b1982a6f93 100644 --- a/jhipster-modules/jhipster-uaa/gateway/pom.xml +++ b/jhipster-modules/jhipster-uaa/gateway/pom.xml @@ -1048,7 +1048,7 @@ 3.5.5 3.6 2.0.1.Final - 1.2.0.Final + 1.6.0.Beta1 3.1.0 diff --git a/jhipster-modules/jhipster-uaa/quotes/pom.xml b/jhipster-modules/jhipster-uaa/quotes/pom.xml index 2a3c550071..11033af395 100644 --- a/jhipster-modules/jhipster-uaa/quotes/pom.xml +++ b/jhipster-modules/jhipster-uaa/quotes/pom.xml @@ -868,7 +868,7 @@ 3.5.5 3.6 2.0.1.Final - 1.2.0.Final + 1.6.0.Beta1 3.1.0 diff --git a/jhipster-modules/jhipster-uaa/uaa/pom.xml b/jhipster-modules/jhipster-uaa/uaa/pom.xml index 42802b6040..47a5c81c1e 100644 --- a/jhipster-modules/jhipster-uaa/uaa/pom.xml +++ b/jhipster-modules/jhipster-uaa/uaa/pom.xml @@ -869,7 +869,7 @@ 3.5.5 3.6 2.0.1.Final - 1.2.0.Final + 1.6.0.Beta1 3.1.0 diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index 7c279acb7b..5332bcaeb3 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -73,7 +73,7 @@ - 1.5.5.Final + 1.6.0.Beta1 4.3.4.RELEASE 0.2.0 diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index 9f57a1a90c..d22a9cf3ac 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -151,7 +151,7 @@ 1.5.4 6.5.2 - 1.5.2.Final + 1.6.0.Beta1 3.2.0 1.6.1.CR2 diff --git a/persistence-modules/spring-data-jpa-enterprise/pom.xml b/persistence-modules/spring-data-jpa-enterprise/pom.xml index 6bd89032fa..d998849ffb 100644 --- a/persistence-modules/spring-data-jpa-enterprise/pom.xml +++ b/persistence-modules/spring-data-jpa-enterprise/pom.xml @@ -45,7 +45,7 @@ org.mapstruct - mapstruct-jdk8 + mapstruct ${mapstruct.version} provided @@ -97,7 +97,7 @@ - 1.3.1.Final + 1.6.0.Beta1 1.19.1 diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index 276659c609..9b5b7ea254 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -280,7 +280,7 @@ - 1.5.2.Final + 1.6.0.Beta1 2.0.0 3.0.0-M7 5.14.0 diff --git a/spring-boot-modules/spring-boot-3/pom.xml b/spring-boot-modules/spring-boot-3/pom.xml index bb8c5dd53c..a1a5eab563 100644 --- a/spring-boot-modules/spring-boot-3/pom.xml +++ b/spring-boot-modules/spring-boot-3/pom.xml @@ -206,8 +206,8 @@ - 19 - 1.5.2.Final + 17 + 1.6.0.Beta1 2.2.0 3.0.0-M7 com.baeldung.sample.TodoApplication From 6db881bfa2df6776a67b7de0873c07bed1402aed Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 07:53:55 +0200 Subject: [PATCH 180/233] [JAVA-26774] Revert mapstruct upgrade on jhipster modules --- jhipster-6/bookstore-monolith/pom.xml | 2 +- jhipster-modules/jhipster-microservice/car-app/pom.xml | 2 +- jhipster-modules/jhipster-microservice/dealer-app/pom.xml | 2 +- jhipster-modules/jhipster-microservice/gateway-app/pom.xml | 2 +- jhipster-modules/jhipster-monolithic/pom.xml | 2 +- jhipster-modules/jhipster-uaa/gateway/pom.xml | 2 +- jhipster-modules/jhipster-uaa/quotes/pom.xml | 2 +- jhipster-modules/jhipster-uaa/uaa/pom.xml | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/jhipster-6/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml index 26a1ff6214..a35abb9c19 100644 --- a/jhipster-6/bookstore-monolith/pom.xml +++ b/jhipster-6/bookstore-monolith/pom.xml @@ -1159,7 +1159,7 @@ 5.1.5.RELEASE 2.0.1.Final 2.3.2 - 1.6.0.Beta1 + 1.3.0.Final 3.1.0 diff --git a/jhipster-modules/jhipster-microservice/car-app/pom.xml b/jhipster-modules/jhipster-microservice/car-app/pom.xml index 3789dc35c1..f345688939 100644 --- a/jhipster-modules/jhipster-microservice/car-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/car-app/pom.xml @@ -36,7 +36,7 @@ 3.6.2 4.8 jdt_apt - 1.6.0.Beta1 + 1.1.0.Final 2.10 1.4.1 3.0.1 diff --git a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml index 5d588e8dcb..056bd60f33 100644 --- a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml @@ -35,7 +35,7 @@ 3.6.2 4.8 jdt_apt - 1.6.0.Beta1 + 1.1.0.Final 2.10 1.4.1 3.0.1 diff --git a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml index 26c621bb57..b90f22f009 100644 --- a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml @@ -39,7 +39,7 @@ 4.8 1.3.0 jdt_apt - 1.6.0.Beta1 + 1.1.0.Final 2.10 1.4.1 3.0.1 diff --git a/jhipster-modules/jhipster-monolithic/pom.xml b/jhipster-modules/jhipster-monolithic/pom.xml index a8b93b5514..fbcee8f1ff 100644 --- a/jhipster-modules/jhipster-monolithic/pom.xml +++ b/jhipster-modules/jhipster-monolithic/pom.xml @@ -904,7 +904,7 @@ 3.6.2 4.8 jdt_apt - 1.6.0.Beta1 + 1.1.0.Final 1.4.1 3.0.1 2.10 diff --git a/jhipster-modules/jhipster-uaa/gateway/pom.xml b/jhipster-modules/jhipster-uaa/gateway/pom.xml index b1982a6f93..13652575cd 100644 --- a/jhipster-modules/jhipster-uaa/gateway/pom.xml +++ b/jhipster-modules/jhipster-uaa/gateway/pom.xml @@ -1048,7 +1048,7 @@ 3.5.5 3.6 2.0.1.Final - 1.6.0.Beta1 + 1.2.0.Final 3.1.0 diff --git a/jhipster-modules/jhipster-uaa/quotes/pom.xml b/jhipster-modules/jhipster-uaa/quotes/pom.xml index 11033af395..2a3c550071 100644 --- a/jhipster-modules/jhipster-uaa/quotes/pom.xml +++ b/jhipster-modules/jhipster-uaa/quotes/pom.xml @@ -868,7 +868,7 @@ 3.5.5 3.6 2.0.1.Final - 1.6.0.Beta1 + 1.2.0.Final 3.1.0 diff --git a/jhipster-modules/jhipster-uaa/uaa/pom.xml b/jhipster-modules/jhipster-uaa/uaa/pom.xml index 47a5c81c1e..42802b6040 100644 --- a/jhipster-modules/jhipster-uaa/uaa/pom.xml +++ b/jhipster-modules/jhipster-uaa/uaa/pom.xml @@ -869,7 +869,7 @@ 3.5.5 3.6 2.0.1.Final - 1.6.0.Beta1 + 1.2.0.Final 3.1.0 From 7dbd9cf9f60aa62ce088a7196d606f6c2e4c870c Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 08:00:42 +0200 Subject: [PATCH 181/233] [JAVA-26774] --- spring-boot-modules/spring-boot-3/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-3/pom.xml b/spring-boot-modules/spring-boot-3/pom.xml index a1a5eab563..ae9e9d7308 100644 --- a/spring-boot-modules/spring-boot-3/pom.xml +++ b/spring-boot-modules/spring-boot-3/pom.xml @@ -206,7 +206,7 @@ - 17 + 19 1.6.0.Beta1 2.2.0 3.0.0-M7 From 46dbc56913f2b3dc7f90b1d12e540a20edcb3ebf Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 12 Nov 2023 11:51:29 +0530 Subject: [PATCH 182/233] JAVA-27189 Upgrade hibernate validator version in spring-static-resources --- spring-static-resources/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index f682eafdbe..f635583e62 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -117,7 +117,7 @@ ${jackson.version} - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} @@ -194,7 +194,7 @@ 1.8.9 - 6.0.10.Final + 8.0.1.Final 4.1.0 2.10 1 From c5cbb3f0d98d88531bda791ee49463c4411129f0 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 08:52:18 +0200 Subject: [PATCH 183/233] [JAVA-26763] Upgraded powermock to latest version --- spring-web-modules/spring-mvc-velocity/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-web-modules/spring-mvc-velocity/pom.xml b/spring-web-modules/spring-mvc-velocity/pom.xml index 676fa09dac..cc92e8c6a5 100644 --- a/spring-web-modules/spring-mvc-velocity/pom.xml +++ b/spring-web-modules/spring-mvc-velocity/pom.xml @@ -64,7 +64,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 ${powermock.version} test @@ -106,7 +106,7 @@ - 1.6.6 + 2.0.9 4.4.5 4.5.2 1.7 From 21f73644b4b55c9508d588f0613690390ed404e7 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 12 Nov 2023 13:24:22 +0530 Subject: [PATCH 184/233] JAVA-27191 Upgrade hibernate validator version in spring-mvc-basics-2 --- spring-web-modules/spring-mvc-basics-2/pom.xml | 4 ++-- .../com/baeldung/spring/controller/CustomerController.java | 2 +- .../com/baeldung/spring/controller/EmployeeController.java | 2 +- .../java/com/baeldung/spring/controller/MailController.java | 2 +- .../src/main/java/com/baeldung/spring/domain/Employee.java | 4 ++-- .../main/java/com/baeldung/spring/domain/MailObject.java | 6 +++--- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/spring-web-modules/spring-mvc-basics-2/pom.xml b/spring-web-modules/spring-mvc-basics-2/pom.xml index 28eb3a16f2..613e42dee3 100644 --- a/spring-web-modules/spring-mvc-basics-2/pom.xml +++ b/spring-web-modules/spring-mvc-basics-2/pom.xml @@ -42,7 +42,7 @@ ${jstl.version} - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} @@ -148,7 +148,7 @@ - 6.0.10.Final + 8.0.1.Final enter-location-of-server 3.0.11.RELEASE 2.4.12 diff --git a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/CustomerController.java b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/CustomerController.java index 8ecfce58e3..e1d2a8e37f 100644 --- a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/CustomerController.java +++ b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/CustomerController.java @@ -1,6 +1,6 @@ package com.baeldung.spring.controller; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; diff --git a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/EmployeeController.java index 6543a98af1..5299d8289b 100644 --- a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -3,7 +3,7 @@ package com.baeldung.spring.controller; import java.util.HashMap; import java.util.Map; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; diff --git a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java index b6e19a4c39..f4088b8bb3 100644 --- a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java +++ b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java @@ -8,7 +8,7 @@ import java.util.Set; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; diff --git a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/Employee.java b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/Employee.java index 900770b873..a0641b0a32 100644 --- a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/Employee.java +++ b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/Employee.java @@ -1,7 +1,7 @@ package com.baeldung.spring.domain; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; public class Employee { diff --git a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java index d425ca9a26..23807926ca 100644 --- a/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java +++ b/spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java @@ -1,8 +1,8 @@ package com.baeldung.spring.domain; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; /** * Created by Olga on 7/20/2016. From 57b035bade3b2481ec793d1ca7bd85f012f86dee Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 12 Nov 2023 14:01:38 +0530 Subject: [PATCH 185/233] JAVA-27192 Upgrade hibernate validator in spring-mvc-crash --- spring-web-modules/spring-mvc-crash/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-mvc-crash/pom.xml b/spring-web-modules/spring-mvc-crash/pom.xml index f3faa18816..9bfcfb488e 100644 --- a/spring-web-modules/spring-mvc-crash/pom.xml +++ b/spring-web-modules/spring-mvc-crash/pom.xml @@ -147,7 +147,7 @@ 4.4.5 4.5.2 - 6.0.10.Final + 8.0.1.Final 3.0.1-b08 2.8.0 From e6316d25d3f8be6060ea15aae0fc2c7196240db0 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 12 Nov 2023 14:30:03 +0530 Subject: [PATCH 186/233] JAVA-27193 Upgrade hibernate validator version in spring-mvc-forms-jsp --- spring-web-modules/spring-mvc-forms-jsp/pom.xml | 4 ++-- .../controller/CustomerController.java | 2 +- .../controller/EmployeeController.java | 2 +- .../springmvcforms/controller/UserController.java | 2 +- .../com/baeldung/springmvcforms/domain/Employee.java | 4 ++-- .../com/baeldung/springmvcforms/domain/User.java | 12 ++++++------ 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/spring-web-modules/spring-mvc-forms-jsp/pom.xml b/spring-web-modules/spring-mvc-forms-jsp/pom.xml index 3ad815e95f..5096c6e23d 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/pom.xml +++ b/spring-web-modules/spring-mvc-forms-jsp/pom.xml @@ -48,7 +48,7 @@ ${mysql-connector-java.version} - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} @@ -102,7 +102,7 @@ - 6.0.10.Final + 8.0.1.Final 5.2.5.Final 6.0.6 1.3.2 diff --git a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java index 586c2467fe..81dd700551 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java +++ b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java @@ -1,6 +1,6 @@ package com.baeldung.springmvcforms.controller; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; diff --git a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java index 478b3532fe..9c0b3a7086 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java +++ b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java @@ -7,7 +7,7 @@ import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; -import javax.validation.Valid; +import jakarta.validation.Valid; import java.util.HashMap; import java.util.Map; diff --git a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/UserController.java b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/UserController.java index f5553cf2b7..80f56645a9 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/UserController.java +++ b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/UserController.java @@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; -import javax.validation.Valid; +import jakarta.validation.Valid; import java.util.Arrays; import java.util.Collections; import java.util.List; diff --git a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Employee.java b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Employee.java index 23cb72b3dc..ae174e2020 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Employee.java +++ b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Employee.java @@ -1,7 +1,7 @@ package com.baeldung.springmvcforms.domain; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; public class Employee { diff --git a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java index 9e0e7c99be..db055763a4 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java +++ b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java @@ -1,11 +1,11 @@ package com.baeldung.springmvcforms.domain; -import javax.validation.constraints.Digits; -import javax.validation.constraints.Email; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.Digits; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; public class User { From ec251f847b550c513d6431ea34de0599e298c239 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 16:35:46 +0200 Subject: [PATCH 187/233] [JAVA-26739] Upgraded json-path to latest version --- core-java-modules/core-java-optional/pom.xml | 4 +- .../java9additions/Java9OptionalUnitTest.java | 170 +++++++++--------- ethereum/pom.xml | 2 +- jackson-modules/jackson-annotations/pom.xml | 4 +- json-modules/json-path/pom.xml | 4 +- .../spring-mvc-basics-5/pom.xml | 2 +- spring-web-modules/spring-mvc-java/pom.xml | 2 +- video-tutorials/jackson-annotations/pom.xml | 2 +- 8 files changed, 94 insertions(+), 96 deletions(-) diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index eeefed867e..68800f67fc 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/pom.xml @@ -47,14 +47,14 @@ io.rest-assured json-path - ${rest-assured.version} + ${json-path.version} test 5.4.0.Final - 3.1.1 + 5.3.2 \ No newline at end of file diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/java9additions/Java9OptionalUnitTest.java b/core-java-modules/core-java-optional/src/test/java/com/baeldung/java9additions/Java9OptionalUnitTest.java index ee04432e44..e7daac4b8c 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/java9additions/Java9OptionalUnitTest.java +++ b/core-java-modules/core-java-optional/src/test/java/com/baeldung/java9additions/Java9OptionalUnitTest.java @@ -8,88 +8,88 @@ import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; -// Uncomment code when code base is compatible with Java 9 -//public class Java9OptionalUnitTest { -// -// @Test -// public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() { -// //given -// Optional value = Optional.of("a"); -// -// //when -// List collect = value.stream().map(String::toUpperCase).collect(Collectors.toList()); -// -// //then -// assertThat(collect).hasSameElementsAs(List.of("A")); -// } -// -// @Test -// public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() { -// //given -// Optional value = Optional.empty(); -// -// //when -// List collect = value.stream().map(String::toUpperCase).collect(Collectors.toList()); -// -// //then -// assertThat(collect).isEmpty(); -// } -// -// @Test -// public void givenOptional_whenPresent_thenShouldExecuteProperCallback() { -// //given -// Optional value = Optional.of("properValue"); -// AtomicInteger successCounter = new AtomicInteger(0); -// AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0); -// -// //when -// value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet); -// -// //then -// assertThat(successCounter.get()).isEqualTo(1); -// assertThat(onEmptyOptionalCounter.get()).isEqualTo(0); -// } -// -// @Test -// public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() { -// //given -// Optional value = Optional.empty(); -// AtomicInteger successCounter = new AtomicInteger(0); -// AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0); -// -// //when -// value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet); -// -// //then -// assertThat(successCounter.get()).isEqualTo(0); -// assertThat(onEmptyOptionalCounter.get()).isEqualTo(1); -// } -// -// @Test -// public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() { -// //given -// String expected = "properValue"; -// Optional value = Optional.of(expected); -// Optional defaultValue = Optional.of("default"); -// -// //when -// Optional result = value.or(() -> defaultValue); -// -// //then -// assertThat(result.get()).isEqualTo(expected); -// } -// -// @Test -// public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() { -// //given -// String defaultString = "default"; -// Optional value = Optional.empty(); -// Optional defaultValue = Optional.of(defaultString); -// -// //when -// Optional result = value.or(() -> defaultValue); -// -// //then -// assertThat(result.get()).isEqualTo(defaultString); -// } -//} \ No newline at end of file + +public class Java9OptionalUnitTest { + + @Test + public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() { + //given + Optional value = Optional.of("a"); + + //when + List collect = value.stream().map(String::toUpperCase).collect(Collectors.toList()); + + //then + assertThat(collect).hasSameElementsAs(List.of("A")); + } + + @Test + public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() { + //given + Optional value = Optional.empty(); + + //when + List collect = value.stream().map(String::toUpperCase).collect(Collectors.toList()); + + //then + assertThat(collect).isEmpty(); + } + + @Test + public void givenOptional_whenPresent_thenShouldExecuteProperCallback() { + //given + Optional value = Optional.of("properValue"); + AtomicInteger successCounter = new AtomicInteger(0); + AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0); + + //when + value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet); + + //then + assertThat(successCounter.get()).isEqualTo(1); + assertThat(onEmptyOptionalCounter.get()).isEqualTo(0); + } + + @Test + public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() { + //given + Optional value = Optional.empty(); + AtomicInteger successCounter = new AtomicInteger(0); + AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0); + + //when + value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet); + + //then + assertThat(successCounter.get()).isEqualTo(0); + assertThat(onEmptyOptionalCounter.get()).isEqualTo(1); + } + + @Test + public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() { + //given + String expected = "properValue"; + Optional value = Optional.of(expected); + Optional defaultValue = Optional.of("default"); + + //when + Optional result = value.or(() -> defaultValue); + + //then + assertThat(result.get()).isEqualTo(expected); + } + + @Test + public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() { + //given + String defaultString = "default"; + Optional value = Optional.empty(); + Optional defaultValue = Optional.of(defaultString); + + //when + Optional result = value.or(() -> defaultValue); + + //then + assertThat(result.get()).isEqualTo(defaultString); + } +} \ No newline at end of file diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 8dc25427d9..a94f74c115 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -192,7 +192,7 @@ 1.5.0-RELEASE 3.3.1 1.5.6.RELEASE - 2.4.0 + 2.8.0 2.0.4.RELEASE 3.1 diff --git a/jackson-modules/jackson-annotations/pom.xml b/jackson-modules/jackson-annotations/pom.xml index e2d5e1e607..59d7d3d197 100644 --- a/jackson-modules/jackson-annotations/pom.xml +++ b/jackson-modules/jackson-annotations/pom.xml @@ -21,7 +21,7 @@ io.rest-assured json-path - ${rest-assured.version} + ${json-path.version} test @@ -59,7 +59,7 @@ 2.1.214 - 3.1.1 + 5.3.2 2.5.0 diff --git a/json-modules/json-path/pom.xml b/json-modules/json-path/pom.xml index 88b81dfc68..763a275290 100644 --- a/json-modules/json-path/pom.xml +++ b/json-modules/json-path/pom.xml @@ -13,7 +13,6 @@ - com.jayway.jsonpath json-path @@ -22,8 +21,7 @@ - - 2.4.0 + 2.8.0 \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-5/pom.xml b/spring-web-modules/spring-mvc-basics-5/pom.xml index e0d603e303..1c8c87a2ef 100644 --- a/spring-web-modules/spring-mvc-basics-5/pom.xml +++ b/spring-web-modules/spring-mvc-basics-5/pom.xml @@ -82,7 +82,7 @@ 1.3.2 - 2.7.0 + 2.8.0 2.3.5 2.0.0 3.0.0 diff --git a/spring-web-modules/spring-mvc-java/pom.xml b/spring-web-modules/spring-mvc-java/pom.xml index 8098f07282..717c3b76b8 100644 --- a/spring-web-modules/spring-mvc-java/pom.xml +++ b/spring-web-modules/spring-mvc-java/pom.xml @@ -237,7 +237,7 @@ 4.0.1 2.3.3 2.32 - 2.4.0 + 2.8.0 com.baeldung.SpringMVCApplication diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index eaec50c1f7..f6a2e6928a 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -120,7 +120,7 @@ 3.0.1 3.0.0 2.2.6 - 3.0.1 + 5.3.2 \ No newline at end of file From fc91dd633712953b632249dda9d78f1ef9a75c3c Mon Sep 17 00:00:00 2001 From: gaepi Date: Sun, 12 Nov 2023 16:01:21 +0100 Subject: [PATCH 188/233] JAVA-27462 | removing spring security deprecations. --- .../src/main/java/com/baeldung/keycloak/SecurityConfig.java | 4 +++- .../com/baeldung/keycloaksoap/KeycloakSecurityConfig.java | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java index eb7767480f..5b9ce9677a 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -4,6 +4,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.Customizer; 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; @@ -53,7 +54,8 @@ class SecurityConfig { .hasRole("USER") .anyRequest() .authenticated(); - http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); + http.oauth2ResourceServer((oauth2) -> oauth2 + .jwt(Customizer.withDefaults())); return http.build(); } diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java index e55d307e33..70b306eaee 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java @@ -3,6 +3,7 @@ package com.baeldung.keycloaksoap; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.Customizer; 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; @@ -21,7 +22,8 @@ public class KeycloakSecurityConfig { .disable() .authorizeHttpRequests(auth -> auth.anyRequest() .authenticated()) - .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); + .oauth2ResourceServer((oauth2) -> oauth2 + .jwt(Customizer.withDefaults())); return http.build(); } } From b0a0d8c2475932c6eab0d46ae20294ccfe956e3d Mon Sep 17 00:00:00 2001 From: gaepi Date: Sun, 12 Nov 2023 16:13:39 +0100 Subject: [PATCH 189/233] JAVA-27461 | removing spring security deprecations. --- .../com/baeldung/keycloaksoap/KeycloakSecurityConfig.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java index 70b306eaee..77ffc6a5b4 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java @@ -7,6 +7,7 @@ import org.springframework.security.config.Customizer; 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.configurers.AbstractHttpConfigurer; import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; import org.springframework.security.web.SecurityFilterChain; @@ -18,8 +19,7 @@ public class KeycloakSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.csrf() - .disable() + http.csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth.anyRequest() .authenticated()) .oauth2ResourceServer((oauth2) -> oauth2 From aed73f72f5458591646d6bc48747c037ab1f43d9 Mon Sep 17 00:00:00 2001 From: gaepi Date: Sun, 12 Nov 2023 16:13:53 +0100 Subject: [PATCH 190/233] JAVA-27461 | removing spring security deprecations. --- .../java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java index 77ffc6a5b4..ff1cf0cb42 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java @@ -8,7 +8,6 @@ import org.springframework.security.config.annotation.method.configuration.Enabl 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.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; import org.springframework.security.web.SecurityFilterChain; @Configuration From e6cb1a2e43c3c84dbfc1799dda2bb0052f47b2aa Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 17:34:55 +0200 Subject: [PATCH 191/233] [JAVA-26714] Upgraded commons-codec to latest version --- algorithms-modules/pom.xml | 2 +- apache-httpclient4/pom.xml | 2 +- aws-modules/aws-miscellaneous/pom.xml | 2 +- aws-modules/aws-s3/pom.xml | 2 +- core-java-modules/core-java-networking-2/pom.xml | 2 +- core-java-modules/core-java-numbers-6/pom.xml | 2 +- core-java-modules/core-java-security-2/pom.xml | 2 +- core-java-modules/core-java-security-3/pom.xml | 2 +- core-java-modules/core-java-string-operations-2/pom.xml | 2 +- httpclient-simple/pom.xml | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/algorithms-modules/pom.xml b/algorithms-modules/pom.xml index 342662ce9c..fda8eea0e7 100644 --- a/algorithms-modules/pom.xml +++ b/algorithms-modules/pom.xml @@ -28,7 +28,7 @@ - 1.11 + 1.16.0 3.6.1 2.7 1.0.1 diff --git a/apache-httpclient4/pom.xml b/apache-httpclient4/pom.xml index f4c213687e..8b2fd76f0e 100644 --- a/apache-httpclient4/pom.xml +++ b/apache-httpclient4/pom.xml @@ -234,7 +234,7 @@ - 1.10 + 1.16.0 4.1.5 2.5.1 diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index 5fdd7fa04d..b6326b6eb1 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -75,7 +75,7 @@ 2.10.1 1.21.1 - 1.10.L001 + 1.16.0 0.9.4.0006L 3.1.1 diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml index e2bc04964a..6cbdadabae 100644 --- a/aws-modules/aws-s3/pom.xml +++ b/aws-modules/aws-s3/pom.xml @@ -62,7 +62,7 @@ 2.20.52 - 1.10.L001 + 1.16.0 0.9.4.0006L diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml index 34f16a9938..388e439e37 100644 --- a/core-java-modules/core-java-networking-2/pom.xml +++ b/core-java-modules/core-java-networking-2/pom.xml @@ -56,7 +56,7 @@ 2.4.5 2.3.3 2.0.0-alpha-3 - 1.15 + 1.16.0 \ No newline at end of file diff --git a/core-java-modules/core-java-numbers-6/pom.xml b/core-java-modules/core-java-numbers-6/pom.xml index 7a3b3d4426..66e16c8030 100644 --- a/core-java-modules/core-java-numbers-6/pom.xml +++ b/core-java-modules/core-java-numbers-6/pom.xml @@ -42,7 +42,7 @@ - 1.15 + 1.16.0 32.1.2-jre \ No newline at end of file diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml index 0fc121c070..05cd727638 100644 --- a/core-java-modules/core-java-security-2/pom.xml +++ b/core-java-modules/core-java-security-2/pom.xml @@ -34,7 +34,7 @@ 1.60 - 1.11 + 1.16.0 2.3.1 diff --git a/core-java-modules/core-java-security-3/pom.xml b/core-java-modules/core-java-security-3/pom.xml index b979b56658..4633ba02e3 100644 --- a/core-java-modules/core-java-security-3/pom.xml +++ b/core-java-modules/core-java-security-3/pom.xml @@ -44,7 +44,7 @@ 1.70 - 1.15 + 1.16.0 2.3.1 6.0.3 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 383a3b4a40..27071e5427 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -87,7 +87,7 @@ 8.0.1.Final 5.0.0 - 1.14 + 1.16.0 5.3.0 diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index a6049432ce..8cbc1237c2 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -205,7 +205,7 @@ 17 - 1.10 + 1.16.0 2.5.1 From d1675a28f48eaad3e8690fdab14ce4890d408764 Mon Sep 17 00:00:00 2001 From: gaepi Date: Sun, 12 Nov 2023 16:45:31 +0100 Subject: [PATCH 192/233] JAVA-27461 | removing deprecations. --- spring-reactive-modules/spring-5-reactive/pom.xml | 0 .../webflux/functional/EmployeeFunctionalConfig.java | 9 ++++----- 2 files changed, 4 insertions(+), 5 deletions(-) delete mode 100644 spring-reactive-modules/spring-5-reactive/pom.xml diff --git a/spring-reactive-modules/spring-5-reactive/pom.xml b/spring-reactive-modules/spring-5-reactive/pom.xml deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-reactive-modules/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java b/spring-reactive-modules/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java index e6f8ba35c2..7775f61467 100644 --- a/spring-reactive-modules/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java +++ b/spring-reactive-modules/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java @@ -53,11 +53,10 @@ public class EmployeeFunctionalConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http.csrf() - .disable() - .authorizeExchange() - .anyExchange() - .permitAll(); + http.csrf(csrf -> csrf.disable()) + .authorizeExchange( + exchanges -> exchanges.anyExchange().permitAll() + ); return http.build(); } } \ No newline at end of file From fe7f89a08fbadbd8e87f518fc82f243b8cc807db Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 17:46:52 +0200 Subject: [PATCH 193/233] [JAVA-26714] Upgraded bouncycastle to latest version --- core-java-modules/core-java-security-2/pom.xml | 4 ++-- core-java-modules/core-java-security-3/pom.xml | 4 ++-- core-java-modules/core-java-security-4/pom.xml | 4 ++-- libraries-security/pom.xml | 6 +++--- .../oauth2-authorization-server/pom.xml | 11 +++++------ 5 files changed, 14 insertions(+), 15 deletions(-) diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml index 05cd727638..b54afc31d8 100644 --- a/core-java-modules/core-java-security-2/pom.xml +++ b/core-java-modules/core-java-security-2/pom.xml @@ -21,7 +21,7 @@ org.bouncycastle - bcprov-jdk15on + bcprov-jdk18on ${bouncycastle.version} @@ -33,7 +33,7 @@ - 1.60 + 1.76 1.16.0 2.3.1 diff --git a/core-java-modules/core-java-security-3/pom.xml b/core-java-modules/core-java-security-3/pom.xml index 4633ba02e3..dae570e51d 100644 --- a/core-java-modules/core-java-security-3/pom.xml +++ b/core-java-modules/core-java-security-3/pom.xml @@ -21,7 +21,7 @@ org.bouncycastle - bcprov-jdk15on + bcprov-jdk18on ${bouncycastle.version} @@ -43,7 +43,7 @@ - 1.70 + 1.76 1.16.0 2.3.1 6.0.3 diff --git a/core-java-modules/core-java-security-4/pom.xml b/core-java-modules/core-java-security-4/pom.xml index 2b9809b749..a4700c34ba 100644 --- a/core-java-modules/core-java-security-4/pom.xml +++ b/core-java-modules/core-java-security-4/pom.xml @@ -16,7 +16,7 @@ org.bouncycastle - bcpkix-jdk15on + bcpkix-jdk18on ${bouncycastle.version} @@ -27,7 +27,7 @@ - 1.70 + 1.76 1.2.6 diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index 62c476a82c..969f14ec43 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -40,12 +40,12 @@ org.bouncycastle - bcprov-jdk15on + bcprov-jdk18on ${bouncycastle.version} org.bouncycastle - bcpkix-jdk15on + bcpkix-jdk18on ${bouncycastle.version} @@ -122,7 +122,7 @@ 1.2.2 1.2.2 1.9.2 - 1.58 + 1.76 0.1.55 2.5.1 2.4.0.RELEASE diff --git a/security-modules/oauth2-framework-impl/oauth2-authorization-server/pom.xml b/security-modules/oauth2-framework-impl/oauth2-authorization-server/pom.xml index 7f13e5acea..1ebbb5e10f 100644 --- a/security-modules/oauth2-framework-impl/oauth2-authorization-server/pom.xml +++ b/security-modules/oauth2-framework-impl/oauth2-authorization-server/pom.xml @@ -21,13 +21,13 @@ org.bouncycastle - bcprov-jdk15on - ${bcprov-jdk15on.version} + bcprov-jdk18on + ${bouncycastle.version} org.bouncycastle - bcpkix-jdk15on - ${bcpkix-jdk15on.version} + bcpkix-jdk18on + ${bouncycastle.version} @@ -69,8 +69,7 @@ 9080 9443 7.3 - 1.62 - 1.62 + 1.76 \ No newline at end of file From c0a9532c647bfee5f6a68d6e4550636940cbd4de Mon Sep 17 00:00:00 2001 From: Lucian Snare Date: Sun, 12 Nov 2023 10:59:00 -0500 Subject: [PATCH 194/233] BAEL-6790: Write and Read file with HashMap (#15087) * Add examples for reading and writing a HashMap from a file * Add test for gson --- .../core-java-collections-maps-7/README.md | 4 +- .../core-java-collections-maps-7/pom.xml | 65 ++------- .../map/readandwritefile/Student.java | 51 +++++++ .../ReadAndWriteFileWithHashMapUnitTest.java | 135 ++++++++++++++++++ 4 files changed, 199 insertions(+), 56 deletions(-) create mode 100644 core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/readandwritefile/Student.java create mode 100644 core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/readandwritefile/ReadAndWriteFileWithHashMapUnitTest.java 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 2e1531050e..a62bdda7af 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -1,5 +1,7 @@ -## Relevant Articles +## Relevant Articles: - [Difference Between putIfAbsent() and computeIfAbsent() in Java’s Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent) +- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/how-to-write-and-read-a-file-with-a-java-hashmap/) - [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 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 cefee201cc..a7acded9cf 100644 --- a/core-java-modules/core-java-collections-maps-7/pom.xml +++ b/core-java-modules/core-java-collections-maps-7/pom.xml @@ -1,11 +1,15 @@ + 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 @@ -13,72 +17,24 @@ 0.0.1-SNAPSHOT - - 5.2.5.RELEASE - com.fasterxml.jackson.core jackson-databind - 2.12.4 - - - org.openjdk.jmh - jmh-core - 1.36 + ${jackson.version} com.google.code.gson gson - 2.8.9 - - - org.json - json - 20230227 - - - junit - junit - 4.13.1 - test - - - org.junit.jupiter - junit-jupiter - 5.8.1 - test - - - org.junit.jupiter - junit-jupiter - 5.8.1 - test - - - junit - junit - 4.13.1 - test - - - org.junit.jupiter - junit-jupiter - 5.8.1 - test - - - junit - junit - 4.13.1 - test + ${gson.version} org.apache.commons commons-csv - 1.5 + ${csv.version} + @@ -92,5 +48,4 @@ - diff --git a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/readandwritefile/Student.java b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/readandwritefile/Student.java new file mode 100644 index 0000000000..b981de6300 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/readandwritefile/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.map.readandwritefile; + +import java.io.Serializable; +import java.util.Objects; + +public class Student implements Serializable { + private static final long serialVersionUID = 1L; + private String firstName; + private String lastName; + + /** Default constructor for JSON serialization */ + public Student() { + + } + + public Student(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Student student = (Student) o; + return Objects.equals(firstName, student.firstName) && Objects.equals(lastName, student.lastName); + } + + @Override + public int hashCode() { + return super.hashCode(); + } +} diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/readandwritefile/ReadAndWriteFileWithHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/readandwritefile/ReadAndWriteFileWithHashMapUnitTest.java new file mode 100644 index 0000000000..56867d3885 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/readandwritefile/ReadAndWriteFileWithHashMapUnitTest.java @@ -0,0 +1,135 @@ +package com.baeldung.map.readandwritefile; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import org.junit.After; +import org.junit.Test; +import org.junit.Before; + +public class ReadAndWriteFileWithHashMapUnitTest { + + private static final Map STUDENT_DATA = new HashMap<>(); + + static { + STUDENT_DATA.put(1234, new Student("Henry", "Winter")); + STUDENT_DATA.put(5678, new Student("Richard", "Papen")); + } + + private File file; + + @Before + public void createFile() throws IOException { + file = File.createTempFile("student", ".data"); + } + + @After + public void deleteFile() { + file.delete(); + } + + @Test + public void givenHashMap_whenWrittenAsPropertiesFile_thenReloadedMapIsIdentical() throws IOException { + // Given a map containing student data + Map studentData = new HashMap<>(); + studentData.put("student.firstName", "Henry"); + studentData.put("student.lastName", "Winter"); + + // When converting to a Properties object and writing to a file + Properties props = new Properties(); + props.putAll(studentData); + try (OutputStream output = Files.newOutputStream(file.toPath())) { + props.store(output, null); + } + + // Then the map resulting from loading the Properties file is identical + Properties propsFromFile = new Properties(); + try (InputStream input = Files.newInputStream(file.toPath())) { + propsFromFile.load(input); + } + + Map studentDataFromProps = propsFromFile.stringPropertyNames() + .stream() + .collect(Collectors.toMap(key -> key, props::getProperty)); + assertThat(studentDataFromProps).isEqualTo(studentData); + } + + @Test + public void givenHashMap_whenSerializedToFile_thenDeserializedMapIsIdentical() throws IOException, ClassNotFoundException { + // Given a map containing student data (STUDENT_DATA) + + // When serializing the map to a file + try (FileOutputStream fileOutput = new FileOutputStream(file); ObjectOutputStream objectStream = new ObjectOutputStream(fileOutput)) { + objectStream.writeObject(STUDENT_DATA); + } + + // Then read the file back into a map and check the contents + Map studentsFromFile; + try (FileInputStream fileReader = new FileInputStream(file); ObjectInputStream objectStream = new ObjectInputStream(fileReader)) { + studentsFromFile = (HashMap) objectStream.readObject(); + } + assertThat(studentsFromFile).isEqualTo(STUDENT_DATA); + } + + @Test + public void givenHashMap_whenSerializedToFileWithJackson_thenDeserializedMapIsIdentical() throws IOException { + // Given a map containing student data (STUDENT_DATA) + + // When converting to JSON with Jackson and writing to a file + ObjectMapper mapper = new ObjectMapper(); + try (FileOutputStream fileOutput = new FileOutputStream(file)) { + mapper.writeValue(fileOutput, STUDENT_DATA); + } + + // Then deserialize the file back into a map and check that it's identical + Map mapFromFile; + try (FileInputStream fileInput = new FileInputStream(file)) { + // Create a TypeReference so we can deserialize the parameterized type + TypeReference> mapType = new TypeReference>() { + }; + mapFromFile = mapper.readValue(fileInput, mapType); + } + assertThat(mapFromFile).isEqualTo(STUDENT_DATA); + } + + @Test + public void givenHashMap_whenSerializedToFileWithGson_thenDeserializedMapIsIdentical() throws IOException { + // Given a map containing student data (STUDENT_DATA) + + // When converting to JSON using Gson and writing to a file + Gson gson = new Gson(); + try (FileWriter writer = new FileWriter(file)) { + gson.toJson(STUDENT_DATA, writer); + } + + // Then deserialize the file back into a map and check that it's identical + Map studentsFromFile; + try (FileReader reader = new FileReader(file)) { + Type mapType = new TypeToken>() { + }.getType(); + studentsFromFile = gson.fromJson(reader, mapType); + } + assertThat(studentsFromFile).isEqualTo(STUDENT_DATA); + } +} From 2c7a0d05e2a823cc74889d9e3ced74538f7c0bf0 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 18:00:46 +0200 Subject: [PATCH 195/233] [JAVA-26714] Clean up of commons-lang3 --- core-java-modules/core-java-collections-4/pom.xml | 1 - core-java-modules/core-java-collections-list-5/pom.xml | 1 - core-java-modules/core-java-date-operations-3/pom.xml | 1 - core-java-modules/core-java-function/pom.xml | 1 - core-java-modules/core-java-functional/pom.xml | 1 - core-java-modules/core-java-lang-5/pom.xml | 1 - core-java-modules/core-java-reflection/pom.xml | 1 - core-java-modules/core-java-string-algorithms-3/pom.xml | 1 - core-java-modules/core-java-string-operations-3/pom.xml | 1 - core-java-modules/core-java-string-operations-4/pom.xml | 7 +++---- 10 files changed, 3 insertions(+), 13 deletions(-) diff --git a/core-java-modules/core-java-collections-4/pom.xml b/core-java-modules/core-java-collections-4/pom.xml index 1a59411ecb..344ec6bc41 100644 --- a/core-java-modules/core-java-collections-4/pom.xml +++ b/core-java-modules/core-java-collections-4/pom.xml @@ -34,7 +34,6 @@ 2.2 - 3.12.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 2b4b0041b3..b8832df357 100644 --- a/core-java-modules/core-java-collections-list-5/pom.xml +++ b/core-java-modules/core-java-collections-list-5/pom.xml @@ -66,7 +66,6 @@ 1.21 2.2 - 3.12.0 2.10.1 2.15.2 20230618 diff --git a/core-java-modules/core-java-date-operations-3/pom.xml b/core-java-modules/core-java-date-operations-3/pom.xml index 9b7be18b85..8e4740785c 100644 --- a/core-java-modules/core-java-date-operations-3/pom.xml +++ b/core-java-modules/core-java-date-operations-3/pom.xml @@ -28,7 +28,6 @@ 2.12.5 - 3.12.0 \ No newline at end of file diff --git a/core-java-modules/core-java-function/pom.xml b/core-java-modules/core-java-function/pom.xml index e8b538ad24..4110b8f6d9 100644 --- a/core-java-modules/core-java-function/pom.xml +++ b/core-java-modules/core-java-function/pom.xml @@ -51,7 +51,6 @@ 3.8.0 3.22.0 - 3.12.0 0.10.4 diff --git a/core-java-modules/core-java-functional/pom.xml b/core-java-modules/core-java-functional/pom.xml index 4b0bf9f730..3b21dd6e8a 100644 --- a/core-java-modules/core-java-functional/pom.xml +++ b/core-java-modules/core-java-functional/pom.xml @@ -35,7 +35,6 @@ 3.8.0 3.22.0 - 3.12.0 0.10.4 diff --git a/core-java-modules/core-java-lang-5/pom.xml b/core-java-modules/core-java-lang-5/pom.xml index 8e95fc4405..b65f061fc7 100644 --- a/core-java-modules/core-java-lang-5/pom.xml +++ b/core-java-modules/core-java-lang-5/pom.xml @@ -24,7 +24,6 @@ - 3.12.0 0.10.2 diff --git a/core-java-modules/core-java-reflection/pom.xml b/core-java-modules/core-java-reflection/pom.xml index a836ee4a22..f77c791936 100644 --- a/core-java-modules/core-java-reflection/pom.xml +++ b/core-java-modules/core-java-reflection/pom.xml @@ -52,7 +52,6 @@ 1.8 1.8 0.10.2 - 3.12.0 \ No newline at end of file diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 507e830e8a..c47967a29f 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -61,7 +61,6 @@ 11 11 1.7 - 3.12.0 5.1.1 1.10.0 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 39167271fa..7795d164a1 100644 --- a/core-java-modules/core-java-string-operations-3/pom.xml +++ b/core-java-modules/core-java-string-operations-3/pom.xml @@ -70,7 +70,6 @@ 11 11 5.3.9 - 3.12.0 3.6.3 6.1.1 2.11.1 diff --git a/core-java-modules/core-java-string-operations-4/pom.xml b/core-java-modules/core-java-string-operations-4/pom.xml index 27c2bf91bd..b9591763a0 100644 --- a/core-java-modules/core-java-string-operations-4/pom.xml +++ b/core-java-modules/core-java-string-operations-4/pom.xml @@ -27,12 +27,12 @@ org.apache.commons commons-lang3 - ${apache-commons-lang3.version} + ${commons-lang3.version} org.apache.commons commons-text - ${apache-commons-text.version} + ${commons-text.version} org.assertj @@ -60,8 +60,7 @@ 11 5.8 5.3.13 - 3.12.0 - 1.10.0 + 1.10.0 \ No newline at end of file From 573df300b06ea130e8d4762c71f4072ab0cfd81c Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Sun, 12 Nov 2023 09:00:56 -0700 Subject: [PATCH 196/233] Fix indentation issues --- .../atomicinteger/Employee.java | 3 +- .../synchronizestatic/none/Employee.java | 3 +- .../reentrantlock/Employee.java | 3 +- .../synchronizedblock/Employee.java | 3 +- .../synchronizedclass/Employee.java | 3 +- .../SychronizeStaticDataUnitTest.java | 38 ++++++++----------- 6 files changed, 21 insertions(+), 32 deletions(-) diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java index 9c3c9b987c..bb7c1c6b4c 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/atomicinteger/Employee.java @@ -13,8 +13,7 @@ public class Employee { String name; String title; - public Employee(int id, String name, String title) - { + public Employee(int id, String name, String title) { incrementCount(); this.id = id; this.name = name; diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/none/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/none/Employee.java index f050a68be4..ba722e15e9 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/none/Employee.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/none/Employee.java @@ -10,8 +10,7 @@ public class Employee { String name; String title; - public Employee(int id, String name, String title) - { + public Employee(int id, String name, String title) { incrementCount(); this.id = id; this.name = name; diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/reentrantlock/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/reentrantlock/Employee.java index 2ac0b0d3f2..e74013ad0e 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/reentrantlock/Employee.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/reentrantlock/Employee.java @@ -14,8 +14,7 @@ public class Employee { String name; String title; - public Employee(int id, String name, String title) - { + public Employee(int id, String name, String title) { incrementCount(); this.id = id; this.name = name; diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedblock/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedblock/Employee.java index 9c078e7abe..4cf04e5b06 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedblock/Employee.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedblock/Employee.java @@ -12,8 +12,7 @@ public class Employee { String name; String title; - public Employee(int id, String name, String title) - { + public Employee(int id, String name, String title) { incrementCount(); this.id = id; this.name = name; diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java index a69b633f3b..627040e88c 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java @@ -10,8 +10,7 @@ public class Employee String name; String title; - public Employee(int id, String name, String title) - { + public Employee(int id, String name, String title) { incrementCount(); this.id = id; this.name = name; diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java index e633005c6f..b4e03673a1 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java @@ -11,8 +11,7 @@ import java.util.concurrent.Executors; * package. When not synchronized the out will not be sequential; * when it is synchronized the output will be in sequential. */ -public class SychronizeStaticDataUnitTest -{ +public class SychronizeStaticDataUnitTest { private final Executor pool = Executors.newFixedThreadPool(4); private final int numberToTest = 100; @@ -24,10 +23,9 @@ public class SychronizeStaticDataUnitTest for(int i = 0; i < numberToTest; i++) { int finalI = i; - pool.execute(() -> - { - new com.baeldung.concurrent.synchronizestatic.none.Employee(finalI, "John", "Smith"); - }); + pool.execute(() -> { + new com.baeldung.concurrent.synchronizestatic.none.Employee(finalI, "John", "Smith"); + }); } } @@ -38,10 +36,9 @@ public class SychronizeStaticDataUnitTest for(int i = 0; i < numberToTest; i++) { int finalI = i; - pool.execute(() -> - { - new com.baeldung.concurrent.synchronizestatic.synchronizedmethod.Employee(finalI, "John", "Smith"); - }); + pool.execute(() -> { + new com.baeldung.concurrent.synchronizestatic.synchronizedmethod.Employee(finalI, "John", "Smith"); + }); } } @@ -52,10 +49,9 @@ public class SychronizeStaticDataUnitTest for(int i = 0; i < numberToTest; i++) { int finalI = i; - pool.execute(() -> - { - new com.baeldung.concurrent.synchronizestatic.synchronizedclass.Employee(finalI, "John", "Smith"); - }); + pool.execute(() -> { + new com.baeldung.concurrent.synchronizestatic.synchronizedclass.Employee(finalI, "John", "Smith"); + }); } } @@ -66,10 +62,9 @@ public class SychronizeStaticDataUnitTest for(int i = 0; i < numberToTest; i++) { int finalI = i; - pool.execute(() -> - { - new com.baeldung.concurrent.synchronizestatic.synchronizedblock.Employee(finalI, "John", "Smith"); - }); + pool.execute(() -> { + new com.baeldung.concurrent.synchronizestatic.synchronizedblock.Employee(finalI, "John", "Smith"); + }); } } @@ -87,10 +82,9 @@ public class SychronizeStaticDataUnitTest for(int i = 0; i < numberToTest; i++) { int finalI = i; - pool.execute(() -> - { - new com.baeldung.concurrent.synchronizestatic.reentrantlock.Employee(finalI, "John", "Smith"); - }); + pool.execute(() -> { + new com.baeldung.concurrent.synchronizestatic.reentrantlock.Employee(finalI, "John", "Smith"); + }); } } } From daea7e1edc1f746e4c1a1a3afc3c6ba5637a7033 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 18:03:56 +0200 Subject: [PATCH 197/233] [JAVA-26714] Revert typo --- aws-modules/aws-s3/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml index 6cbdadabae..e2bc04964a 100644 --- a/aws-modules/aws-s3/pom.xml +++ b/aws-modules/aws-s3/pom.xml @@ -62,7 +62,7 @@ 2.20.52 - 1.16.0 + 1.10.L001 0.9.4.0006L From 39c2f491713a429cd5f9c5b3b45eb62165ed0a0e Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 12 Nov 2023 18:10:31 +0200 Subject: [PATCH 198/233] [JAVA-26714] Upgraded guava to latest version --- core-java-modules/core-java-numbers-6/pom.xml | 1 - core-java-modules/core-java-streams-5/pom.xml | 1 - docker-modules/docker-caching/multi-module-caching/pom.xml | 2 +- docker-modules/docker-caching/single-module-caching/pom.xml | 2 +- json-modules/json-conversion/pom.xml | 1 - pom.xml | 2 +- spring-web-modules/spring-rest-http-2/pom.xml | 1 - 7 files changed, 3 insertions(+), 7 deletions(-) diff --git a/core-java-modules/core-java-numbers-6/pom.xml b/core-java-modules/core-java-numbers-6/pom.xml index 66e16c8030..34e53056a4 100644 --- a/core-java-modules/core-java-numbers-6/pom.xml +++ b/core-java-modules/core-java-numbers-6/pom.xml @@ -43,6 +43,5 @@ 1.16.0 - 32.1.2-jre \ No newline at end of file diff --git a/core-java-modules/core-java-streams-5/pom.xml b/core-java-modules/core-java-streams-5/pom.xml index d7baf84d30..e217271f4c 100644 --- a/core-java-modules/core-java-streams-5/pom.xml +++ b/core-java-modules/core-java-streams-5/pom.xml @@ -77,7 +77,6 @@ 12 12 0.10.2 - 32.1.2-jre \ 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 60f14a17e5..bebfb85e8a 100644 --- a/docker-modules/docker-caching/multi-module-caching/pom.xml +++ b/docker-modules/docker-caching/multi-module-caching/pom.xml @@ -27,7 +27,7 @@ UTF-8 1.8 - 32.1.2-jre + 32.1.3-jre \ No newline at end of file diff --git a/docker-modules/docker-caching/single-module-caching/pom.xml b/docker-modules/docker-caching/single-module-caching/pom.xml index 0e5174b7ca..bb44c21e10 100644 --- a/docker-modules/docker-caching/single-module-caching/pom.xml +++ b/docker-modules/docker-caching/single-module-caching/pom.xml @@ -49,7 +49,7 @@ 8 8 UTF-8 - 32.1.2-jre + 32.1.3-jre \ No newline at end of file diff --git a/json-modules/json-conversion/pom.xml b/json-modules/json-conversion/pom.xml index 638216f4c5..9eebac16b4 100644 --- a/json-modules/json-conversion/pom.xml +++ b/json-modules/json-conversion/pom.xml @@ -38,7 +38,6 @@ 2.10.1 - 32.1.2-jre diff --git a/pom.xml b/pom.xml index 47c566023d..7099dd8cbc 100644 --- a/pom.xml +++ b/pom.xml @@ -1236,7 +1236,7 @@ 3.21.0 1.18.28 2.1.214 - 32.1.2-jre + 32.1.3-jre 3.3.0 diff --git a/spring-web-modules/spring-rest-http-2/pom.xml b/spring-web-modules/spring-rest-http-2/pom.xml index 88294c7811..bcacdbbdb1 100644 --- a/spring-web-modules/spring-rest-http-2/pom.xml +++ b/spring-web-modules/spring-rest-http-2/pom.xml @@ -53,7 +53,6 @@ 2.9.2 1.6.1 1.7.0 - 31.0.1-jre \ No newline at end of file From ffe2c5780ebad433ca55f67e5b53f5251b9e8f3e Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Mon, 13 Nov 2023 12:05:47 +0530 Subject: [PATCH 199/233] JAVA-27194 Upgarde hibernate validator version in spring-mvc-java --- spring-web-modules/spring-mvc-java/pom.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/spring-web-modules/spring-mvc-java/pom.xml b/spring-web-modules/spring-mvc-java/pom.xml index 8098f07282..745a6f45c0 100644 --- a/spring-web-modules/spring-mvc-java/pom.xml +++ b/spring-web-modules/spring-mvc-java/pom.xml @@ -101,7 +101,6 @@ org.hibernate.validator hibernate-validator - ${hibernate-validator.version} org.glassfish @@ -217,8 +216,6 @@ 6.0.10.Final 5.1.40 - - 6.0.10.Final 2.2.0 From 7465581d605e220bb4064d2b62d3f892ab4c8c28 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Mon, 13 Nov 2023 09:44:21 +0200 Subject: [PATCH 200/233] [JAVA-26714] --- core-java-modules/core-java-string-algorithms-3/pom.xml | 1 - core-java-modules/core-java-string-operations-3/pom.xml | 1 - 2 files changed, 2 deletions(-) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index c47967a29f..96bb824f84 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -21,7 +21,6 @@ org.apache.commons commons-lang3 - ${apache-commons-lang3.version} com.vdurmont 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 7795d164a1..ce58669ba0 100644 --- a/core-java-modules/core-java-string-operations-3/pom.xml +++ b/core-java-modules/core-java-string-operations-3/pom.xml @@ -22,7 +22,6 @@ org.apache.commons commons-lang3 - ${apache-commons-lang3.version} org.apache.maven From 0415bc0ec7093073f1fe4960dbc491ef2733ed11 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Mon, 13 Nov 2023 09:48:20 +0200 Subject: [PATCH 201/233] [JAVA-26714] --- core-java-modules/core-java-string-algorithms-3/pom.xml | 1 + core-java-modules/core-java-string-operations-3/pom.xml | 1 + 2 files changed, 2 insertions(+) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 96bb824f84..548a3dc3f8 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -21,6 +21,7 @@ org.apache.commons commons-lang3 + ${commons-lang3.version} com.vdurmont 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 ce58669ba0..0558e71a35 100644 --- a/core-java-modules/core-java-string-operations-3/pom.xml +++ b/core-java-modules/core-java-string-operations-3/pom.xml @@ -22,6 +22,7 @@ org.apache.commons commons-lang3 + ${commons-lang3.version} org.apache.maven From 72391c6947feb37c1bf2783a57e7fe5ed9c7d246 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Mon, 13 Nov 2023 14:52:49 +0530 Subject: [PATCH 202/233] JAVA-27194 Upgrade hibernate validator version in spring-mvc-xml-2 --- spring-web-modules/spring-mvc-xml-2/pom.xml | 29 ++++++++----------- .../ConstraintViolationExceptionHandler.java | 2 +- ...stAndPathVariableValidationController.java | 10 +++---- .../baeldung/spring/taglibrary/Person.java | 2 +- .../spring/taglibrary/PersonController.java | 2 +- 5 files changed, 20 insertions(+), 25 deletions(-) diff --git a/spring-web-modules/spring-mvc-xml-2/pom.xml b/spring-web-modules/spring-mvc-xml-2/pom.xml index 8c0062f538..49590758cc 100644 --- a/spring-web-modules/spring-mvc-xml-2/pom.xml +++ b/spring-web-modules/spring-mvc-xml-2/pom.xml @@ -10,8 +10,9 @@ com.baeldung - spring-web-modules + parent-spring-6 0.0.1-SNAPSHOT + ../../parent-spring-6 @@ -19,26 +20,18 @@ org.springframework spring-web - ${spring.version} org.springframework spring-webmvc - ${spring.version} - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} + jakarta.servlet + jakarta.servlet-api + ${jakarta.servlet-api.version} provided - - javax.servlet - jstl - ${jstl.version} - runtime - org.hibernate.validator hibernate-validator @@ -57,9 +50,9 @@ ${commons-io.version} - org.glassfish - javax.el - ${javax.el.version} + org.glassfish.expressly + expressly + ${expressly.version} org.springframework.boot @@ -98,9 +91,11 @@ 5.1.40 4.4.5 4.5.2 - 6.0.10.Final - 3.0.1-b08 + 8.0.1.Final + 5.0.0 1.6.1 + 6.0.0 + 3.1.5 \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java index 645b36c2a5..d3d833a696 100644 --- a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java @@ -8,7 +8,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; -import javax.validation.ConstraintViolationException; +import jakarta.validation.ConstraintViolationException; @ControllerAdvice public class ConstraintViolationExceptionHandler extends ResponseEntityExceptionHandler { diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationController.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationController.java index 4768237871..e1842564ac 100644 --- a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationController.java +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationController.java @@ -7,11 +7,11 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; @Controller @RequestMapping("/public/api/1") diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/Person.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/Person.java index ed2fa903ef..a08f0f515c 100644 --- a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/Person.java +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/Person.java @@ -2,7 +2,7 @@ package com.baeldung.spring.taglibrary; import java.util.List; -import javax.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotEmpty; import org.springframework.web.multipart.MultipartFile; diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonController.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonController.java index 0fcb66f2dd..79e65b1fde 100644 --- a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonController.java +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonController.java @@ -10,7 +10,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import javax.validation.Valid; +import jakarta.validation.Valid; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; From 7d0c744c7c89d845b32cc4609fa98e40d876e2fd Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Mon, 13 Nov 2023 09:27:36 +0000 Subject: [PATCH 203/233] [JAVA-26433] Formatting (#15179) --- .../collectors/Java8CollectorsUnitTest.java | 155 ++++++++++-------- 1 file changed, 91 insertions(+), 64 deletions(-) diff --git a/core-java-modules/core-java-streams-simple/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java b/core-java-modules/core-java-streams-simple/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java index 085c1b5d7f..1faada9d23 100644 --- a/core-java-modules/core-java-streams-simple/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java +++ b/core-java-modules/core-java-streams-simple/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java @@ -3,6 +3,7 @@ package com.baeldung.streams.collectors; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; + import org.junit.Test; import java.util.*; @@ -23,142 +24,159 @@ public class Java8CollectorsUnitTest { private final List listWithDuplicates = Arrays.asList("a", "bb", "c", "d", "bb"); @Test - public void whenCollectingToList_shouldCollectToList() throws Exception { - final List result = givenList.stream().collect(toList()); + public void whenCollectingToList_shouldCollectToList() { + final List result = givenList.stream() + .collect(toList()); assertThat(result).containsAll(givenList); } @Test public void whenCollectingToUnmodifiableList_shouldCollectToUnmodifiableList() { - final List result = givenList.stream().collect(toUnmodifiableList()); + final List result = givenList.stream() + .collect(toUnmodifiableList()); - assertThatThrownBy(() -> result.add("foo")) - .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> result.add("foo")).isInstanceOf(UnsupportedOperationException.class); } @Test - public void whenCollectingToSet_shouldCollectToSet() throws Exception { - final Set result = givenList.stream().collect(toSet()); + public void whenCollectingToSet_shouldCollectToSet() { + final Set result = givenList.stream() + .collect(toSet()); assertThat(result).containsAll(givenList); } @Test public void whenCollectingToUnmodifiableSet_shouldCollectToUnmodifiableSet() { - final Set result = givenList.stream().collect(toUnmodifiableSet()); + final Set result = givenList.stream() + .collect(toUnmodifiableSet()); - assertThatThrownBy(() -> result.add("foo")) - .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> result.add("foo")).isInstanceOf(UnsupportedOperationException.class); } @Test public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception { - final Set result = listWithDuplicates.stream().collect(toSet()); + final Set result = listWithDuplicates.stream() + .collect(toSet()); assertThat(result).hasSize(4); } @Test - public void whenCollectingToCollection_shouldCollectToCollection() throws Exception { - final List result = givenList.stream().collect(toCollection(LinkedList::new)); + public void whenCollectingToCollection_shouldCollectToCollection() { + final List result = givenList.stream() + .collect(toCollection(LinkedList::new)); - assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class); + assertThat(result).containsAll(givenList) + .isInstanceOf(LinkedList.class); } @Test - public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception { + public void whenCollectingToImmutableCollection_shouldThrowException() { assertThatThrownBy(() -> { - givenList.stream().collect(toCollection(ImmutableList::of)); + givenList.stream() + .collect(toCollection(ImmutableList::of)); }).isInstanceOf(UnsupportedOperationException.class); } @Test - public void whenCollectingToMap_shouldCollectToMap() throws Exception { - final Map result = givenList.stream().collect(toMap(Function.identity(), String::length)); + public void whenCollectingToMap_shouldCollectToMap() { + final Map result = givenList.stream() + .collect(toMap(Function.identity(), String::length)); - assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); + assertThat(result).containsEntry("a", 1) + .containsEntry("bb", 2) + .containsEntry("ccc", 3) + .containsEntry("dd", 2); } @Test public void whenCollectingToUnmodifiableMap_shouldCollectToUnmodifiableMap() { final Map result = givenList.stream() - .collect(toUnmodifiableMap(Function.identity(), String::length)); + .collect(toUnmodifiableMap(Function.identity(), String::length)); - assertThatThrownBy(() -> result.put("foo", 3)) - .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> result.put("foo", 3)).isInstanceOf(UnsupportedOperationException.class); } @Test public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception { - final Map result = listWithDuplicates.stream().collect( - toMap( - Function.identity(), - String::length, - (item, identicalItem) -> item - ) - ); + final Map result = listWithDuplicates.stream() + .collect(toMap(Function.identity(), String::length, (item, identicalItem) -> item)); - assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("c", 1).containsEntry("d", 1); + assertThat(result).containsEntry("a", 1) + .containsEntry("bb", 2) + .containsEntry("c", 1) + .containsEntry("d", 1); } @Test - public void givenContainsDuplicateElements_whenCollectingToMap_shouldThrowException() throws Exception { + public void givenContainsDuplicateElements_whenCollectingToMap_shouldThrowException() { assertThatThrownBy(() -> { - listWithDuplicates.stream().collect(toMap(Function.identity(), String::length)); + listWithDuplicates.stream() + .collect(toMap(Function.identity(), String::length)); }).isInstanceOf(IllegalStateException.class); } @Test - public void whenCollectingAndThen_shouldCollect() throws Exception { - final List result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf)); + public void whenCollectingAndThen_shouldCollect() { + final List result = givenList.stream() + .collect(collectingAndThen(toList(), ImmutableList::copyOf)); - assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class); + assertThat(result).containsAll(givenList) + .isInstanceOf(ImmutableList.class); } @Test - public void whenJoining_shouldJoin() throws Exception { - final String result = givenList.stream().collect(joining()); + public void whenJoining_shouldJoin() { + final String result = givenList.stream() + .collect(joining()); assertThat(result).isEqualTo("abbcccdd"); } @Test - public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception { - final String result = givenList.stream().collect(joining(" ")); + public void whenJoiningWithSeparator_shouldJoinWithSeparator() { + final String result = givenList.stream() + .collect(joining(" ")); assertThat(result).isEqualTo("a bb ccc dd"); } @Test - public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception { - final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST")); + public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() { + final String result = givenList.stream() + .collect(joining(" ", "PRE-", "-POST")); assertThat(result).isEqualTo("PRE-a bb ccc dd-POST"); } @Test - public void whenPartitioningBy_shouldPartition() throws Exception { - final Map> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2)); + public void whenPartitioningBy_shouldPartition() { + final Map> result = givenList.stream() + .collect(partitioningBy(s -> s.length() > 2)); - assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> { - assertThat(booleanListMap.get(true)).contains("ccc"); + assertThat(result).containsKeys(true, false) + .satisfies(booleanListMap -> { + assertThat(booleanListMap.get(true)).contains("ccc"); - assertThat(booleanListMap.get(false)).contains("a", "bb", "dd"); - }); + assertThat(booleanListMap.get(false)).contains("a", "bb", "dd"); + }); } @Test - public void whenCounting_shouldCount() throws Exception { - final Long result = givenList.stream().collect(counting()); + public void whenCounting_shouldCount() { + final Long result = givenList.stream() + .collect(counting()); assertThat(result).isEqualTo(4); } @Test - public void whenSummarizing_shouldSummarize() throws Exception { - final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length)); + public void whenSummarizing_shouldSummarize() { + final DoubleSummaryStatistics result = givenList.stream() + .collect(summarizingDouble(String::length)); assertThat(result.getAverage()).isEqualTo(2); assertThat(result.getCount()).isEqualTo(4); @@ -168,38 +186,47 @@ public class Java8CollectorsUnitTest { } @Test - public void whenAveraging_shouldAverage() throws Exception { - final Double result = givenList.stream().collect(averagingDouble(String::length)); + public void whenAveraging_shouldAverage() { + final Double result = givenList.stream() + .collect(averagingDouble(String::length)); assertThat(result).isEqualTo(2); } @Test - public void whenSumming_shouldSum() throws Exception { - final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length)); + public void whenSumming_shouldSum() { + final Double result = givenList.stream() + .collect(summingDouble(String::length)); assertThat(result).isEqualTo(8); } @Test - public void whenMaxingBy_shouldMaxBy() throws Exception { - final Optional result = givenList.stream().collect(maxBy(Comparator.naturalOrder())); + public void whenMaxingBy_shouldMaxBy() { + final Optional result = givenList.stream() + .collect(maxBy(Comparator.naturalOrder())); - assertThat(result).isPresent().hasValue("dd"); + assertThat(result).isPresent() + .hasValue("dd"); } @Test - public void whenGroupingBy_shouldGroupBy() throws Exception { - final Map> result = givenList.stream().collect(groupingBy(String::length, toSet())); + public void whenGroupingBy_shouldGroupBy() { + final Map> result = givenList.stream() + .collect(groupingBy(String::length, toSet())); - assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc")); + assertThat(result).containsEntry(1, newHashSet("a")) + .containsEntry(2, newHashSet("bb", "dd")) + .containsEntry(3, newHashSet("ccc")); } @Test - public void whenCreatingCustomCollector_shouldCollect() throws Exception { - final ImmutableSet result = givenList.stream().collect(toImmutableSet()); + public void whenCreatingCustomCollector_shouldCollect() { + final ImmutableSet result = givenList.stream() + .collect(toImmutableSet()); - assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd"); + assertThat(result).isInstanceOf(ImmutableSet.class) + .contains("a", "bb", "ccc", "dd"); } From e82269d2069859be8ef9e1b253c5b95b7d34256e Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Mon, 13 Nov 2023 15:02:17 +0530 Subject: [PATCH 204/233] JAVA-27224 Upgrade parent-boot-3 to latest version of Boot (#15188) --- parent-boot-3/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-boot-3/pom.xml b/parent-boot-3/pom.xml index dabcd7850b..9f9d6f7901 100644 --- a/parent-boot-3/pom.xml +++ b/parent-boot-3/pom.xml @@ -230,7 +230,7 @@ 3.3.0 2.22.2 - 3.1.2 + 3.1.5 5.8.2 0.9.17 17 From 5040974af23bf29aec2fafb44ff94af538b7e026 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Mon, 13 Nov 2023 11:48:01 +0200 Subject: [PATCH 205/233] [JAVA-26714] --- libraries-security/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index 969f14ec43..8a6dad6da2 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -40,12 +40,12 @@ org.bouncycastle - bcprov-jdk18on + bcprov-jdk15on ${bouncycastle.version} org.bouncycastle - bcpkix-jdk18on + bcpkix-jdk15on ${bouncycastle.version} @@ -122,7 +122,7 @@ 1.2.2 1.2.2 1.9.2 - 1.76 + 1.68 0.1.55 2.5.1 2.4.0.RELEASE From 21eb70547f10f84ac1be2b903f8a6d00742253ff Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Mon, 13 Nov 2023 10:00:45 +0000 Subject: [PATCH 206/233] [JAVA-26719] Upgraded joda-time to latest version (#15189) --- .../core-java-8-datetime-2/pom.xml | 2 +- .../parsingDates/SimpleParseDate.java | 2 +- .../parsingDates/SimpleParseDateUnitTest.java | 42 +++++++++---------- .../core-java-8-datetime/pom.xml | 2 +- .../core-java-date-operations-1/pom.xml | 2 +- .../core-java-date-operations-2/pom.xml | 2 +- .../core-java-datetime-conversion/pom.xml | 2 +- json-modules/gson/pom.xml | 2 +- .../spring-data-couchbase-2/pom.xml | 2 +- spring-ejb-modules/ejb-beans/pom.xml | 2 +- spring-static-resources/pom.xml | 7 ---- testing-modules/rest-assured/pom.xml | 6 --- video-tutorials/jackson-annotations/pom.xml | 2 +- 13 files changed, 30 insertions(+), 45 deletions(-) diff --git a/core-java-modules/core-java-8-datetime-2/pom.xml b/core-java-modules/core-java-8-datetime-2/pom.xml index ce349d9dc3..02af06dc9d 100644 --- a/core-java-modules/core-java-8-datetime-2/pom.xml +++ b/core-java-modules/core-java-8-datetime-2/pom.xml @@ -55,7 +55,7 @@ 1.8 1.8 - 2.10 + 2.12.5 \ No newline at end of file diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java index cb024eea53..ba4f14ec5f 100644 --- a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java +++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java @@ -7,7 +7,7 @@ import java.util.List; public class SimpleParseDate { - public Date parseDate(String dateString, List formatStrings) { + public static Date parseDate(String dateString, List formatStrings) { for (String formatString : formatStrings) { try { return new SimpleDateFormat(formatString).parse(dateString); diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java index d7cbb6a834..ed8607fd96 100644 --- a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java @@ -1,43 +1,41 @@ package com.baeldung.parsingDates; -import com.baeldung.parsingDates.SimpleDateTimeFormat; -import com.baeldung.parsingDates.SimpleDateTimeFormater; -import com.baeldung.parsingDates.SimpleDateUtils; -import com.baeldung.parsingDates.SimpleParseDate; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.time.format.DateTimeParseException; import java.util.Arrays; -import org.junit.*; -import static org.junit.Assert.*; + import org.joda.time.LocalDate; +import org.junit.jupiter.api.Test; -public class SimpleParseDateUnitTest { +class SimpleParseDateUnitTest { @Test - public void whenInvalidInput_thenGettingUnexpectedResult() { - SimpleParseDate simpleParseDate = new SimpleParseDate(); + void whenInvalidInput_thenGettingUnexpectedResult() { String date = "2022-40-40"; - assertEquals("Sat May 10 00:00:00 UTC 2025", simpleParseDate.parseDate(date, Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd")).toString()); + assertEquals("Sat May 10 00:00:00 UTC 2025", SimpleParseDate.parseDate(date, Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd")) + .toString()); } @Test - public void whenInvalidDate_thenAssertThrows() { - SimpleDateTimeFormater simpleDateTimeFormater = new SimpleDateTimeFormater(); - assertEquals(java.time.LocalDate.parse("2022-12-04"), simpleDateTimeFormater.parseDate("2022-12-04")); - assertThrows(DateTimeParseException.class, () -> simpleDateTimeFormater.parseDate("2022-13-04")); + void whenInvalidDate_thenAssertThrows() { + assertEquals(java.time.LocalDate.parse("2022-12-04"), SimpleDateTimeFormater.parseDate("2022-12-04")); + assertThrows(DateTimeParseException.class, () -> SimpleDateTimeFormater.parseDate("2022-13-04")); } @Test - public void whenDateIsCorrect_thenParseCorrect() { - SimpleDateUtils simpleDateUtils = new SimpleDateUtils(); - assertNull(simpleDateUtils.parseDate("53/10/2014")); - assertEquals("Wed Sep 10 00:00:00 UTC 2014", simpleDateUtils.parseDate("10/09/2014").toString()); + void whenDateIsCorrect_thenParseCorrect() { + assertNull(SimpleDateUtils.parseDate("53/10/2014")); + assertEquals("Wed Sep 10 00:00:00 UTC 2014", SimpleDateUtils.parseDate("10/09/2014") + .toString()); } @Test - public void whenDateIsCorrect_thenResultCorrect() { - SimpleDateTimeFormat simpleDateTimeFormat = new SimpleDateTimeFormat(); - assertNull(simpleDateTimeFormat.parseDate("53/10/2014")); - assertEquals(LocalDate.parse("2014-10-10"), simpleDateTimeFormat.parseDate("2014-10-10")); + void whenDateIsCorrect_thenResultCorrect() { + assertNull(SimpleDateTimeFormat.parseDate("53/10/2014")); + assertEquals(LocalDate.parse("2014-10-10"), SimpleDateTimeFormat.parseDate("2014-10-10")); } } diff --git a/core-java-modules/core-java-8-datetime/pom.xml b/core-java-modules/core-java-8-datetime/pom.xml index 481b1a6a69..06ecc3d017 100644 --- a/core-java-modules/core-java-8-datetime/pom.xml +++ b/core-java-modules/core-java-8-datetime/pom.xml @@ -56,7 +56,7 @@ 1.8 1.8 - 2.10 + 2.12.5 \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations-1/pom.xml b/core-java-modules/core-java-date-operations-1/pom.xml index 5bfbb5bab0..3d7335c86e 100644 --- a/core-java-modules/core-java-date-operations-1/pom.xml +++ b/core-java-modules/core-java-date-operations-1/pom.xml @@ -54,7 +54,7 @@ - 2.10 + 2.12.5 RELEASE 1.9 1.9 diff --git a/core-java-modules/core-java-date-operations-2/pom.xml b/core-java-modules/core-java-date-operations-2/pom.xml index c6a22a4166..86fbbf614e 100644 --- a/core-java-modules/core-java-date-operations-2/pom.xml +++ b/core-java-modules/core-java-date-operations-2/pom.xml @@ -47,7 +47,7 @@ - 2.10 + 2.12.5 1.5.1 3.2.7.Final 5.9 diff --git a/core-java-modules/core-java-datetime-conversion/pom.xml b/core-java-modules/core-java-datetime-conversion/pom.xml index 3ff26323df..8e148edaad 100644 --- a/core-java-modules/core-java-datetime-conversion/pom.xml +++ b/core-java-modules/core-java-datetime-conversion/pom.xml @@ -54,7 +54,7 @@ - 2.10 + 2.12.5 1.9 1.9 diff --git a/json-modules/gson/pom.xml b/json-modules/gson/pom.xml index ba968d9ae1..9e29bab3c4 100644 --- a/json-modules/gson/pom.xml +++ b/json-modules/gson/pom.xml @@ -65,7 +65,7 @@ 2.10.1 - 2.9.6 + 2.12.5 \ No newline at end of file diff --git a/persistence-modules/spring-data-couchbase-2/pom.xml b/persistence-modules/spring-data-couchbase-2/pom.xml index 45462d477e..eda2c45371 100644 --- a/persistence-modules/spring-data-couchbase-2/pom.xml +++ b/persistence-modules/spring-data-couchbase-2/pom.xml @@ -72,7 +72,7 @@ 6.0.6 5.0.3 8.0.1.Final - 2.12.2 + 2.12.5 \ No newline at end of file diff --git a/spring-ejb-modules/ejb-beans/pom.xml b/spring-ejb-modules/ejb-beans/pom.xml index 94f7963ad6..6203db5f5a 100644 --- a/spring-ejb-modules/ejb-beans/pom.xml +++ b/spring-ejb-modules/ejb-beans/pom.xml @@ -192,7 +192,7 @@ 2.21.0 2.8 8.2.1.Final - 2.10.12 + 2.12.5 \ No newline at end of file diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index f682eafdbe..173c5a5af0 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -121,12 +121,6 @@ hibernate-validator ${hibernate-validator.version} - - - joda-time - joda-time - ${joda-time.version} - com.github.jknack @@ -196,7 +190,6 @@ 6.0.10.Final 4.1.0 - 2.10 1 1.5.1 diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index a4860b641d..d07e6d3b28 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -93,11 +93,6 @@ mail ${javax.mail.version} - - joda-time - joda-time - ${joda-time.version} - com.fasterxml.jackson.core jackson-annotations @@ -184,7 +179,6 @@ 4.5.2 0.9 8.0.0 - 2.9.6 1.1 1.2 2.27.2 diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index eaec50c1f7..611a337b0c 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -114,7 +114,7 @@ - 2.9.6 + 2.12.5 2.8.0 3.0.1 From 25a02eb86de26a26bb983f4dfa357480d8384247 Mon Sep 17 00:00:00 2001 From: luca Date: Mon, 13 Nov 2023 12:24:40 +0100 Subject: [PATCH 207/233] fix: add only one spring boot app --- .../baeldung/overridebean/{basic => }/Config.java | 5 +---- .../overridebean/{basic => boot}/Application.java | 2 +- .../overridebean/conditional/Application.java | 14 -------------- .../baeldung/overridebean/profile/Application.java | 14 -------------- .../conditional/ConditionIntegrationTest.java | 1 + .../mockbean/MockBeanIntegrationTest.java | 2 +- .../OverrideBeanDefinitionIntegrationTest.java | 4 ++-- .../primary/PrimaryIntegrationTest.java | 4 ++-- .../profile/ProfileIntegrationTest.java | 1 + 9 files changed, 9 insertions(+), 38 deletions(-) rename spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/{basic => }/Config.java (64%) rename spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/{basic => boot}/Application.java (93%) delete mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/Application.java delete mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/Application.java diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Config.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Config.java similarity index 64% rename from spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Config.java rename to spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Config.java index 67d999958d..f0892338f8 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Config.java +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/Config.java @@ -1,11 +1,8 @@ -package com.baeldung.overridebean.basic; +package com.baeldung.overridebean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.baeldung.overridebean.Service; -import com.baeldung.overridebean.ServiceImpl; - @Configuration public class Config { diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Application.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/boot/Application.java similarity index 93% rename from spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Application.java rename to spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/boot/Application.java index 6f9acde3d8..1eb0012493 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/basic/Application.java +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/boot/Application.java @@ -1,4 +1,4 @@ -package com.baeldung.overridebean.basic; +package com.baeldung.overridebean.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/Application.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/Application.java deleted file mode 100644 index 9c4cdbf8ec..0000000000 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/conditional/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.overridebean.conditional; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; - -@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class }) -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/Application.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/Application.java deleted file mode 100644 index d3298b2eb4..0000000000 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/overridebean/profile/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.overridebean.profile; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; - -@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class }) -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionIntegrationTest.java index 5f6b1d128f..b3a5164ff5 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionIntegrationTest.java @@ -12,6 +12,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.overridebean.Endpoint; +import com.baeldung.overridebean.boot.Application; @SpringBootTest(classes = { Application.class, ConditionalConfig.class, Endpoint.class, ConditionalTestConfig.class }, properties = "service.stub=true") @AutoConfigureMockMvc diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java index 6a7be1cbda..2ece28482d 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java @@ -15,7 +15,7 @@ import org.springframework.test.web.servlet.MockMvc; import com.baeldung.overridebean.Endpoint; import com.baeldung.overridebean.Service; -import com.baeldung.overridebean.basic.Application; +import com.baeldung.overridebean.boot.Application; @SpringBootTest(classes = { Application.class, Endpoint.class }) @AutoConfigureMockMvc diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionIntegrationTest.java index 0f3753ef34..a8dba58b79 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/overridebeandefinition/OverrideBeanDefinitionIntegrationTest.java @@ -11,9 +11,9 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMock import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; +import com.baeldung.overridebean.Config; import com.baeldung.overridebean.Endpoint; -import com.baeldung.overridebean.basic.Application; -import com.baeldung.overridebean.basic.Config; +import com.baeldung.overridebean.boot.Application; @SpringBootTest(classes = { Application.class, Config.class, Endpoint.class, OverrideBeanDefinitionTestConfig.class }, properties = "spring.main.allow-bean-definition-overriding=true") @AutoConfigureMockMvc diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryIntegrationTest.java index 2bddfd4637..b6061c86d5 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/primary/PrimaryIntegrationTest.java @@ -11,9 +11,9 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMock import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; +import com.baeldung.overridebean.Config; import com.baeldung.overridebean.Endpoint; -import com.baeldung.overridebean.basic.Application; -import com.baeldung.overridebean.basic.Config; +import com.baeldung.overridebean.boot.Application; @SpringBootTest(classes = { Application.class, Config.class, Endpoint.class, PrimaryTestConfig.class }) @AutoConfigureMockMvc diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java index deabfea9e5..7f4aae026c 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java @@ -12,6 +12,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.overridebean.Endpoint; +import com.baeldung.overridebean.boot.Application; @SpringBootTest(classes = { Application.class, ProfileConfig.class, Endpoint.class, ProfileTestConfig.class }) @AutoConfigureMockMvc From 8325025cb7cddb8e7ffee50e533e65face3bfed3 Mon Sep 17 00:00:00 2001 From: Bipinkumar27 Date: Mon, 13 Nov 2023 23:08:31 +0530 Subject: [PATCH 208/233] JAVA-18764: Changes made for adding the H2 dependency for removing integration failure --- security-modules/cas/cas-secured-app/pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/security-modules/cas/cas-secured-app/pom.xml b/security-modules/cas/cas-secured-app/pom.xml index 6e1b878354..7c4864b1c0 100644 --- a/security-modules/cas/cas-secured-app/pom.xml +++ b/security-modules/cas/cas-secured-app/pom.xml @@ -55,6 +55,11 @@ spring-security-test test + + com.h2database + h2 + ${h2.version} + From f8e9ed2925735ff03f26c968769c2a0a82930dcd Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Tue, 14 Nov 2023 05:35:36 +0100 Subject: [PATCH 209/233] Converting a File to a MultipartFile (#15180) * Converting a File to a MultipartFile * Converting a File to a MultipartFile --- spring-web-modules/spring-mvc-java-2/pom.xml | 6 +++ .../ConvertFileToMultipartFileUnitTest.java | 45 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/multipart/file/ConvertFileToMultipartFileUnitTest.java diff --git a/spring-web-modules/spring-mvc-java-2/pom.xml b/spring-web-modules/spring-mvc-java-2/pom.xml index d88a9c320a..b1b5a797f8 100644 --- a/spring-web-modules/spring-mvc-java-2/pom.xml +++ b/spring-web-modules/spring-mvc-java-2/pom.xml @@ -41,6 +41,11 @@ jaxb-runtime ${jaxb-runtime.version} + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + @@ -57,6 +62,7 @@ 4.0.1 5.2.2.RELEASE 2.3.5 + 1.5 \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/multipart/file/ConvertFileToMultipartFileUnitTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/multipart/file/ConvertFileToMultipartFileUnitTest.java new file mode 100644 index 0000000000..7d99f7f9bb --- /dev/null +++ b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/multipart/file/ConvertFileToMultipartFileUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.multipart.file; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItem; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; +import org.springframework.mock.web.MockMultipartFile; + +public class ConvertFileToMultipartFileUnitTest { + + @Test + public void givenFile_whenCreateMultipartFile_thenContentMatch() throws IOException { + File file = new File("src/main/resources/targetFile.tmp"); + byte[] fileBytes = Files.readAllBytes(file.toPath()); + MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", fileBytes); + String fileContent = new String(multipartFile.getBytes()); + assertEquals("Hello World", fileContent); + assertEquals("targetFile.tmp", multipartFile.getOriginalFilename()); + } + + @Test + public void givenFile_whenCreateMultipartFileUsingCommonsMultipart_thenContentMatch() throws IOException { + File file = new File("src/main/resources/targetFile.tmp"); + FileItem fileItem = new DiskFileItem("file", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile()); + InputStream input = new FileInputStream(file); + OutputStream outputStream = fileItem.getOutputStream(); + IOUtils.copy(input, outputStream); + MultipartFile multipartFile = new CommonsMultipartFile(fileItem); + String fileContent = new String(multipartFile.getBytes()); + assertEquals("Hello World", fileContent); + assertEquals("targetFile.tmp", multipartFile.getOriginalFilename()); + } + +} From b38b5327fd82481b3828e453286e1b2eddc7324f Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Tue, 14 Nov 2023 07:30:13 +0200 Subject: [PATCH 210/233] [JAVA-26731] Upgraded bucket4j-spring-boot-starter version --- spring-boot-modules/spring-boot-libraries/pom.xml | 10 +++++++--- .../ratelimiting/application-bucket4j-starter.yml | 6 +++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index ed9a414a60..b0f0c780aa 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -18,6 +18,10 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-validation + org.springframework.boot spring-boot-starter-security @@ -95,7 +99,7 @@ - com.github.vladimir-bukhtoyarov + com.bucket4j bucket4j-core ${bucket4j.version} @@ -226,8 +230,8 @@ 2.1 2.6.0 3.3.0 - 7.6.0 - 0.7.0 + 8.1.0 + 0.8.1 3.1.8 diff --git a/spring-boot-modules/spring-boot-libraries/src/main/resources/ratelimiting/application-bucket4j-starter.yml b/spring-boot-modules/spring-boot-libraries/src/main/resources/ratelimiting/application-bucket4j-starter.yml index ecc9f22e0a..efff65555b 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/resources/ratelimiting/application-bucket4j-starter.yml +++ b/spring-boot-modules/spring-boot-libraries/src/main/resources/ratelimiting/application-bucket4j-starter.yml @@ -21,19 +21,19 @@ bucket4j: url: /api/v1/area.* http-response-body: "{ \"status\": 429, \"error\": \"Too Many Requests\", \"message\": \"You have exhausted your API Request Quota\" }" rate-limits: - - expression: "getHeader('X-api-key')" + - cache-key: "getHeader('X-api-key')" execute-condition: "getHeader('X-api-key').startsWith('PX001-')" bandwidths: - capacity: 100 time: 1 unit: hours - - expression: "getHeader('X-api-key')" + - cache-key: "getHeader('X-api-key')" execute-condition: "getHeader('X-api-key').startsWith('BX001-')" bandwidths: - capacity: 40 time: 1 unit: hours - - expression: "getHeader('X-api-key')" + - cache-key: "getHeader('X-api-key')" bandwidths: - capacity: 20 time: 1 From 8532499dcc839936968894ce06747c454c4d30a7 Mon Sep 17 00:00:00 2001 From: Mikhail Polivakha <68962645+Mikhail2048@users.noreply.github.com> Date: Tue, 14 Nov 2023 08:40:27 +0300 Subject: [PATCH 211/233] BAEL-7187 implemented (#15208) * BAEL-7139 implemented * BAEL-7187 implemented --- ...tableFutureExceptionsHandlingUnitTest.java | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/exceptions_completablefuture/CompletableFutureExceptionsHandlingUnitTest.java diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/exceptions_completablefuture/CompletableFutureExceptionsHandlingUnitTest.java b/core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/exceptions_completablefuture/CompletableFutureExceptionsHandlingUnitTest.java new file mode 100644 index 0000000000..afb31f7617 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/exceptions_completablefuture/CompletableFutureExceptionsHandlingUnitTest.java @@ -0,0 +1,126 @@ +package com.baeldung.exceptions_completablefuture; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.stream.Stream; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +public class CompletableFutureExceptionsHandlingUnitTest { + + @ParameterizedTest + @MethodSource("parametersSource_handle") + void whenCompletableFutureIsScheduled_thenHandleStageIsAlwaysInvoked(int radius, long expected) + throws ExecutionException, InterruptedException { + long actual = CompletableFuture + .supplyAsync(() -> { + if (radius <= 0) { + throw new IllegalArgumentException("Supplied with non-positive radius '%d'"); + } + return Math.round(Math.pow(radius, 2) * Math.PI); + }) + .handle((result, ex) -> { + if (ex == null) { + return result; + } else { + return -1L; + } + }) + .get(); + + Assertions.assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("parametersSource_exceptionally") + void whenCompletableFutureIsScheduled_thenExceptionallyExecutedOnlyOnFailure(int a, int b, int c, long expected) + throws ExecutionException, InterruptedException { + long actual = CompletableFuture + .supplyAsync(() -> { + if (a <= 0 || b <= 0 || c <= 0) { + throw new IllegalArgumentException(String.format("Supplied with incorrect edge length [%s]", List.of(a, b, c))); + } + return a * b * c; + }) + .exceptionally((ex) -> -1) + .get(); + + Assertions.assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("parametersSource_exceptionally") + void givenCompletableFutureIsScheduled_whenHandleIsAlreadyPresent_thenExceptionallyIsNotExecuted(int a, int b, int c, long expected) + throws ExecutionException, InterruptedException { + long actual = CompletableFuture + .supplyAsync(() -> { + if (a <= 0 || b <= 0 || c <= 0) { + throw new IllegalArgumentException(String.format("Supplied with incorrect edge length [%s]", List.of(a, b, c))); + } + return a * b * c; + }) + .handle((result, throwable) -> { + if (throwable != null) { + return -1; + } + return result; + }) + .exceptionally((ex) -> { + System.exit(1); + return 0; + }) + .get(); + + Assertions.assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("parametersSource_whenComplete") + void whenCompletableFutureIsScheduled_thenWhenCompletedExecutedAlways(Double a, long expected, Class ifAny) { + try { + CountDownLatch countDownLatch = new CountDownLatch(1); + + long actual = CompletableFuture + .supplyAsync(() -> { + if (a.isNaN()) { + throw new IllegalArgumentException("Supplied value is NaN"); + } + return Math.round(Math.pow(a, 2)); + }) + .whenComplete((result, exception) -> countDownLatch.countDown()) + .get(); + + Assertions.assertThat(countDownLatch.await(20L, java.util.concurrent.TimeUnit.SECONDS)); + Assertions.assertThat(actual).isEqualTo(expected); + } catch (Exception e) { + Assertions.assertThat(e.getClass()).isSameAs(ExecutionException.class); + Assertions.assertThat(e.getCause().getClass()).isSameAs(ifAny); + } + } + + static Stream parametersSource_handle() { + return Stream.of( + Arguments.of(1, 3), + Arguments.of(-1, -1) + ); + } + + static Stream parametersSource_exceptionally() { + return Stream.of( + Arguments.of(1, 5, 5, 25), + Arguments.of(-1, 10, 15, -1) + ); + } + + static Stream parametersSource_whenComplete() { + return Stream.of( + Arguments.of(2d, 4, null), + Arguments.of(Double.NaN, 1, IllegalArgumentException.class) + ); + } +} From 122ca1a996bb2e014d840eaf879e99dc7432371a Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Tue, 14 Nov 2023 11:17:53 +0530 Subject: [PATCH 212/233] JAVA-27197 Upgrade hibernate-validator version in spring-thymeleaf-5 module --- spring-web-modules/spring-thymeleaf-5/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-thymeleaf-5/pom.xml b/spring-web-modules/spring-thymeleaf-5/pom.xml index 0717e41bac..2d178bd933 100644 --- a/spring-web-modules/spring-thymeleaf-5/pom.xml +++ b/spring-web-modules/spring-thymeleaf-5/pom.xml @@ -139,7 +139,7 @@ 3.0.4.RELEASE 2.4.1 2.0.1.Final - 6.0.11.Final + 8.0.1.Final 1.6.1 From c5af2f3f3b9b6143b2536d9ce430b0a444a59ff6 Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Tue, 14 Nov 2023 07:53:16 +0200 Subject: [PATCH 213/233] This PR is related to BAEL-7181 (#15192) * This commit is related to BAEL-7181 This commit aims to add a class "TimestampToLong.java" that provides several approaches to convert timestamp string into long. * This commit is related to BAEL-7181 This commit aims to add a test class "TimestampToLongUnitTest.java" that provides several approaches to convert timestamp string into long. --- .../timestamptolong/TimestampToLong.java | 32 ++++++++++++ .../TimestampToLongUnitTest.java | 52 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java create mode 100644 core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java diff --git a/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java new file mode 100644 index 0000000000..2ebe30f4ff --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java @@ -0,0 +1,32 @@ +package com.baeldung.timestamptolong; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +public class TimestampToLong { + public void usingSimpleDateFormat() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String currentDateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); + long actualTimestamp = sdf.parse(currentDateString).getTime(); + } + + public void usingInstantClass() { + Instant instant = Instant.now(); + long actualTimestamp = instant.toEpochMilli(); + } + + public void usingTimestamp() { + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + long actualTimestamp = timestamp.getTime(); + } + + public void usingJava8DateTime() { + LocalDateTime localDateTime = LocalDateTime.now(); + long actualTimestamp = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java new file mode 100644 index 0000000000..ede8f7792d --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.timestamptolong; + +import org.junit.Test; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +import static org.junit.Assert.assertTrue; + +public class TimestampToLongUnitTest { + + private static final long TOLERANCE = 1000; + + @Test + public void givenSimpleDateFormat_whenFormattingDate_thenTConvertToLong() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + String currentDateString = sdf.format(new Date()); + long actualTimestamp = sdf.parse(currentDateString).getTime(); + + assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + } + + @Test + public void givenInstantClass_whenGettingTimestamp_thenTConvertToLong() { + Instant instant = Instant.now(); + long actualTimestamp = instant.toEpochMilli(); + + assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + } + + @Test + public void givenTimestamp_whenCreatingTimestamp_thenTConvertToLong() { + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + long actualTimestamp = timestamp.getTime(); + + assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + } + + @Test + public void givenJava8DateTime_whenGettingTimestamp_thenTConvertToLong() { + LocalDateTime localDateTime = LocalDateTime.now(); + long actualTimestamp = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + + assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + } +} From f94f248f5a52c110615c827212eefe30b1d2cd82 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Tue, 14 Nov 2023 11:25:35 +0530 Subject: [PATCH 214/233] JAVA-27196 Upgrade hibernate-validator version in spring-mvc-xml module --- spring-web-modules/spring-mvc-xml/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-mvc-xml/pom.xml b/spring-web-modules/spring-mvc-xml/pom.xml index bf0dc52b68..12f0a1a68a 100644 --- a/spring-web-modules/spring-mvc-xml/pom.xml +++ b/spring-web-modules/spring-mvc-xml/pom.xml @@ -142,7 +142,7 @@ 4.4.5 4.5.2 - 6.0.10.Final + 8.0.1.Final 3.0.1-b08 2.8.0 From 68f4c0517caaca2dc5e4fb41fa0e31aacd0fa761 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Tue, 14 Nov 2023 11:50:54 +0530 Subject: [PATCH 215/233] JAVA-27198 Upgrade hibernate-validator version in spring-thymeleaf module --- spring-web-modules/spring-thymeleaf/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-thymeleaf/pom.xml b/spring-web-modules/spring-thymeleaf/pom.xml index 94ae05ca11..ce0c0a7e21 100644 --- a/spring-web-modules/spring-thymeleaf/pom.xml +++ b/spring-web-modules/spring-thymeleaf/pom.xml @@ -140,7 +140,7 @@ 3.0.4.RELEASE 2.4.1 2.0.1.Final - 6.0.11.Final + 8.0.1.Final 1.9.9 From bf4cc41cb4a77ea0b2be2124bb72af3647a7c7c5 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Tue, 14 Nov 2023 12:24:10 +0530 Subject: [PATCH 216/233] JAVA-27199 Upgrade hibernate validator version in vraptor module --- web-modules/vraptor/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web-modules/vraptor/pom.xml b/web-modules/vraptor/pom.xml index ecc6fe3313..25f8b5d5e5 100644 --- a/web-modules/vraptor/pom.xml +++ b/web-modules/vraptor/pom.xml @@ -49,7 +49,7 @@ provided - org.hibernate + org.hibernate.validator hibernate-validator-cdi ${hibernate-validator.version} @@ -115,7 +115,7 @@ 4.2.0.Final 2.1.2.Final 2.2 - 5.1.1.Final + 8.0.1.Final 4.1.0-RC3 4.0.4 8.0.8-dmr From f20a18ed9b97ead5c6f6e67f55993d3acc4c12dc Mon Sep 17 00:00:00 2001 From: luca Date: Tue, 14 Nov 2023 10:28:22 +0100 Subject: [PATCH 217/233] clean, add mock example --- .../conditional/ConditionalTestConfig.java | 2 +- .../mockbean/MockBeanIntegrationTest.java | 4 +- .../profile/ProfileIntegrationMockTest.java | 38 +++++++++++++++++++ ...t.java => ProfileIntegrationStubTest.java} | 6 ++- .../profile/ProfileTestConfig.java | 12 +++++- 5 files changed, 56 insertions(+), 6 deletions(-) create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationMockTest.java rename spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/{ProfileIntegrationTest.java => ProfileIntegrationStubTest.java} (84%) diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalTestConfig.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalTestConfig.java index c48c4e2266..ce82b43df0 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalTestConfig.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/conditional/ConditionalTestConfig.java @@ -9,8 +9,8 @@ import com.baeldung.overridebean.Service; @TestConfiguration public class ConditionalTestConfig { - @ConditionalOnProperty(name = "service.stub", havingValue = "true") @Bean + @ConditionalOnProperty(name = "service.stub", havingValue = "true") public Service helloWorld() { return new ConditionalStub(); } diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java index 2ece28482d..9a63ad4113 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/mockbean/MockBeanIntegrationTest.java @@ -25,11 +25,11 @@ class MockBeanIntegrationTest { private MockMvc mockMvc; @MockBean - private Service serviceExample; + private Service service; @Test void givenServiceMockBean_whenGetHelloEndpoint_thenMockOk() throws Exception { - when(serviceExample.helloWorld()).thenReturn("hello mock bean"); + when(service.helloWorld()).thenReturn("hello mock bean"); this.mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string(containsString("hello mock bean"))); diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationMockTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationMockTest.java new file mode 100644 index 0000000000..43fb69860d --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationMockTest.java @@ -0,0 +1,38 @@ +package com.baeldung.overridebean.profile; + +import static org.hamcrest.Matchers.containsString; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.overridebean.Endpoint; +import com.baeldung.overridebean.Service; +import com.baeldung.overridebean.boot.Application; + +@SpringBootTest(classes = { Application.class, ProfileConfig.class, Endpoint.class, ProfileTestConfig.class }) +@AutoConfigureMockMvc +@ActiveProfiles("mock") +class ProfileIntegrationMockTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private Service service; + + @Test + void givenConfigurationWithProfile_whenTestProfileIsActive_thenMockOk() throws Exception { + when(service.helloWorld()).thenReturn("hello profile mock"); + this.mockMvc.perform(get("/hello")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("hello profile mock"))); + } +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationStubTest.java similarity index 84% rename from spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java rename to spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationStubTest.java index 7f4aae026c..e1c88f2a31 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationStubTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.overridebean.Endpoint; @@ -16,13 +17,14 @@ import com.baeldung.overridebean.boot.Application; @SpringBootTest(classes = { Application.class, ProfileConfig.class, Endpoint.class, ProfileTestConfig.class }) @AutoConfigureMockMvc -class ProfileIntegrationTest { +@ActiveProfiles("stub") +class ProfileIntegrationStubTest { @Autowired private MockMvc mockMvc; @Test - void givenConfigurationWithProfile_whenNoProductionProfileIsActive_thenStubOk() throws Exception { + void givenConfigurationWithProfile_whenTestProfileIsActive_thenStubOk() throws Exception { this.mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string(containsString("hello profile stub"))); diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileTestConfig.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileTestConfig.java index edd33162e0..7e1de309d3 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileTestConfig.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileTestConfig.java @@ -1,7 +1,10 @@ package com.baeldung.overridebean.profile; +import static org.mockito.Mockito.mock; + import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Profile; import com.baeldung.overridebean.Service; @@ -9,7 +12,14 @@ import com.baeldung.overridebean.Service; public class ProfileTestConfig { @Bean - public Service helloWorld() { + @Profile("stub") + public Service helloWorldStub() { return new ProfileServiceStub(); } + + @Bean + @Profile("mock") + public Service helloWorldMock() { + return mock(Service.class); + } } From 690f6edd5169c4bac54828d94c35be8aae417819 Mon Sep 17 00:00:00 2001 From: Ehsan Sasanianno Date: Tue, 14 Nov 2023 12:39:36 +0100 Subject: [PATCH 218/233] java-26772: upgrade jedis to 5.0.2 (#15207) --- persistence-modules/redis/pom.xml | 2 +- persistence-modules/spring-data-redis/pom.xml | 2 ++ spring-boot-modules/spring-boot-3-2/pom.xml | 2 ++ spring-web-modules/spring-session/spring-session-redis/pom.xml | 2 ++ 4 files changed, 7 insertions(+), 1 deletion(-) diff --git a/persistence-modules/redis/pom.xml b/persistence-modules/redis/pom.xml index 571487af3d..98be674a8e 100644 --- a/persistence-modules/redis/pom.xml +++ b/persistence-modules/redis/pom.xml @@ -57,7 +57,7 @@ 0.6 3.20.0 - 4.3.2 + 5.0.2 4.1.90.Final diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index ab133192a0..052935e215 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -50,6 +50,7 @@ redis.clients jedis + ${jedis.version} jar @@ -83,6 +84,7 @@ 3.2.4 0.10.0 0.6 + 5.0.2 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index 9b5b7ea254..c85488d44b 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -135,6 +135,7 @@ redis.clients jedis + ${jedis.version} jar @@ -285,6 +286,7 @@ 3.0.0-M7 5.14.0 0.2.0 + 5.0.2 diff --git a/spring-web-modules/spring-session/spring-session-redis/pom.xml b/spring-web-modules/spring-session/spring-session-redis/pom.xml index 6824a3632d..6b1aec24e4 100644 --- a/spring-web-modules/spring-session/spring-session-redis/pom.xml +++ b/spring-web-modules/spring-session/spring-session-redis/pom.xml @@ -40,12 +40,14 @@ redis.clients jedis + ${jedis.version} jar 0.6 + 5.0.2 \ No newline at end of file From c6dbdeaaa5ecffef4bf18828a44d604255d9703e Mon Sep 17 00:00:00 2001 From: vunamtien Date: Tue, 14 Nov 2023 18:41:43 +0700 Subject: [PATCH 219/233] BAEL-7106-compress-and-uncompress-bytes (#15216) --- .../compressbytes/CompressByteArrayUtil.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java new file mode 100644 index 0000000000..88e2283985 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java @@ -0,0 +1,58 @@ +package com.baeldung.compressbytes; + +import java.io.ByteArrayOutputStream; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + +public class CompressByteArrayUtil { + + public static byte[] compress(byte[] input) { + Deflater deflater = new Deflater(); + deflater.setInput(input); + deflater.finish(); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + + while (!deflater.finished()) { + int compressedSize = deflater.deflate(buffer); + outputStream.write(buffer, 0, compressedSize); + } + + return outputStream.toByteArray(); + } + + public static byte[] decompress(byte[] input) throws DataFormatException { + Inflater inflater = new Inflater(); + inflater.setInput(input); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + + while (!inflater.finished()) { + int decompressedSize = inflater.inflate(buffer); + outputStream.write(buffer, 0, decompressedSize); + } + + return outputStream.toByteArray(); + } + + public static void main(String[] args) throws Exception { + String inputString = "Baeldung helps developers explore the Java ecosystem and simply be better engineers. " + + "We publish to-the-point guides and courses, with a strong focus on building web applications, Spring, " + + "Spring Security, and RESTful APIs"; + byte[] input = inputString.getBytes(); + + // Compression + byte[] compressedData = compress(input); + + // Decompression + byte[] decompressedData = decompress(compressedData); + + System.out.println("Original: " + input.length + " bytes"); + System.out.println("Compressed: " + compressedData.length + " bytes"); + System.out.println("Decompressed: " + decompressedData.length + " bytes"); + } + +} From 2133e9b5db41efebdf7492f9ebd1672e8bdb42ba Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Tue, 14 Nov 2023 22:48:17 +0100 Subject: [PATCH 220/233] BAEL-7176: How to avoid NoSuchElementException with Stream (#15098) --- .../NoSuchElementExceptionStreamUnitTest.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 core-java-modules/core-java-streams-5/src/test/java/com/baeldung/nosuchelementexception/NoSuchElementExceptionStreamUnitTest.java diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/nosuchelementexception/NoSuchElementExceptionStreamUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/nosuchelementexception/NoSuchElementExceptionStreamUnitTest.java new file mode 100644 index 0000000000..bef834c1af --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/nosuchelementexception/NoSuchElementExceptionStreamUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.nosuchelementexception; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; + +import org.junit.Test; + +public class NoSuchElementExceptionStreamUnitTest { + + @Test(expected = NoSuchElementException.class) + public void givenEmptyOptional_whenCallingGetMethod_thenThrowNoSuchElementException() { + List names = List.of("William", "Amelia", "Albert", "Philip"); + Optional emptyOptional = names.stream() + .filter(name -> name.equals("Emma")) + .findFirst(); + + emptyOptional.get(); + } + + @Test + public void givenEmptyOptional_whenUsingIsPresentMethod_thenReturnDefault() { + List names = List.of("Tyler", "Amelia", "James", "Emma"); + Optional emptyOptional = names.stream() + .filter(name -> name.equals("Lucas")) + .findFirst(); + + String name = "unknown"; + if (emptyOptional.isPresent()) { + name = emptyOptional.get(); + } + + assertEquals("unknown", name); + } + + @Test + public void givenEmptyOptional_whenUsingOrElseMethod_thenReturnDefault() { + List names = List.of("Nicholas", "Justin", "James"); + Optional emptyOptional = names.stream() + .filter(name -> name.equals("Lucas")) + .findFirst(); + + String name = emptyOptional.orElse("unknown"); + + assertEquals("unknown", name); + } + + @Test + public void givenEmptyOptional_whenUsingOrElseGetMethod_thenReturnDefault() { + List names = List.of("Thomas", "Catherine", "David", "Olivia"); + Optional emptyOptional = names.stream() + .filter(name -> name.equals("Liam")) + .findFirst(); + + String name = emptyOptional.orElseGet(() -> "unknown"); + + assertEquals("unknown", name); + } + +} From 4d9a5ea8b46689b1c7f3a1f224a30c9207b431c5 Mon Sep 17 00:00:00 2001 From: Gaetano Piazzolla Date: Wed, 15 Nov 2023 10:55:56 +0100 Subject: [PATCH 221/233] JAVA-12712 | intelliJ Module (#15152) --- intelliJ-modules/.gitignore | 1 + .../gradle/wrapper/gradle-wrapper.properties | 7 + intelliJ-modules/gradlew | 248 ++++++++++++++++++ intelliJ-modules/gradlew.bat | 92 +++++++ intelliJ-modules/settings.gradle | 3 + .../stackoverflow-plugin-gradle/build.gradle | 10 +- .../stackoverflow-plugin/build.gradle | 5 + .../stackoverflow-plugin/settings.gradle | 1 + 8 files changed, 363 insertions(+), 4 deletions(-) create mode 100644 intelliJ-modules/.gitignore create mode 100644 intelliJ-modules/gradle/wrapper/gradle-wrapper.properties create mode 100644 intelliJ-modules/gradlew create mode 100644 intelliJ-modules/gradlew.bat create mode 100644 intelliJ-modules/settings.gradle create mode 100644 intelliJ-modules/stackoverflow-plugin/build.gradle create mode 100644 intelliJ-modules/stackoverflow-plugin/settings.gradle diff --git a/intelliJ-modules/.gitignore b/intelliJ-modules/.gitignore new file mode 100644 index 0000000000..d16386367f --- /dev/null +++ b/intelliJ-modules/.gitignore @@ -0,0 +1 @@ +build/ \ No newline at end of file diff --git a/intelliJ-modules/gradle/wrapper/gradle-wrapper.properties b/intelliJ-modules/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..62f495dfed --- /dev/null +++ b/intelliJ-modules/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/intelliJ-modules/gradlew b/intelliJ-modules/gradlew new file mode 100644 index 0000000000..fcb6fca147 --- /dev/null +++ b/intelliJ-modules/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/intelliJ-modules/gradlew.bat b/intelliJ-modules/gradlew.bat new file mode 100644 index 0000000000..93e3f59f13 --- /dev/null +++ b/intelliJ-modules/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/intelliJ-modules/settings.gradle b/intelliJ-modules/settings.gradle new file mode 100644 index 0000000000..ff10e09b3c --- /dev/null +++ b/intelliJ-modules/settings.gradle @@ -0,0 +1,3 @@ +rootProject.name = 'intellij-modules' +include 'stackoverflow-plugin' +include 'stackoverflow-plugin-gradle' diff --git a/intelliJ-modules/stackoverflow-plugin-gradle/build.gradle b/intelliJ-modules/stackoverflow-plugin-gradle/build.gradle index cd0cc258bf..3967a1f075 100644 --- a/intelliJ-modules/stackoverflow-plugin-gradle/build.gradle +++ b/intelliJ-modules/stackoverflow-plugin-gradle/build.gradle @@ -1,6 +1,6 @@ plugins { id 'java' - id 'org.jetbrains.intellij' version '0.4.21' + id 'org.jetbrains.intellij' version '1.16.0' } group 'com.baeldung' @@ -11,15 +11,17 @@ repositories { } dependencies { - testCompile group: 'junit', name: 'junit', version: '4.12' + testImplementation('junit:junit:4.12') } // See https://github.com/JetBrains/gradle-intellij-plugin/ intellij { - version '2020.1.1' + version = "2022.2.5" + type = "IC" } + patchPluginXml { - changeNotes """ + changeNotes = """ Add change notes here.
most HTML tags may be used""" } \ No newline at end of file diff --git a/intelliJ-modules/stackoverflow-plugin/build.gradle b/intelliJ-modules/stackoverflow-plugin/build.gradle new file mode 100644 index 0000000000..81962e0e0a --- /dev/null +++ b/intelliJ-modules/stackoverflow-plugin/build.gradle @@ -0,0 +1,5 @@ +// this project is not supposed to be built. We check only if it compiles fine. + +plugins { + id 'java' +} \ No newline at end of file diff --git a/intelliJ-modules/stackoverflow-plugin/settings.gradle b/intelliJ-modules/stackoverflow-plugin/settings.gradle new file mode 100644 index 0000000000..4ebea35284 --- /dev/null +++ b/intelliJ-modules/stackoverflow-plugin/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'stackoverflow-plugin' From de50130c7461ddb7c12ee4b5832eb4244f852c1d Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Wed, 15 Nov 2023 14:30:00 +0100 Subject: [PATCH 222/233] Create Table using ASCII in a Console in Java (#15158) --- core-java-modules/core-java-console/pom.xml | 6 ++ .../consoletableoutput/BodyMassIndex.java | 44 +++++++++++++ .../BodyMassIndexApplication.java | 62 +++++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 core-java-modules/core-java-console/src/main/java/com/baeldung/consoletableoutput/BodyMassIndex.java create mode 100644 core-java-modules/core-java-console/src/main/java/com/baeldung/consoletableoutput/BodyMassIndexApplication.java diff --git a/core-java-modules/core-java-console/pom.xml b/core-java-modules/core-java-console/pom.xml index 1b56f1f27c..8677b672ea 100644 --- a/core-java-modules/core-java-console/pom.xml +++ b/core-java-modules/core-java-console/pom.xml @@ -29,6 +29,11 @@
+ + de.vandermeer + asciitable + ${ascii.version} + @@ -157,6 +162,7 @@ 3.0.0-M1 1.8 1.8 + 0.3.2 \ No newline at end of file diff --git a/core-java-modules/core-java-console/src/main/java/com/baeldung/consoletableoutput/BodyMassIndex.java b/core-java-modules/core-java-console/src/main/java/com/baeldung/consoletableoutput/BodyMassIndex.java new file mode 100644 index 0000000000..96cede7020 --- /dev/null +++ b/core-java-modules/core-java-console/src/main/java/com/baeldung/consoletableoutput/BodyMassIndex.java @@ -0,0 +1,44 @@ +package com.baeldung.consoletableoutput; + +public class BodyMassIndex { + + private String name; + private double height; + private double weight; + + public BodyMassIndex(String name, double height, double weight) { + this.name = name; + this.height = height; + this.weight = weight; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getHeight() { + return height; + } + + public void setHeight(double height) { + this.height = height; + } + + public double getWeight() { + return weight; + } + + public void setWeight(double weight) { + this.weight = weight; + } + + public double calculate() { + double bmi = weight / (height * height); + String formattedBmi = String.format("%.2f", bmi); + return Double.parseDouble(formattedBmi); + } +} diff --git a/core-java-modules/core-java-console/src/main/java/com/baeldung/consoletableoutput/BodyMassIndexApplication.java b/core-java-modules/core-java-console/src/main/java/com/baeldung/consoletableoutput/BodyMassIndexApplication.java new file mode 100644 index 0000000000..cb340256aa --- /dev/null +++ b/core-java-modules/core-java-console/src/main/java/com/baeldung/consoletableoutput/BodyMassIndexApplication.java @@ -0,0 +1,62 @@ +package com.baeldung.consoletableoutput; + +import java.util.ArrayList; +import java.util.List; + +import de.vandermeer.asciitable.AsciiTable; +import de.vandermeer.skb.interfaces.transformers.textformat.TextAlignment; + +public class BodyMassIndexApplication { + + public static void main(String[] args) { + stringFormat(); + asciiTable(); + + } + + public static void stringFormat() { + List bodyMassIndices = new ArrayList<>(); + bodyMassIndices.add(new BodyMassIndex("Tom", 1.8, 80)); + bodyMassIndices.add(new BodyMassIndex("Elton", 1.9, 90)); + bodyMassIndices.add(new BodyMassIndex("Harry", 1.9, 90)); + bodyMassIndices.add(new BodyMassIndex("Hannah", 1.9, 90)); + + String leftAlignment = "| %-7s | %-7.2f | %-7.2f | %-5.2f |%n"; + + System.out.format("+---------+---------+---------+-------+%n"); + System.out.format("| Name | Height | Weight | BMI |%n"); + System.out.format("+---------+---------+---------+-------+%n"); + + for (BodyMassIndex bodyMassIndex : bodyMassIndices) { + System.out.format(leftAlignment, bodyMassIndex.getName(), bodyMassIndex.getHeight(), bodyMassIndex.getWeight(), bodyMassIndex.calculate()); + System.out.format("+---------+---------+---------+-------+%n"); + } + + } + + public static void asciiTable() { + List bodyMassIndices = new ArrayList<>(); + bodyMassIndices.add(new BodyMassIndex("Tom", 1.8, 80)); + bodyMassIndices.add(new BodyMassIndex("Elton", 1.9, 90)); + bodyMassIndices.add(new BodyMassIndex("Harry", 1.9, 90)); + bodyMassIndices.add(new BodyMassIndex("Hannah", 1.9, 90)); + + AsciiTable asciiTable = new AsciiTable(); + asciiTable.addRule(); + asciiTable.addRow("Name", "Height", "Weight", "BMI"); + asciiTable.addRule(); + + for (BodyMassIndex bodyMassIndex : bodyMassIndices) { + + asciiTable.addRow(bodyMassIndex.getName(), bodyMassIndex.getHeight(), bodyMassIndex.getWeight(), bodyMassIndex.calculate()); + asciiTable.addRule(); + + } + + asciiTable.setTextAlignment(TextAlignment.CENTER); + String render = asciiTable.render(); + System.out.println(render); + + } + +} From 5787183a36f8a30196f5630f4b702010db1b0042 Mon Sep 17 00:00:00 2001 From: Wynn Teo <49014791+wynnteo@users.noreply.github.com> Date: Wed, 15 Nov 2023 22:55:03 +0800 Subject: [PATCH 223/233] BAEL-7109 - added code to demostrate how to get max date in java (#14944) * BAEL-7109 - added code to demostrate how to get max date in java * BAEL-7109 Fix test case typo * BAEL-7109 Fix test case file name * Fix the test method * Fix the test method * Fix the test method * Remove public * add new line --- .../com/baeldung/maxdate/DateComparison.java | 18 ++++++++++++++++++ .../com/baeldung/maxdate/MaxDateDisplay.java | 18 ++++++++++++++++++ .../maxdate/DateComparisonUnitTest.java | 16 ++++++++++++++++ .../maxdate/MaxDateDisplayUnitTest.java | 18 ++++++++++++++++++ 4 files changed, 70 insertions(+) create mode 100644 core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/maxdate/DateComparison.java create mode 100644 core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/maxdate/MaxDateDisplay.java create mode 100644 core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/maxdate/DateComparisonUnitTest.java create mode 100644 core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/maxdate/MaxDateDisplayUnitTest.java diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/maxdate/DateComparison.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/maxdate/DateComparison.java new file mode 100644 index 0000000000..d6450670a2 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/maxdate/DateComparison.java @@ -0,0 +1,18 @@ +package com.baeldung.maxdate; + +import java.util.Date; + +public class DateComparison { + public int compareTodayWithMaxDate() { + Date today = new Date(); + Date maxDate = new Date(Long.MAX_VALUE); + + int comparisonResult = today.compareTo(maxDate); + return comparisonResult; + } + + public static void main(String[] args) { + DateComparison comparator = new DateComparison(); + System.out.println(comparator.compareTodayWithMaxDate()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/maxdate/MaxDateDisplay.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/maxdate/MaxDateDisplay.java new file mode 100644 index 0000000000..b79b5f4422 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/maxdate/MaxDateDisplay.java @@ -0,0 +1,18 @@ +package com.baeldung.maxdate; + +import java.util.Date; +import java.text.SimpleDateFormat; + +public class MaxDateDisplay { + public String getMaxDateValue() { + Date maxDate = new Date(Long.MAX_VALUE); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + return "The maximum date value in Java is: " + sdf.format(maxDate); + } + + public static void main(String[] args) { + MaxDateDisplay display = new MaxDateDisplay(); + System.out.println(display.getMaxDateValue()); + } +} + diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/maxdate/DateComparisonUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/maxdate/DateComparisonUnitTest.java new file mode 100644 index 0000000000..70aef126da --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/maxdate/DateComparisonUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.maxdate; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class DateComparisonUnitTest { + + @Test + void whenCompareTodayWithMaxDate_thenCorrectResult() { + DateComparison comparator = new DateComparison(); + int result = comparator.compareTodayWithMaxDate(); + + assertTrue(result < 0); + } +} diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/maxdate/MaxDateDisplayUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/maxdate/MaxDateDisplayUnitTest.java new file mode 100644 index 0000000000..dd7000bd29 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/maxdate/MaxDateDisplayUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.maxdate; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class MaxDateDisplayUnitTest { + + @Test + void whenGetMaxDate_thenCorrectResult() { + MaxDateDisplay display = new MaxDateDisplay(); + String result = display.getMaxDateValue(); + assertEquals( + "The maximum date value in Java is: 292278994-08-17 07:12:55.807", + result + ); + } +} From 0838279c6afa9bf92a2a89cdb2edcafaddd1a039 Mon Sep 17 00:00:00 2001 From: ACHRAF TAITAI <43656331+achraftt@users.noreply.github.com> Date: Wed, 15 Nov 2023 22:16:28 +0100 Subject: [PATCH 224/233] BAEL-7092: How to get the size of a file in MB, KB & GB in java (#15117) * BAEL-7092: How to get the size of a file in MB, KB & GB in java * Update JavaFileSizeUnitTest.java * BAEL-7092: How to get the size of a file in MB, KB & GB in java --------- Co-authored-by: Grzegorz Piwowarek --- .../java/com/baeldung/size/FileSizeUtils.java | 28 +++++++++++++++++ .../baeldung/size/JavaFileSizeUnitTest.java | 31 ++++++++++++++++--- 2 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 core-java-modules/core-java-io/src/main/java/com/baeldung/size/FileSizeUtils.java diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/size/FileSizeUtils.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/size/FileSizeUtils.java new file mode 100644 index 0000000000..18c8687043 --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/size/FileSizeUtils.java @@ -0,0 +1,28 @@ +package com.baeldung.size; + +import java.io.File; + +public class FileSizeUtils { + public static long getFileSizeInBytes(File file) { + if (file.exists()) { + return file.length(); + } else { + throw new IllegalArgumentException("File not found."); + } + } + + public static double getFileSizeInKilobytes(File file) { + long bytes = getFileSizeInBytes(file); + return (double) bytes / 1024; + } + + public static double getFileSizeInMegabytes(File file) { + double kilobytes = getFileSizeInKilobytes(file); + return kilobytes / 1024; + } + + public static double getFileSizeInGigabytes(File file) { + double megabytes = getFileSizeInMegabytes(file); + return megabytes / 1024; + } +} diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/size/JavaFileSizeUnitTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/size/JavaFileSizeUnitTest.java index d015f2602e..d8f4361260 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/size/JavaFileSizeUnitTest.java +++ b/core-java-modules/core-java-io/src/test/java/com/baeldung/size/JavaFileSizeUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.size; -import static org.junit.Assert.assertEquals; +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Test; import java.io.File; import java.io.FileInputStream; @@ -10,9 +12,9 @@ import java.net.URL; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; public class JavaFileSizeUnitTest { private static final long EXPECTED_FILE_SIZE_IN_BYTES = 11; @@ -85,4 +87,23 @@ public class JavaFileSizeUnitTest { assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, stream.available()); } } -} \ No newline at end of file + + @Test + public void whenGetFileSizeInDifferentUnits_thenCorrect(){ + filePath = String.join(File.separator, new String[] { "src", "test", "resources", "size", "sample_file_1.in" }); + File file = new File(filePath); + if (file.exists()) { + long expectedBytes = file.length(); + double expectedKilobytes = (double) expectedBytes / 1024; + double expectedMegabytes = expectedKilobytes / 1024; + double expectedGigabytes = expectedMegabytes / 1024; + + assertEquals(expectedBytes, FileSizeUtils.getFileSizeInBytes(file)); + assertEquals(expectedKilobytes, FileSizeUtils.getFileSizeInKilobytes(file), 0.01); + assertEquals(expectedMegabytes, FileSizeUtils.getFileSizeInMegabytes(file), 0.01); + assertEquals(expectedGigabytes, FileSizeUtils.getFileSizeInGigabytes(file), 0.01); + } else { + fail("File not found."); + } + } +} From 336ee922eb0933fef3f6ab6b554f4cc07f2f652d Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Thu, 16 Nov 2023 12:21:18 +0200 Subject: [PATCH 225/233] JAVA-26692 Go over tutorials - integration builds test results - Week 45 - 2023 (#15194) Co-authored-by: timis1 --- .../multipletopics/KafkaMultipleTopicsIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/multipletopics/KafkaMultipleTopicsIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/multipletopics/KafkaMultipleTopicsIntegrationTest.java index 345e84b65b..570670cdf9 100644 --- a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/multipletopics/KafkaMultipleTopicsIntegrationTest.java +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/multipletopics/KafkaMultipleTopicsIntegrationTest.java @@ -21,7 +21,7 @@ import org.springframework.kafka.test.context.EmbeddedKafka; import org.springframework.kafka.test.utils.ContainerTestUtils; @SpringBootTest(classes = KafkaMultipleTopicsApplication.class) -@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" }) +@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9099", "port=9099" }) public class KafkaMultipleTopicsIntegrationTest { private static final String CARD_PAYMENTS_TOPIC = "card-payments"; private static final String BANK_TRANSFERS_TOPIC = "bank-transfers"; From 58db4f7a091f29128ddbbacc99ccecec46a2c422 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 16 Nov 2023 20:22:43 +0100 Subject: [PATCH 226/233] JAVA-27338: Fix VehicleUnitTest --- .../com/baeldung/sealed/classes/VehicleUnitTest.java | 8 ++++---- .../com/baeldung/sealed/records/VehicleUnitTest.java | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/core-java-modules/core-java-17/src/test/java/com/baeldung/sealed/classes/VehicleUnitTest.java b/core-java-modules/core-java-17/src/test/java/com/baeldung/sealed/classes/VehicleUnitTest.java index 73d8aad810..0c437affd8 100644 --- a/core-java-modules/core-java-17/src/test/java/com/baeldung/sealed/classes/VehicleUnitTest.java +++ b/core-java-modules/core-java-17/src/test/java/com/baeldung/sealed/classes/VehicleUnitTest.java @@ -18,19 +18,19 @@ public class VehicleUnitTest { } @Test - public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() { + public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() throws ClassNotFoundException { Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false); Assertions.assertThat(car.getClass().getSuperclass().isSealed()).isEqualTo(true); Assertions.assertThat(car.getClass().getSuperclass().getPermittedSubclasses()) - .contains(ClassDesc.of(car.getClass().getCanonicalName())); + .contains(Class.forName(car.getClass().getCanonicalName())); } @Test - public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() { + public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() throws ClassNotFoundException { Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false); Assertions.assertThat(truck.getClass().getSuperclass().isSealed()).isEqualTo(true); Assertions.assertThat(truck.getClass().getSuperclass().getPermittedSubclasses()) - .contains(ClassDesc.of(truck.getClass().getCanonicalName())); + .contains(Class.forName(truck.getClass().getCanonicalName())); } @Test diff --git a/core-java-modules/core-java-17/src/test/java/com/baeldung/sealed/records/VehicleUnitTest.java b/core-java-modules/core-java-17/src/test/java/com/baeldung/sealed/records/VehicleUnitTest.java index ac8a8c953c..8dd150b5e7 100644 --- a/core-java-modules/core-java-17/src/test/java/com/baeldung/sealed/records/VehicleUnitTest.java +++ b/core-java-modules/core-java-17/src/test/java/com/baeldung/sealed/records/VehicleUnitTest.java @@ -18,19 +18,19 @@ public class VehicleUnitTest { } @Test - public void givenCar_whenUsingReflectionAPI_thenInterfaceIsSealed() { + public void givenCar_whenUsingReflectionAPI_thenInterfaceIsSealed() throws ClassNotFoundException { Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false); Assertions.assertThat(car.getClass().getInterfaces()[0].isSealed()).isEqualTo(true); - Assertions.assertThat(car.getClass().getInterfaces()[0].permittedSubclasses()) - .contains(ClassDesc.of(car.getClass().getCanonicalName())); + Assertions.assertThat(car.getClass().getInterfaces()[0].getPermittedSubclasses()) + .contains(Class.forName(car.getClass().getCanonicalName())); } @Test - public void givenTruck_whenUsingReflectionAPI_thenInterfaceIsSealed() { + public void givenTruck_whenUsingReflectionAPI_thenInterfaceIsSealed() throws ClassNotFoundException { Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false); Assertions.assertThat(truck.getClass().getInterfaces()[0].isSealed()).isEqualTo(true); - Assertions.assertThat(truck.getClass().getInterfaces()[0].permittedSubclasses()) - .contains(ClassDesc.of(truck.getClass().getCanonicalName())); + Assertions.assertThat(truck.getClass().getInterfaces()[0].getPermittedSubclasses()) + .contains(Class.forName(truck.getClass().getCanonicalName())); } @Test From 0b229a9af4cc321f4bebb278d47616f726c7cb48 Mon Sep 17 00:00:00 2001 From: Ulisses Lima Date: Thu, 16 Nov 2023 18:35:11 -0300 Subject: [PATCH 227/233] draft 1 (#15222) --- ...tSpecificDeserializationFilterFactory.java | 47 +++++++ .../pojo/ContextSpecific.java | 7 ++ .../pojo/NestedSample.java | 19 +++ .../deserializationfilters/pojo/Sample.java | 61 +++++++++ .../pojo/SampleExploit.java | 25 ++++ .../service/DeserializationService.java | 11 ++ .../service/LimitedArrayService.java | 15 +++ .../service/LowDepthService.java | 20 +++ .../service/SmallObjectService.java | 15 +++ .../utils/DeserializationUtils.java | 50 ++++++++ .../utils/FilterUtils.java | 32 +++++ .../utils/SerializationUtils.java | 17 +++ ...cDeserializationFilterIntegrationTest.java | 119 ++++++++++++++++++ 13 files changed, 438 insertions(+) create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/ContextSpecificDeserializationFilterFactory.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/ContextSpecific.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/NestedSample.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/Sample.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/SampleExploit.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/DeserializationService.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/LimitedArrayService.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/LowDepthService.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/SmallObjectService.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/DeserializationUtils.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/FilterUtils.java create mode 100644 core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/SerializationUtils.java create mode 100644 core-java-modules/core-java-17/src/test/java/com/baeldung/deserializationfilters/ContextSpecificDeserializationFilterIntegrationTest.java diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/ContextSpecificDeserializationFilterFactory.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/ContextSpecificDeserializationFilterFactory.java new file mode 100644 index 0000000000..25a855487e --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/ContextSpecificDeserializationFilterFactory.java @@ -0,0 +1,47 @@ +package com.baeldung.deserializationfilters; + +import java.io.ObjectInputFilter; +import java.util.function.BinaryOperator; + +import com.baeldung.deserializationfilters.service.DeserializationService; +import com.baeldung.deserializationfilters.service.LimitedArrayService; +import com.baeldung.deserializationfilters.service.LowDepthService; +import com.baeldung.deserializationfilters.service.SmallObjectService; +import com.baeldung.deserializationfilters.utils.FilterUtils; + +public class ContextSpecificDeserializationFilterFactory implements BinaryOperator { + + @Override + public ObjectInputFilter apply(ObjectInputFilter current, ObjectInputFilter next) { + if (current == null) { + Class caller = findInStack(DeserializationService.class); + + if (caller == null) { + current = FilterUtils.fallbackFilter(); + } else if (caller.equals(SmallObjectService.class)) { + current = FilterUtils.safeSizeFilter(190); + } else if (caller.equals(LowDepthService.class)) { + current = FilterUtils.safeDepthFilter(2); + } else if (caller.equals(LimitedArrayService.class)) { + current = FilterUtils.safeArrayFilter(3); + } + } + + return ObjectInputFilter.merge(current, next); + } + + private static Class findInStack(Class superType) { + for (StackTraceElement element : Thread.currentThread() + .getStackTrace()) { + try { + Class subType = Class.forName(element.getClassName()); + if (superType.isAssignableFrom(subType)) { + return subType; + } + } catch (ClassNotFoundException e) { + return null; + } + } + return null; + } +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/ContextSpecific.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/ContextSpecific.java new file mode 100644 index 0000000000..add827d280 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/ContextSpecific.java @@ -0,0 +1,7 @@ +package com.baeldung.deserializationfilters.pojo; + +import java.io.Serializable; + +public interface ContextSpecific extends Serializable { + +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/NestedSample.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/NestedSample.java new file mode 100644 index 0000000000..a1d41744e6 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/NestedSample.java @@ -0,0 +1,19 @@ +package com.baeldung.deserializationfilters.pojo; + +public class NestedSample implements ContextSpecific { + private static final long serialVersionUID = 1L; + + private Sample optional; + + public NestedSample(Sample optional) { + this.optional = optional; + } + + public Sample getOptional() { + return optional; + } + + public void setOptional(Sample optional) { + this.optional = optional; + } +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/Sample.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/Sample.java new file mode 100644 index 0000000000..fed3639c64 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/Sample.java @@ -0,0 +1,61 @@ +package com.baeldung.deserializationfilters.pojo; + +public class Sample implements ContextSpecific, Comparable { + private static final long serialVersionUID = 1L; + + private int[] array; + private String name; + private NestedSample nested; + + public Sample(String name) { + this.name = name; + } + + public Sample(int[] array) { + this.array = array; + } + + public Sample(NestedSample nested) { + this.nested = nested; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int[] getArray() { + return array; + } + + public void setArray(int[] array) { + this.array = array; + } + + public NestedSample getNested() { + return nested; + } + + public void setNested(NestedSample nested) { + this.nested = nested; + } + + @Override + public String toString() { + return name; + } + + @Override + public int compareTo(Sample o) { + if (name == null) + return -1; + + if (o == null || o.getName() == null) + return 1; + + return getName().compareTo(o.getName()); + } +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/SampleExploit.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/SampleExploit.java new file mode 100644 index 0000000000..24dce289c6 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/pojo/SampleExploit.java @@ -0,0 +1,25 @@ +package com.baeldung.deserializationfilters.pojo; + +public class SampleExploit extends Sample { + private static final long serialVersionUID = 1L; + + public SampleExploit() { + super("exploit"); + } + + public static void maliciousCode() { + System.out.println("exploit executed"); + } + + @Override + public String toString() { + maliciousCode(); + return "exploit"; + } + + @Override + public int compareTo(Sample o) { + maliciousCode(); + return super.compareTo(o); + } +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/DeserializationService.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/DeserializationService.java new file mode 100644 index 0000000000..9a66cb0e91 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/DeserializationService.java @@ -0,0 +1,11 @@ +package com.baeldung.deserializationfilters.service; + +import java.io.InputStream; +import java.util.Set; + +import com.baeldung.deserializationfilters.pojo.ContextSpecific; + +public interface DeserializationService { + + Set process(InputStream... inputStreams); +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/LimitedArrayService.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/LimitedArrayService.java new file mode 100644 index 0000000000..3aadbe7111 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/LimitedArrayService.java @@ -0,0 +1,15 @@ +package com.baeldung.deserializationfilters.service; + +import java.io.InputStream; +import java.util.Set; + +import com.baeldung.deserializationfilters.pojo.ContextSpecific; +import com.baeldung.deserializationfilters.utils.DeserializationUtils; + +public class LimitedArrayService implements DeserializationService { + + @Override + public Set process(InputStream... inputStreams) { + return DeserializationUtils.deserializeIntoSet(inputStreams); + } +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/LowDepthService.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/LowDepthService.java new file mode 100644 index 0000000000..69350c1399 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/LowDepthService.java @@ -0,0 +1,20 @@ +package com.baeldung.deserializationfilters.service; + +import java.io.InputStream; +import java.io.ObjectInputFilter; +import java.util.Set; + +import com.baeldung.deserializationfilters.pojo.ContextSpecific; +import com.baeldung.deserializationfilters.utils.DeserializationUtils; + +public class LowDepthService implements DeserializationService { + + public Set process(ObjectInputFilter filter, InputStream... inputStreams) { + return DeserializationUtils.deserializeIntoSet(filter, inputStreams); + } + + @Override + public Set process(InputStream... inputStreams) { + return process(null, inputStreams); + } +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/SmallObjectService.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/SmallObjectService.java new file mode 100644 index 0000000000..a0690276b7 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/service/SmallObjectService.java @@ -0,0 +1,15 @@ +package com.baeldung.deserializationfilters.service; + +import java.io.InputStream; +import java.util.Set; + +import com.baeldung.deserializationfilters.pojo.ContextSpecific; +import com.baeldung.deserializationfilters.utils.DeserializationUtils; + +public class SmallObjectService implements DeserializationService { + + @Override + public Set process(InputStream... inputStreams) { + return DeserializationUtils.deserializeIntoSet(inputStreams); + } +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/DeserializationUtils.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/DeserializationUtils.java new file mode 100644 index 0000000000..54db823102 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/DeserializationUtils.java @@ -0,0 +1,50 @@ +package com.baeldung.deserializationfilters.utils; + +import java.io.InputStream; +import java.io.InvalidClassException; +import java.io.ObjectInputFilter; +import java.io.ObjectInputStream; +import java.util.Set; +import java.util.TreeSet; + +import com.baeldung.deserializationfilters.pojo.ContextSpecific; + +public class DeserializationUtils { + private DeserializationUtils() { + } + + public static Object deserialize(InputStream inStream) { + return deserialize(inStream, null); + } + + public static Object deserialize(InputStream inStream, ObjectInputFilter filter) { + try (ObjectInputStream in = new ObjectInputStream(inStream)) { + if (filter != null) { + in.setObjectInputFilter(filter); + } + return in.readObject(); + } catch (InvalidClassException e) { + return null; + } catch (Throwable e) { + e.printStackTrace(); + return null; + } + } + + public static Set deserializeIntoSet(InputStream... inputStreams) { + return deserializeIntoSet(null, inputStreams); + } + + public static Set deserializeIntoSet(ObjectInputFilter filter, InputStream... inputStreams) { + Set set = new TreeSet<>(); + + for (InputStream inputStream : inputStreams) { + Object object = deserialize(inputStream, filter); + if (object != null) { + set.add((ContextSpecific) object); + } + } + + return set; + } +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/FilterUtils.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/FilterUtils.java new file mode 100644 index 0000000000..fac69a94b9 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/FilterUtils.java @@ -0,0 +1,32 @@ +package com.baeldung.deserializationfilters.utils; + +import java.io.ObjectInputFilter; + +public class FilterUtils { + + private static final String DEFAULT_PACKAGE_PATTERN = "java.base/*;!*"; + private static final String POJO_PACKAGE = "com.baeldung.deserializationfilters.pojo"; + + private FilterUtils() { + } + + private static ObjectInputFilter baseFilter(String parameter, int max) { + return ObjectInputFilter.Config.createFilter(String.format("%s=%d;%s.**;%s", parameter, max, POJO_PACKAGE, DEFAULT_PACKAGE_PATTERN)); + } + + public static ObjectInputFilter fallbackFilter() { + return ObjectInputFilter.Config.createFilter(String.format("%s", DEFAULT_PACKAGE_PATTERN)); + } + + public static ObjectInputFilter safeSizeFilter(int max) { + return baseFilter("maxbytes", max); + } + + public static ObjectInputFilter safeArrayFilter(int max) { + return baseFilter("maxarray", max); + } + + public static ObjectInputFilter safeDepthFilter(int max) { + return baseFilter("maxdepth", max); + } +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/SerializationUtils.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/SerializationUtils.java new file mode 100644 index 0000000000..4f62e5d46b --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/deserializationfilters/utils/SerializationUtils.java @@ -0,0 +1,17 @@ +package com.baeldung.deserializationfilters.utils; + +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; + +public class SerializationUtils { + + private SerializationUtils() { + } + + public static void serialize(Object object, OutputStream outStream) throws IOException { + try (ObjectOutputStream objStream = new ObjectOutputStream(outStream)) { + objStream.writeObject(object); + } + } +} diff --git a/core-java-modules/core-java-17/src/test/java/com/baeldung/deserializationfilters/ContextSpecificDeserializationFilterIntegrationTest.java b/core-java-modules/core-java-17/src/test/java/com/baeldung/deserializationfilters/ContextSpecificDeserializationFilterIntegrationTest.java new file mode 100644 index 0000000000..3e7de20070 --- /dev/null +++ b/core-java-modules/core-java-17/src/test/java/com/baeldung/deserializationfilters/ContextSpecificDeserializationFilterIntegrationTest.java @@ -0,0 +1,119 @@ +package com.baeldung.deserializationfilters; + +import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputFilter; +import java.util.Set; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.baeldung.deserializationfilters.pojo.ContextSpecific; +import com.baeldung.deserializationfilters.pojo.NestedSample; +import com.baeldung.deserializationfilters.pojo.Sample; +import com.baeldung.deserializationfilters.pojo.SampleExploit; +import com.baeldung.deserializationfilters.service.LimitedArrayService; +import com.baeldung.deserializationfilters.service.LowDepthService; +import com.baeldung.deserializationfilters.service.SmallObjectService; +import com.baeldung.deserializationfilters.utils.DeserializationUtils; +import com.baeldung.deserializationfilters.utils.FilterUtils; +import com.baeldung.deserializationfilters.utils.SerializationUtils; + +public class ContextSpecificDeserializationFilterIntegrationTest { + + private static ByteArrayOutputStream serialSampleA = new ByteArrayOutputStream(); + private static ByteArrayOutputStream serialBigSampleA = new ByteArrayOutputStream(); + + private static ByteArrayOutputStream serialSampleB = new ByteArrayOutputStream(); + private static ByteArrayOutputStream serialBigSampleB = new ByteArrayOutputStream(); + + private static ByteArrayOutputStream serialSampleC = new ByteArrayOutputStream(); + private static ByteArrayOutputStream serialBigSampleC = new ByteArrayOutputStream(); + + private static ByteArrayInputStream bytes(ByteArrayOutputStream stream) { + return new ByteArrayInputStream(stream.toByteArray()); + } + + @BeforeAll + static void setup() throws IOException { + ObjectInputFilter.Config.setSerialFilterFactory(new ContextSpecificDeserializationFilterFactory()); + + SerializationUtils.serialize(new Sample("simple"), serialSampleA); + SerializationUtils.serialize(new SampleExploit(), serialBigSampleA); + + SerializationUtils.serialize(new Sample(new int[] { 1, 2, 3 }), serialSampleB); + SerializationUtils.serialize(new Sample(new int[] { 1, 2, 3, 4, 5, 6 }), serialBigSampleB); + + SerializationUtils.serialize(new Sample(new NestedSample(null)), serialSampleC); + SerializationUtils.serialize(new Sample(new NestedSample(new Sample("deep"))), serialBigSampleC); + } + + @Test + void whenSmallObjectContext_thenCorrectFilterApplied() { + Set result = new SmallObjectService().process( // + bytes(serialSampleA), // + bytes(serialBigSampleA)); + + assertEquals(1, result.size()); + assertEquals("simple", ((Sample) result.iterator() + .next()).getName()); + } + + @Test + void whenLimitedArrayContext_thenCorrectFilterApplied() { + Set result = new LimitedArrayService().process( // + bytes(serialSampleB), // + bytes(serialBigSampleB)); + + assertEquals(1, result.size()); + } + + @Test + void whenLowDepthContext_thenCorrectFilterApplied() { + Set result = new LowDepthService().process( // + bytes(serialSampleC), // + bytes(serialBigSampleC)); + + assertEquals(1, result.size()); + } + + @Test + void givenExtraFilter_whenCombinedContext_thenMergedFiltersApplied() { + Set result = new LowDepthService().process( // + FilterUtils.safeSizeFilter(190), // + bytes(serialSampleA), // + bytes(serialBigSampleA), // + bytes(serialSampleC), // + bytes(serialBigSampleC)); + + assertEquals(1, result.size()); + assertEquals("simple", ((Sample) result.iterator() + .next()).getName()); + } + + @Test + void givenFallbackContext_whenUsingBaseClasses_thenRestrictiveFilterApplied() throws IOException { + String a = new String("a"); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + SerializationUtils.serialize(a, outStream); + + String deserializedA = (String) DeserializationUtils.deserialize(bytes(outStream)); + + assertEquals(a, deserializedA); + } + + @Test + void givenFallbackContext_whenUsingAppClasses_thenRejected() throws IOException { + Sample a = new Sample("a"); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + SerializationUtils.serialize(a, outStream); + + Sample deserializedA = (Sample) DeserializationUtils.deserialize(bytes(outStream)); + + assertNull(deserializedA); + } +} From 290147ff08d2d194a8a054a98301f51dc069f3a6 Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Fri, 17 Nov 2023 00:27:43 +0200 Subject: [PATCH 228/233] This PR is related to BAEL-7181 (#15230) * Update TimestampToLongUnitTest.java * Update TimestampToLong.java --- .../timestamptolong/TimestampToLong.java | 31 +++++++-------- .../TimestampToLongUnitTest.java | 39 +++++++------------ 2 files changed, 30 insertions(+), 40 deletions(-) diff --git a/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java index 2ebe30f4ff..25a8a57ba7 100644 --- a/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java +++ b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java @@ -1,32 +1,31 @@ package com.baeldung.timestamptolong; -import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.Date; public class TimestampToLong { - public void usingSimpleDateFormat() throws ParseException { + + public long usingSimpleDateFormat(String timestampString) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String currentDateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); - long actualTimestamp = sdf.parse(currentDateString).getTime(); + Date date = sdf.parse(timestampString); + String currentDateString = sdf.format(date); + return sdf.parse(currentDateString).getTime(); } - public void usingInstantClass() { - Instant instant = Instant.now(); - long actualTimestamp = instant.toEpochMilli(); + public long usingInstantClass(String timestampString) { + Instant instant = LocalDateTime.parse(timestampString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + .atZone(ZoneId.systemDefault()) + .toInstant(); + return instant.toEpochMilli(); } - public void usingTimestamp() { - Timestamp timestamp = new Timestamp(System.currentTimeMillis()); - long actualTimestamp = timestamp.getTime(); + public long usingJava8DateTime(String timestampString) { + LocalDateTime localDateTime = LocalDateTime.parse(timestampString.replace(" ", "T")); + return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } - - public void usingJava8DateTime() { - LocalDateTime localDateTime = LocalDateTime.now(); - long actualTimestamp = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); - } -} \ No newline at end of file +} diff --git a/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java index ede8f7792d..868d019cf2 100644 --- a/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java +++ b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java @@ -2,51 +2,42 @@ package com.baeldung.timestamptolong; import org.junit.Test; -import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.Date; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; public class TimestampToLongUnitTest { - - private static final long TOLERANCE = 1000; + private static final String timestampString = "2023-11-15 01:02:03"; @Test - public void givenSimpleDateFormat_whenFormattingDate_thenTConvertToLong() throws ParseException { + public void givenSimpleDateFormat_whenFormattingDate_thenConvertToLong() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date = sdf.parse(timestampString); - String currentDateString = sdf.format(new Date()); + String currentDateString = sdf.format(date); long actualTimestamp = sdf.parse(currentDateString).getTime(); - - assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + assertEquals(1700010123000L, actualTimestamp); } @Test - public void givenInstantClass_whenGettingTimestamp_thenTConvertToLong() { - Instant instant = Instant.now(); + public void givenInstantClass_whenGettingTimestamp_thenConvertToLong() { + Instant instant = LocalDateTime.parse(timestampString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + .atZone(ZoneId.systemDefault()) + .toInstant(); long actualTimestamp = instant.toEpochMilli(); - - assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + assertEquals(1700010123000L, actualTimestamp); } @Test - public void givenTimestamp_whenCreatingTimestamp_thenTConvertToLong() { - Timestamp timestamp = new Timestamp(System.currentTimeMillis()); - long actualTimestamp = timestamp.getTime(); - - assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); - } - - @Test - public void givenJava8DateTime_whenGettingTimestamp_thenTConvertToLong() { - LocalDateTime localDateTime = LocalDateTime.now(); + public void givenJava8DateTime_whenGettingTimestamp_thenConvertToLong() { + LocalDateTime localDateTime = LocalDateTime.parse(timestampString.replace(" ", "T")); long actualTimestamp = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); - - assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + assertEquals(1700010123000L, actualTimestamp); } } From 9d441e11b8d53128f733643e3333809564ac6268 Mon Sep 17 00:00:00 2001 From: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> Date: Fri, 17 Nov 2023 01:47:49 +0200 Subject: [PATCH 229/233] This commit is related to the article BAEL-7172 (#15232) This commit aims to add two classes that provide insights about the time complexity of Collections.sort(). --- .../CollectionsSortTimeComplexityJMH.java | 60 +++++++++++++++++++ .../CollectionsSortTimeComplexityMain.java | 33 ++++++++++ 2 files changed, 93 insertions(+) create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionssortcomplexity/CollectionsSortTimeComplexityJMH.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionssortcomplexity/CollectionsSortTimeComplexityMain.java diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionssortcomplexity/CollectionsSortTimeComplexityJMH.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionssortcomplexity/CollectionsSortTimeComplexityJMH.java new file mode 100644 index 0000000000..766a89f674 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionssortcomplexity/CollectionsSortTimeComplexityJMH.java @@ -0,0 +1,60 @@ +package com.baeldung.collectionssortcomplexity; + +import org.openjdk.jmh.annotations.*; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Fork(value = 1, warmups = 1) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 5, time = 1) +public class CollectionsSortTimeComplexityJMH { + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + + } + + @Benchmark + public void measureCollectionsSortBestCase(BestCaseBenchmarkState state) { + List sortedList = new ArrayList<>(state.sortedList); + Collections.sort(sortedList); + } + + @Benchmark + public void measureCollectionsSortAverageWorstCase(AverageWorstCaseBenchmarkState state) { + List unsortedList = new ArrayList<>(state.unsortedList); + Collections.sort(unsortedList); + } + + @State(Scope.Benchmark) + public static class BestCaseBenchmarkState { + List sortedList; + + @Setup(Level.Trial) + public void setUp() { + sortedList = new ArrayList<>(); + for (int i = 1; i <= 1000000; i++) { + sortedList.add(i); + } + } + } + + @State(Scope.Benchmark) + public static class AverageWorstCaseBenchmarkState { + List unsortedList; + + @Setup(Level.Trial) + public void setUp() { + unsortedList = new ArrayList<>(); + for (int i = 1000000; i > 0; i--) { + unsortedList.add(i); + } + } + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionssortcomplexity/CollectionsSortTimeComplexityMain.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionssortcomplexity/CollectionsSortTimeComplexityMain.java new file mode 100644 index 0000000000..f273d3562a --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionssortcomplexity/CollectionsSortTimeComplexityMain.java @@ -0,0 +1,33 @@ +package com.baeldung.collectionssortcomplexity; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class CollectionsSortTimeComplexityMain { + // O(n log n) Time Complexity Example + public static void worstAndAverageCasesTimeComplexity() { + Integer[] sortedArray = {20, 21, 22, 23, 24, 25, 26, 17, 28, 29, 30, 31, 18, 19, 32, 33, 34, 27, 35}; + List list = Arrays.asList(sortedArray); + Collections.shuffle(list); + long startTime = System.nanoTime(); + Collections.sort(list); + long endTime = System.nanoTime(); + System.out.println("Execution Time for O(n log n): " + (endTime - startTime) + " nanoseconds"); + } + + // O(n) Time Complexity Example + public static void bestCaseTimeComplexity() { + Integer[] sortedArray = {19, 22, 19, 22, 24, 25, 17, 11, 22, 23, 28, 23, 0, 1, 12, 9, 13, 27, 15}; + List list = Arrays.asList(sortedArray); + long startTime = System.nanoTime(); + Collections.sort(list); + long endTime = System.nanoTime(); + System.out.println("Execution Time for O(n): " + (endTime - startTime) + " nanoseconds"); + } + + public static void main(String[] args) { + worstAndAverageCasesTimeComplexity(); + bestCaseTimeComplexity(); + } +} From e5215678f385ee012464311a3064835c70129325 Mon Sep 17 00:00:00 2001 From: timis1 Date: Thu, 16 Nov 2023 09:17:03 +0200 Subject: [PATCH 230/233] JAVA-27449 Fix test in libraries-data-io module --- .../com/baeldung/libraries/opencsv/OpenCsvIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 7cfe8984e7..6745b9be7f 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 @@ -74,7 +74,7 @@ public class OpenCsvIntegrationTest { assertThat(contents.split(NEW_LINE)) .containsExactly( - "'colA','colB','colC'", + "'COLA','COLB','COLC'", "'Test1','sample','data'", "'Test2','ipso','facto'" ); From 7f88b9748e82bd6b51f37ae9bfb6981a062a9b98 Mon Sep 17 00:00:00 2001 From: Maiklins Date: Fri, 17 Nov 2023 21:24:13 +0100 Subject: [PATCH 231/233] Update and rename ProfileIntegrationStubTest.java to ProfileStubIntegrationTest.java Satisfy test naming convention --- ...IntegrationStubTest.java => ProfileStubIntegrationTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/{ProfileIntegrationStubTest.java => ProfileStubIntegrationTest.java} (97%) diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationStubTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileStubIntegrationTest.java similarity index 97% rename from spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationStubTest.java rename to spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileStubIntegrationTest.java index e1c88f2a31..2d6eb06d32 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationStubTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileStubIntegrationTest.java @@ -18,7 +18,7 @@ import com.baeldung.overridebean.boot.Application; @SpringBootTest(classes = { Application.class, ProfileConfig.class, Endpoint.class, ProfileTestConfig.class }) @AutoConfigureMockMvc @ActiveProfiles("stub") -class ProfileIntegrationStubTest { +class ProfileStubIntegrationTest { @Autowired private MockMvc mockMvc; From 92ef912fcf29b2fd755560dad3fdcdf67a89fb59 Mon Sep 17 00:00:00 2001 From: Maiklins Date: Fri, 17 Nov 2023 21:24:57 +0100 Subject: [PATCH 232/233] Update and rename ProfileIntegrationMockTest.java to ProfileMockIntegrationTest.java Satisfy naming convention --- ...IntegrationMockTest.java => ProfileMockIntegrationTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/{ProfileIntegrationMockTest.java => ProfileMockIntegrationTest.java} (97%) diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationMockTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileMockIntegrationTest.java similarity index 97% rename from spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationMockTest.java rename to spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileMockIntegrationTest.java index 43fb69860d..2fac6d954a 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileIntegrationMockTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/overridebean/profile/ProfileMockIntegrationTest.java @@ -20,7 +20,7 @@ import com.baeldung.overridebean.boot.Application; @SpringBootTest(classes = { Application.class, ProfileConfig.class, Endpoint.class, ProfileTestConfig.class }) @AutoConfigureMockMvc @ActiveProfiles("mock") -class ProfileIntegrationMockTest { +class ProfileMockIntegrationTest { @Autowired private MockMvc mockMvc; From 6cbd1b5b5229d8839b265f41590580570e56f94b Mon Sep 17 00:00:00 2001 From: mikr Date: Fri, 17 Nov 2023 21:32:43 +0100 Subject: [PATCH 233/233] Update readme --- spring-boot-modules/spring-boot-testing-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-testing-2/README.md b/spring-boot-modules/spring-boot-testing-2/README.md index 1baf83bf34..fbf708381b 100644 --- a/spring-boot-modules/spring-boot-testing-2/README.md +++ b/spring-boot-modules/spring-boot-testing-2/README.md @@ -14,4 +14,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot – Testing Redis With Testcontainers](https://www.baeldung.com/spring-boot-redis-testcontainers) - [Spring Boot – Keycloak Integration Testing with Testcontainers](https://www.baeldung.com/spring-boot-keycloak-integration-testing) - [Difference Between @Spy and @SpyBean](https://www.baeldung.com/spring-spy-vs-spybean) +- [Overriding Spring Beans in Integration Test](https://www.baeldung.com/overriding-spring-beans-in-integration-test) - More articles: [[<-- prev]](../spring-boot-testing)