From 73c2c6bc6737fcd788025c9b446aef4371a178e4 Mon Sep 17 00:00:00 2001 From: technoddy Date: Sun, 19 Mar 2023 13:32:11 -0400 Subject: [PATCH 01/98] Creating shallow copy vs deep copy in Java --- .../baeldung/shallowvsdeepcopy/Address.java | 58 +++++++++++++++++++ .../shallowvsdeepcopy/UserWithDeepClone.java | 49 ++++++++++++++++ .../UserWithShallowClone.java | 48 +++++++++++++++ .../shallowvsdeepcopy/UserCloneUnitTest.java | 23 ++++++++ 4 files changed, 178 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/Address.java create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/UserWithDeepClone.java create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/UserWithShallowClone.java create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowvsdeepcopy/UserCloneUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/Address.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/Address.java new file mode 100644 index 0000000000..a31e8d7e2d --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/Address.java @@ -0,0 +1,58 @@ +package com.baeldung.shallowvsdeepcopy; + +class Address implements Cloneable{ + + private String streetName; + private String zipCode; + private String cityName; + private String country; + + public Address(String streetName, String zipCode, String cityName, String country) { + this.streetName = streetName; + this.zipCode = zipCode; + this.cityName = cityName; + this.country = country; + } + + public String getStreetName() { + return streetName; + } + + public void setStreetName(String streetName) { + this.streetName = streetName; + } + + public String getZipCode() { + return zipCode; + } + + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } + + public String getCityName() { + return cityName; + } + + public void setCityName(String cityName) { + this.cityName = cityName; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @Override + public Address clone() { + try { + Address clone = (Address) super.clone(); + return clone; + } catch (CloneNotSupportedException e) { + throw new AssertionError(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/UserWithDeepClone.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/UserWithDeepClone.java new file mode 100644 index 0000000000..70646d396c --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/UserWithDeepClone.java @@ -0,0 +1,49 @@ +package com.baeldung.shallowvsdeepcopy; + +public class UserWithDeepClone implements Cloneable{ + + private String name; + private Address address; + private int age; + + public UserWithDeepClone(String name, Address address, int age) { + this.name = name; + this.address = address; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public UserWithDeepClone clone() { + try { + UserWithDeepClone clone = (UserWithDeepClone) super.clone(); + clone.setAddress(clone.getAddress().clone()); + return clone; + } catch (CloneNotSupportedException e) { + throw new AssertionError(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/UserWithShallowClone.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/UserWithShallowClone.java new file mode 100644 index 0000000000..19c9b55412 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowvsdeepcopy/UserWithShallowClone.java @@ -0,0 +1,48 @@ +package com.baeldung.shallowvsdeepcopy; + +public class UserWithShallowClone implements Cloneable{ + + private String name; + private Address address; + private int age; + + public UserWithShallowClone(String name, Address address, int age) { + this.name = name; + this.address = address; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public UserWithShallowClone clone() { + try { + UserWithShallowClone clone = (UserWithShallowClone) super.clone(); + return clone; + } catch (CloneNotSupportedException e) { + throw new AssertionError(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowvsdeepcopy/UserCloneUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowvsdeepcopy/UserCloneUnitTest.java new file mode 100644 index 0000000000..f5a7d9df93 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowvsdeepcopy/UserCloneUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.shallowvsdeepcopy; +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class UserCloneUnitTest { + + @Test + public void givenUser_WhenCopyCreated_thenCopyIsShallow(){ + Address address = new Address("abc", "444-0000", "pqr", "USA"); + UserWithShallowClone user = new UserWithShallowClone("baeldung", address,32); + + UserWithShallowClone userClone = (UserWithShallowClone)user.clone(); + assertThat(userClone.getAddress()).isEqualTo(user.getAddress()); + } + + @Test + public void givenUserWithDeepCloneMethod_WhenCopyCreated_thenCopyIsDeep(){ + Address address = new Address("abc", "444-0000", "pqr", "USA"); + UserWithDeepClone user = new UserWithDeepClone("baeldung", address,32); + UserWithDeepClone userClone = (UserWithDeepClone)user.clone(); + assertThat(userClone.getAddress()).isNotEqualTo(user.getAddress()); + } +} \ No newline at end of file From 21f1631e834117f2d91801cd8ed47b89aa937fce Mon Sep 17 00:00:00 2001 From: Fabio Bento Luiz Date: Sat, 25 Mar 2023 19:57:45 +0100 Subject: [PATCH 02/98] Get the user id from the original event instead of creating a new oe --- .../java/com/baeldung/patterns/es/service/UserUtility.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/patterns-modules/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java b/patterns-modules/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java index e44e404588..0833457507 100644 --- a/patterns-modules/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java +++ b/patterns-modules/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java @@ -23,8 +23,7 @@ public class UserUtility { for (Event event : events) { if (event instanceof UserCreatedEvent) { UserCreatedEvent e = (UserCreatedEvent) event; - user = new User(UUID.randomUUID() - .toString(), e.getFirstName(), e.getLastName()); + user = new User(e.getUserId(), e.getFirstName(), e.getLastName()); } if (event instanceof UserAddressAddedEvent) { UserAddressAddedEvent e = (UserAddressAddedEvent) event; From aeb0bd3bd78e4842e6be6ebb386b40314f8d147f Mon Sep 17 00:00:00 2001 From: "press0@gmail.com" Date: Mon, 10 Apr 2023 10:37:33 -0500 Subject: [PATCH 03/98] PR --- .../com/baeldung/algorithms/dfs/Graph.java | 10 ++++++---- .../baeldung/algorithms/dfs/GraphUnitTest.java | 13 ++++++++++--- .../com/baeldung/equalshashcode/Voucher.java | 2 +- .../baeldung/equalshashcode/MoneyUnitTest.java | 18 ++++++++++++++---- 4 files changed, 31 insertions(+), 12 deletions(-) diff --git a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java b/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java index 4623dbb7a4..49cf3fe2bd 100644 --- a/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java +++ b/algorithms-modules/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java @@ -23,7 +23,7 @@ public class Graph { adjVertices.get(src).add(dest); } - public void dfsWithoutRecursion(int start) { + public boolean[] dfsWithoutRecursion(int start) { Stack stack = new Stack(); boolean[] isVisited = new boolean[adjVertices.size()]; stack.push(start); @@ -38,20 +38,22 @@ public class Graph { } } } + return isVisited; } - public void dfs(int start) { + public boolean[] dfs(int start) { boolean[] isVisited = new boolean[adjVertices.size()]; - dfsRecursive(start, isVisited); + return dfsRecursive(start, isVisited); } - private void dfsRecursive(int current, boolean[] isVisited) { + private boolean[] dfsRecursive(int current, boolean[] isVisited) { isVisited[current] = true; visit(current); for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) dfsRecursive(dest, isVisited); } + return isVisited; } public List topologicalSort(int start) { diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java index 086eb77a82..2761062e91 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java @@ -1,7 +1,9 @@ package com.baeldung.algorithms.dfs; +import java.util.Arrays; import java.util.List; +import org.junit.Assert; import org.junit.jupiter.api.Test; class GraphUnitTest { @@ -9,9 +11,12 @@ class GraphUnitTest { @Test void givenDirectedGraph_whenDFS_thenPrintAllValues() { Graph graph = createDirectedGraph(); - graph.dfs(0); - System.out.println(); - graph.dfsWithoutRecursion(0); + boolean[] visited; + visited = graph.dfs(0); + boolean[] expected = new boolean[]{true, true, true, true, true, true}; + Assert.assertArrayEquals(expected, visited); + visited = graph.dfsWithoutRecursion(0); + Assert.assertArrayEquals(expected, visited); } @Test @@ -19,6 +24,8 @@ class GraphUnitTest { Graph graph = createDirectedGraph(); List list = graph.topologicalSort(0); System.out.println(list); + List expected = Arrays.asList(0, 2, 1, 3, 4, 5); + Assert.assertEquals(expected, list); } private Graph createDirectedGraph() { diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Voucher.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Voucher.java index 19f46e0358..6754ee9d30 100644 --- a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Voucher.java +++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/equalshashcode/Voucher.java @@ -16,7 +16,7 @@ class Voucher { return true; if (!(o instanceof Voucher)) return false; - Voucher other = (Voucher)o; + Voucher other = (Voucher) o; boolean valueEquals = (this.value == null && other.value == null) || (this.value != null && this.value.equals(other.value)); boolean storeEquals = (this.store == null && other.store == null) diff --git a/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java index 8fc99e0e81..dd6f36e0e4 100644 --- a/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java +++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java @@ -13,15 +13,25 @@ public class MoneyUnitTest { Money expenses = new Money(55, "USD"); assertTrue(income.equals(expenses)); + assertTrue(expenses.equals(income)); + } + + @Test + public void givenMoneyAndWrongVoucherInstances_whenEquals_thenReturnValuesArentSymmetric() { + Money money = new Money(42, "USD"); + WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon"); + + assertFalse(voucher.equals(money)); + assertTrue(money.equals(voucher)); } @Test public void givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric() { - Money cash = new Money(42, "USD"); - WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon"); + Money money = new Money(42, "USD"); + Voucher voucher = new Voucher(42, "USD", "Amazon"); - assertFalse(voucher.equals(cash)); - assertTrue(cash.equals(voucher)); + assertFalse(voucher.equals(money)); + assertFalse(money.equals(voucher)); } } From 00028b8b19ed41f7d7afc473e8138e1c97ef26ce Mon Sep 17 00:00:00 2001 From: Kingsley Amankwah Date: Fri, 21 Apr 2023 04:48:52 +0530 Subject: [PATCH 04/98] JPA/Hibernate Associations --- .../baeldung/association/Bidirectional.java | 40 ++++++++ .../baeldung/association/Unidirectional.java | 92 ++++++++++++++++++ .../association/BidirectionalUnitTest.java | 48 +++++++++ .../association/UnidirectionalUnitTest.java | 97 +++++++++++++++++++ 4 files changed, 277 insertions(+) create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Bidirectional.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Unidirectional.java create mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/BidirectionalUnitTest.java create mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/UnidirectionalUnitTest.java diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Bidirectional.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Bidirectional.java new file mode 100644 index 0000000000..aff5feaeba --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Bidirectional.java @@ -0,0 +1,40 @@ +package com.baeldung.association; + +import java.util.List; +import javax.persistence.*; + +@Entity +public class Department { + + @OneToMany(mappedBy = "department") + private List employees; + +} + +@Entity +public class Employee { + + @ManyToOne + @JoinColumn(name = "department_id") + private Department department; + +} + +@Entity +public class Student { + + @ManyToMany(mappedBy = "students") + private List courses; + +} + +@Entity +public class Course { + + @ManyToMany + @JoinTable(name = "course_student", + joinColumns = @JoinColumn(name = "course_id"), + inverseJoinColumns = @JoinColumn(name = "student_id")) + private List students; + +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Unidirectional.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Unidirectional.java new file mode 100644 index 0000000000..3e60b8bdd3 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Unidirectional.java @@ -0,0 +1,92 @@ +package com.baeldung.association; + +import javax.persistence.*; + +import java.util.List; +import java.util.Set; + +@Entity +public class Department { + + @Id + private Long id; + + @OneToMany + @JoinColumn(name = "department_id") + private List employees; + +} + +@Entity +public class Employee { + + @Id + private Long id; + + @OneToOne + @JoinColumn(name = "parking_spot_id") + private ParkingSpot parkingSpot; + +} + +@Entity +public class ParkingSpot { + + @Id + private Long id; + +} + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + + @ManyToOne + @JoinColumn(name = "course_id") + private Course course; + +} + +@Entity +public class Course { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + +} + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String title; + + @ManyToMany + @JoinTable(name = "book_author", + joinColumns = @JoinColumn(name = "book_id"), + inverseJoinColumns = @JoinColumn(name = "author_id")) + private Set authors; + +} + +@Entity +public class Author { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + +} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/BidirectionalUnitTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/BidirectionalUnitTest.java new file mode 100644 index 0000000000..99d33af12d --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/BidirectionalUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.association; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class BidirectionalUnitTest { + + @Test + public void givenDepartmentWithEmployees_whenGetEmployees_thenReturnListWithEmployees() { + // given + Department department = new Department(); + Employee employee1 = new Employee(); + Employee employee2 = new Employee(); + department.getEmployees().add(employee1); + department.getEmployees().add(employee2); + + // when + List result = department.getEmployees(); + + // then + assertAll("department employees", + () -> assertEquals(2, result.size()), + () -> assertTrue(result.contains(employee1)), + () -> assertTrue(result.contains(employee2)) + ); + } + + @Test + public void givenCourseWithStudents_whenGetStudents_thenReturnListWithStudents() { + // given + Course course = new Course(); + Student student1 = new Student(); + Student student2 = new Student(); + course.getStudents().add(student1); + course.getStudents().add(student2); + + // when + List result = course.getStudents(); + + // then + assertAll("course students", + () -> assertEquals(2, result.size()), + () -> assertTrue(result.contains(student1)), + () -> assertTrue(result.contains(student2)) + ); + } + +} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/UnidirectionalUnitTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/UnidirectionalUnitTest.java new file mode 100644 index 0000000000..880832c163 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/UnidirectionalUnitTest.java @@ -0,0 +1,97 @@ +package com.baeldung.association; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@DataJpaTest +public class UnidirectionalUnitTest { + + private final TestEntityManager entityManager; + + public UnidirectionalUnitTest(TestEntityManager entityManager) { + this.entityManager = entityManager; + } + + @Test + public void givenDepartmentWithEmployees_whenFindById_thenDepartmentWithEmployeesReturned() { + // given + Employee employee1 = new Employee(); + Employee employee2 = new Employee(); + Department department = new Department(); + department.setEmployees(List.of(employee1, employee2)); + entityManager.persist(department); + entityManager.flush(); + + // when + Department foundDepartment = entityManager.find(Department.class, department.getId()); + + // then + assertThat(foundDepartment).isEqualTo(department); + assertThat(foundDepartment.getEmployees()).containsExactly(employee1, employee2); + } + + @Test + public void givenStudentWithCourse_whenFindById_thenStudentWithCourseReturned() { + // given + Course course = new Course(); + entityManager.persist(course); + entityManager.flush(); + Student student = new Student(); + student.setCourse(course); + entityManager.persist(student); + entityManager.flush(); + + // when + Student foundStudent = entityManager.find(Student.class, student.getId()); + + // then + assertThat(foundStudent).isEqualTo(student); + assertThat(foundStudent.getCourse()).isEqualTo(course); + } + + @Test + public void givenEmployeeWithParkingSpot_whenFindById_thenEmployeeWithParkingSpotReturned() { + // given + ParkingSpot parkingSpot = new ParkingSpot(); + entityManager.persist(parkingSpot); + entityManager.flush(); + Employee employee = new Employee(); + employee.setParkingSpot(parkingSpot); + entityManager.persist(employee); + entityManager.flush(); + + // when + Employee foundEmployee = entityManager.find(Employee.class, employee.getId()); + + // then + assertThat(foundEmployee).isEqualTo(employee); + assertThat(foundEmployee.getParkingSpot()).isEqualTo(parkingSpot); + } + + @Test + public void givenBookWithAuthors_whenFindById_thenBookWithAuthorsReturned() { + // given + Author author1 = new Author(); + Author author2 = new Author(); + entityManager.persist(author1); + entityManager.persist(author2); + entityManager.flush(); + Book book = new Book(); + book.setAuthors(Set.of(author1, author2)); + entityManager.persist(book); + entityManager.flush(); + + // when + Book foundBook = entityManager.find(Book.class, book.getId()); + + // then + assertThat(foundBook).isEqualTo(book); + assertThat(foundBook.getAuthors()).containsExactly(author1, author2); + } + +} From 82f9d6a50060568bbe679c12223324b074fa5427 Mon Sep 17 00:00:00 2001 From: Kingsley Amankwah Date: Thu, 27 Apr 2023 05:00:38 +0530 Subject: [PATCH 05/98] Hibernate Associations --- .../main/java/com/baeldung/HibernateUtil.java | 2 + .../baeldung/association/Bidirectional.java | 40 ------ .../baeldung/association/Unidirectional.java | 92 ------------- .../associations/biredirectional/Course.java | 24 ++++ .../biredirectional/Department.java | 21 +++ .../biredirectional/Employee.java | 19 +++ .../associations/biredirectional/Student.java | 20 +++ .../associations/unidirectional/Author.java | 17 +++ .../associations/unidirectional/Book.java | 20 +++ .../unidirectional/Department.java | 33 +++++ .../associations/unidirectional/Employee.java | 42 ++++++ .../unidirectional/ParkingSpot.java | 11 ++ .../association/BidirectionalUnitTest.java | 48 ------- .../association/UnidirectionalUnitTest.java | 97 ------------- .../associations/BidirectionalUnitTest.java | 103 ++++++++++++++ .../hibernate/associations/DataJpaTest.java | 5 + .../associations/UnidirectionalUnitTest.java | 128 ++++++++++++++++++ 17 files changed, 445 insertions(+), 277 deletions(-) delete mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Bidirectional.java delete mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Unidirectional.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Course.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Department.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Employee.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Student.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Author.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Book.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Department.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Employee.java create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/ParkingSpot.java delete mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/BidirectionalUnitTest.java delete mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/UnidirectionalUnitTest.java create mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/BidirectionalUnitTest.java create mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/DataJpaTest.java create mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/UnidirectionalUnitTest.java diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/HibernateUtil.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/HibernateUtil.java index 26ad7e77ba..8af6b12bae 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/HibernateUtil.java @@ -7,6 +7,7 @@ import org.hibernate.service.ServiceRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +// import com.baeldung.associations.unidirectional.Department; import com.baeldung.manytomany.model.Employee; import com.baeldung.manytomany.model.Project; import com.baeldung.uuids.WebSiteUser; @@ -29,6 +30,7 @@ public class HibernateUtil { configuration.addAnnotatedClass(Element.class); configuration.addAnnotatedClass(Reservation.class); configuration.addAnnotatedClass(Sale.class); + // configuration.addAnnotatedClass(Department.class); configuration.configure("manytomany.cfg.xml"); LOGGER.debug("Hibernate Annotation Configuration loaded"); diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Bidirectional.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Bidirectional.java deleted file mode 100644 index aff5feaeba..0000000000 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Bidirectional.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.association; - -import java.util.List; -import javax.persistence.*; - -@Entity -public class Department { - - @OneToMany(mappedBy = "department") - private List employees; - -} - -@Entity -public class Employee { - - @ManyToOne - @JoinColumn(name = "department_id") - private Department department; - -} - -@Entity -public class Student { - - @ManyToMany(mappedBy = "students") - private List courses; - -} - -@Entity -public class Course { - - @ManyToMany - @JoinTable(name = "course_student", - joinColumns = @JoinColumn(name = "course_id"), - inverseJoinColumns = @JoinColumn(name = "student_id")) - private List students; - -} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Unidirectional.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Unidirectional.java deleted file mode 100644 index 3e60b8bdd3..0000000000 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/association/Unidirectional.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.baeldung.association; - -import javax.persistence.*; - -import java.util.List; -import java.util.Set; - -@Entity -public class Department { - - @Id - private Long id; - - @OneToMany - @JoinColumn(name = "department_id") - private List employees; - -} - -@Entity -public class Employee { - - @Id - private Long id; - - @OneToOne - @JoinColumn(name = "parking_spot_id") - private ParkingSpot parkingSpot; - -} - -@Entity -public class ParkingSpot { - - @Id - private Long id; - -} - -@Entity -public class Student { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - private String name; - - @ManyToOne - @JoinColumn(name = "course_id") - private Course course; - -} - -@Entity -public class Course { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - private String name; - -} - -@Entity -public class Book { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - private String title; - - @ManyToMany - @JoinTable(name = "book_author", - joinColumns = @JoinColumn(name = "book_id"), - inverseJoinColumns = @JoinColumn(name = "author_id")) - private Set authors; - -} - -@Entity -public class Author { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - private String name; - -} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Course.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Course.java new file mode 100644 index 0000000000..aadc08c090 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Course.java @@ -0,0 +1,24 @@ +package com.baeldung.associations.biredirectional; +import jakarta.persistence.*; +import java.util.List; + +@Entity +public class Course { + + @Id + private Long id; + + private String name; + + @ManyToMany + @JoinTable(name = "course_student", + joinColumns = @JoinColumn(name = "course_id"), + inverseJoinColumns = @JoinColumn(name = "student_id")) + private List students; + + public List getStudents() { + return students; + } + + //getters and setters +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Department.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Department.java new file mode 100644 index 0000000000..23f56ccd47 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Department.java @@ -0,0 +1,21 @@ +package com.baeldung.associations.biredirectional; + +import java.util.List; +import jakarta.persistence.*; + + +@Entity +public class Department { + + @Id + private Long id; + + @OneToMany(mappedBy = "department") + private List employees; + + public List getEmployees() { + return employees; + } + + +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Employee.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Employee.java new file mode 100644 index 0000000000..92514b9b8c --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Employee.java @@ -0,0 +1,19 @@ +package com.baeldung.associations.biredirectional; + +import jakarta.persistence.*; + + +@Entity +public class Employee { + + @Id + private Long id; + + private String name; + + @ManyToOne + @JoinColumn(name = "department_id") + private Department department; + + //getters and setters +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Student.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Student.java new file mode 100644 index 0000000000..a494f2475f --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Student.java @@ -0,0 +1,20 @@ +package com.baeldung.associations.biredirectional; + +import java.util.List; + +import jakarta.persistence.*; + +@Entity +public class Student { + + @Id + private Long id; + + private String name; + + @ManyToMany(mappedBy = "students") + private List courses; + + // getters and setters +} + diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Author.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Author.java new file mode 100644 index 0000000000..6a106071a1 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Author.java @@ -0,0 +1,17 @@ +package com.baeldung.associations.unidirectional; +import jakarta.persistence.*; +import java.util.Set; + +@Entity +public class Author { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + + @ManyToMany(fetch = FetchType.LAZY, mappedBy = "authors") + private Set books; + +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Book.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Book.java new file mode 100644 index 0000000000..1467a819a0 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Book.java @@ -0,0 +1,20 @@ +package com.baeldung.associations.unidirectional; +import jakarta.persistence.*; +import java.util.Set; + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String title; + + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable(name = "book_author", + joinColumns = @JoinColumn(name = "book_id"), + inverseJoinColumns = @JoinColumn(name = "author_id")) + private Set authors; + +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Department.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Department.java new file mode 100644 index 0000000000..3d65f2e3ef --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Department.java @@ -0,0 +1,33 @@ +package com.baeldung.associations.unidirectional; + +import jakarta.persistence.*; +import java.util.List; + +@Entity +public class Department { + + @Id + private Long id; + + @OneToMany(fetch = FetchType.LAZY) + @JoinColumn(name = "department_id") + private List employees; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} + + diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Employee.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Employee.java new file mode 100644 index 0000000000..c9fa2c7483 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Employee.java @@ -0,0 +1,42 @@ +package com.baeldung.associations.unidirectional; +import jakarta.persistence.*; + +@Entity +public class Employee { + + @Id + private Long id; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "parking_spot_id") + private ParkingSpot parkingSpot; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "department_id") + private Department department; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public ParkingSpot getParkingSpot() { + return parkingSpot; + } + + public void setParkingSpot(ParkingSpot parkingSpot) { + this.parkingSpot = parkingSpot; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } +} + diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/ParkingSpot.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/ParkingSpot.java new file mode 100644 index 0000000000..6495d895eb --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/ParkingSpot.java @@ -0,0 +1,11 @@ +package com.baeldung.associations.unidirectional; + +import jakarta.persistence.*; + +@Entity +public class ParkingSpot { + + @Id + private Long id; + +} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/BidirectionalUnitTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/BidirectionalUnitTest.java deleted file mode 100644 index 99d33af12d..0000000000 --- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/BidirectionalUnitTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.association; - -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -public class BidirectionalUnitTest { - - @Test - public void givenDepartmentWithEmployees_whenGetEmployees_thenReturnListWithEmployees() { - // given - Department department = new Department(); - Employee employee1 = new Employee(); - Employee employee2 = new Employee(); - department.getEmployees().add(employee1); - department.getEmployees().add(employee2); - - // when - List result = department.getEmployees(); - - // then - assertAll("department employees", - () -> assertEquals(2, result.size()), - () -> assertTrue(result.contains(employee1)), - () -> assertTrue(result.contains(employee2)) - ); - } - - @Test - public void givenCourseWithStudents_whenGetStudents_thenReturnListWithStudents() { - // given - Course course = new Course(); - Student student1 = new Student(); - Student student2 = new Student(); - course.getStudents().add(student1); - course.getStudents().add(student2); - - // when - List result = course.getStudents(); - - // then - assertAll("course students", - () -> assertEquals(2, result.size()), - () -> assertTrue(result.contains(student1)), - () -> assertTrue(result.contains(student2)) - ); - } - -} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/UnidirectionalUnitTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/UnidirectionalUnitTest.java deleted file mode 100644 index 880832c163..0000000000 --- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/association/UnidirectionalUnitTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.baeldung.association; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; - -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -@DataJpaTest -public class UnidirectionalUnitTest { - - private final TestEntityManager entityManager; - - public UnidirectionalUnitTest(TestEntityManager entityManager) { - this.entityManager = entityManager; - } - - @Test - public void givenDepartmentWithEmployees_whenFindById_thenDepartmentWithEmployeesReturned() { - // given - Employee employee1 = new Employee(); - Employee employee2 = new Employee(); - Department department = new Department(); - department.setEmployees(List.of(employee1, employee2)); - entityManager.persist(department); - entityManager.flush(); - - // when - Department foundDepartment = entityManager.find(Department.class, department.getId()); - - // then - assertThat(foundDepartment).isEqualTo(department); - assertThat(foundDepartment.getEmployees()).containsExactly(employee1, employee2); - } - - @Test - public void givenStudentWithCourse_whenFindById_thenStudentWithCourseReturned() { - // given - Course course = new Course(); - entityManager.persist(course); - entityManager.flush(); - Student student = new Student(); - student.setCourse(course); - entityManager.persist(student); - entityManager.flush(); - - // when - Student foundStudent = entityManager.find(Student.class, student.getId()); - - // then - assertThat(foundStudent).isEqualTo(student); - assertThat(foundStudent.getCourse()).isEqualTo(course); - } - - @Test - public void givenEmployeeWithParkingSpot_whenFindById_thenEmployeeWithParkingSpotReturned() { - // given - ParkingSpot parkingSpot = new ParkingSpot(); - entityManager.persist(parkingSpot); - entityManager.flush(); - Employee employee = new Employee(); - employee.setParkingSpot(parkingSpot); - entityManager.persist(employee); - entityManager.flush(); - - // when - Employee foundEmployee = entityManager.find(Employee.class, employee.getId()); - - // then - assertThat(foundEmployee).isEqualTo(employee); - assertThat(foundEmployee.getParkingSpot()).isEqualTo(parkingSpot); - } - - @Test - public void givenBookWithAuthors_whenFindById_thenBookWithAuthorsReturned() { - // given - Author author1 = new Author(); - Author author2 = new Author(); - entityManager.persist(author1); - entityManager.persist(author2); - entityManager.flush(); - Book book = new Book(); - book.setAuthors(Set.of(author1, author2)); - entityManager.persist(book); - entityManager.flush(); - - // when - Book foundBook = entityManager.find(Book.class, book.getId()); - - // then - assertThat(foundBook).isEqualTo(book); - assertThat(foundBook.getAuthors()).containsExactly(author1, author2); - } - -} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/BidirectionalUnitTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/BidirectionalUnitTest.java new file mode 100644 index 0000000000..5b7e01bff1 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/BidirectionalUnitTest.java @@ -0,0 +1,103 @@ +// package com.baeldung.hibernate.associations; + +// import org.junit.jupiter.api.Test; +// import org.junit.jupiter.api.extension.ExtendWith; +// import org.springframework.beans.factory.annotation.Autowired; +// import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +// import org.springframework.test.context.junit.jupiter.SpringExtension; + +// import java.util.Arrays; +// import java.util.List; +// import com.baeldung.associations.biredirectional.*; + + +// import static org.assertj.core.api.Assertions.assertThat; + +// @ExtendWith(SpringExtension.class) +// @DataJpaTest +// public class BidirectionalHibernateIntegrationTest { + +// @Autowired +// private Course courseRepository; + +// @Autowired +// private Student studentRepository; + +// @Test +// public void whenAddingStudentsToCourse_thenCourseHasStudents() { +// // given +// Student student1 = new Student(); +// student1.setName("John"); +// Student student2 = new Student(); +// student2.setName("Jane"); +// studentRepository.saveAll(Arrays.asList(student1, student2)); + +// Course course = new Course(); +// course.setName("History"); +// courseRepository.save(course); + +// // when +// List students = studentRepository.findAll(); +// course.setStudents(students); +// courseRepository.save(course); + +// // then +// Course result = courseRepository.findById(course.getId()).get(); +// assertThat(result.getStudents()).containsExactlyInAnyOrder(student1, student2); +// } + +// } + +package com.baeldung.hibernate.associations; + + +import com.baeldung.associations.biredirectional.*; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.List; + +public class BidirectionalUnitTest { + + @Test + public void givenDepartmentWithEmployees_whenGetEmployees_thenReturnListWithEmployees() { + // given + Department department = new Department(); + Employee employee1 = new Employee(); + Employee employee2 = new Employee(); + department.getEmployees().add(employee1); + department.getEmployees().add(employee2); + + // when + List result = department.getEmployees(); + + // then + assertAll("department employees", + () -> assertEquals(2, result.size()), + () -> assertTrue(result.contains(employee1)), + () -> assertTrue(result.contains(employee2)) + ); + } + + @Test + public void givenCourseWithStudents_whenGetStudents_thenReturnListWithStudents() { + // given + Course course = new Course(); + Student student1 = new Student(); + Student student2 = new Student(); + course.getStudents().add(student1); + course.getStudents().add(student2); + + // when + List result = course.getStudents(); + + // then + assertAll("course students", + () -> assertEquals(2, result.size()), + () -> assertTrue(result.contains(student1)), + () -> assertTrue(result.contains(student2)) + ); + } + +} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/DataJpaTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/DataJpaTest.java new file mode 100644 index 0000000000..184fae20c0 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/DataJpaTest.java @@ -0,0 +1,5 @@ +package com.baeldung.hibernate.associations; + +public @interface DataJpaTest { + +} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/UnidirectionalUnitTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/UnidirectionalUnitTest.java new file mode 100644 index 0000000000..790110a6d7 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/UnidirectionalUnitTest.java @@ -0,0 +1,128 @@ + +// // import org.junit.jupiter.api.Assertions; +// // import org.junit.jupiter.api.Test; +// // import org.springframework.beans.factory.annotation.Autowired; +// // import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +// // import org.springframework.boot.test.context.SpringBootTest; +// // import org.springframework.transaction.annotation.Transactional; + +// // import java.util.Collections; +// // import java.util.List; + +// // @DataJpaTest +// // @Transactional +// // public class UnidirectionalUnitTest { + +// // @Autowired +// // private EntityManager entityManager; + +// // @Test +// // public void givenBookWithAuthor_whenSaved_thenFindBookByAuthor() { +// // // given +// // Author author = new Author(); +// // author.setName("John Doe"); + +// // Book book = new Book(); +// // book.setTitle("My Book"); +// // book.setAuthors(Collections.singleton(author)); + +// // entityManager.persist(author); +// // entityManager.persist(book); + +// // entityManager.flush(); +// // entityManager.clear(); + +// // // when +// // List booksByAuthor = entityManager.createQuery( +// // "select b from Book b join b.authors a where a.name = :name", Book.class) +// // .setParameter("name", "John Doe") +// // .getResultList(); + +// // // then +// // Assertions.assertEquals(1, booksByAuthor.size()); +// // Assertions.assertEquals(book, booksByAuthor.get(0)); +// // } +// // } + + +// package com.baeldung.hibernate.associations; + +// import com.baeldung.associations.unidirectional.*; + +// import org.junit.jupiter.api.Test; +// import org.springframework.beans.factory.annotation.Autowired; +// import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +// import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; + +// import java.util.List; +// import java.util.Set; + +// import static org.assertj.core.api.Assertions.assertThat; + +// @DataJpaTest +// public class UnidirectionalUnitTest { + +// @Autowired +// private TestEntityManager entityManager; + +// @Test +// public void givenDepartmentWithEmployees_whenFindById_thenDepartmentWithEmployeesReturned() { +// // given +// Employee employee1 = new Employee(); +// Employee employee2 = new Employee(); +// Department department = new Department(); +// department.setEmployees(List.of(employee1, employee2)); +// entityManager.persist(department); +// entityManager.flush(); + +// // when +// Department foundDepartment = entityManager.find(Department.class, department.getId()); + +// // then +// assertThat(foundDepartment).isEqualTo(department); +// assertThat(foundDepartment.getEmployees()).containsExactly(employee1, employee2); +// } + +// @Test +// public void givenEmployeeWithParkingSpot_whenFindById_thenEmployeeWithParkingSpotReturned() { +// // given +// ParkingSpot parkingSpot = new ParkingSpot(); +// entityManager.persist(parkingSpot); +// entityManager.flush(); +// Employee employee = new Employee(); +// employee.setParkingSpot(parkingSpot); +// entityManager.persist(employee); +// entityManager.flush(); + +// // when +// Employee foundEmployee = entityManager.find(Employee.class, employee.getId()); + +// // then +// assertThat(foundEmployee).isEqualTo(employee); +// assertThat(foundEmployee.getParkingSpot()).isEqualTo(parkingSpot); +// } + +// @Test +// public void givenBookWithAuthors_whenFindById_thenBookWithAuthorsReturned() { +// // given +// Author author1 = new Author(); +// Author author2 = new Author(); +// entityManager.persist(author1); +// entityManager.persist(author2); +// entityManager.flush(); +// Book book = new Book(); +// book.setAuthors(Set.of(author1, author2)); +// entityManager.persist(book); +// entityManager.flush(); + +// // when +// Book foundBook = entityManager.find(Book.class, book.getId()); + +// // then +// assertThat(foundBook).isEqualTo(book); +// assertThat(foundBook.getAuthors()).containsExactly(author1, author2); +// } + +// } + + From 1767ea3cdc4982644331c213abefc751d64bc20f Mon Sep 17 00:00:00 2001 From: Kingsley Amankwah Date: Thu, 27 Apr 2023 05:10:50 +0530 Subject: [PATCH 06/98] Hibernate Associations --- .../associations/BidirectionalUnitTest.java | 103 -------------- .../hibernate/associations/DataJpaTest.java | 5 - .../associations/UnidirectionalUnitTest.java | 128 ------------------ 3 files changed, 236 deletions(-) delete mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/BidirectionalUnitTest.java delete mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/DataJpaTest.java delete mode 100644 persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/UnidirectionalUnitTest.java diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/BidirectionalUnitTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/BidirectionalUnitTest.java deleted file mode 100644 index 5b7e01bff1..0000000000 --- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/BidirectionalUnitTest.java +++ /dev/null @@ -1,103 +0,0 @@ -// package com.baeldung.hibernate.associations; - -// import org.junit.jupiter.api.Test; -// import org.junit.jupiter.api.extension.ExtendWith; -// import org.springframework.beans.factory.annotation.Autowired; -// import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -// import org.springframework.test.context.junit.jupiter.SpringExtension; - -// import java.util.Arrays; -// import java.util.List; -// import com.baeldung.associations.biredirectional.*; - - -// import static org.assertj.core.api.Assertions.assertThat; - -// @ExtendWith(SpringExtension.class) -// @DataJpaTest -// public class BidirectionalHibernateIntegrationTest { - -// @Autowired -// private Course courseRepository; - -// @Autowired -// private Student studentRepository; - -// @Test -// public void whenAddingStudentsToCourse_thenCourseHasStudents() { -// // given -// Student student1 = new Student(); -// student1.setName("John"); -// Student student2 = new Student(); -// student2.setName("Jane"); -// studentRepository.saveAll(Arrays.asList(student1, student2)); - -// Course course = new Course(); -// course.setName("History"); -// courseRepository.save(course); - -// // when -// List students = studentRepository.findAll(); -// course.setStudents(students); -// courseRepository.save(course); - -// // then -// Course result = courseRepository.findById(course.getId()).get(); -// assertThat(result.getStudents()).containsExactlyInAnyOrder(student1, student2); -// } - -// } - -package com.baeldung.hibernate.associations; - - -import com.baeldung.associations.biredirectional.*; - -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.List; - -public class BidirectionalUnitTest { - - @Test - public void givenDepartmentWithEmployees_whenGetEmployees_thenReturnListWithEmployees() { - // given - Department department = new Department(); - Employee employee1 = new Employee(); - Employee employee2 = new Employee(); - department.getEmployees().add(employee1); - department.getEmployees().add(employee2); - - // when - List result = department.getEmployees(); - - // then - assertAll("department employees", - () -> assertEquals(2, result.size()), - () -> assertTrue(result.contains(employee1)), - () -> assertTrue(result.contains(employee2)) - ); - } - - @Test - public void givenCourseWithStudents_whenGetStudents_thenReturnListWithStudents() { - // given - Course course = new Course(); - Student student1 = new Student(); - Student student2 = new Student(); - course.getStudents().add(student1); - course.getStudents().add(student2); - - // when - List result = course.getStudents(); - - // then - assertAll("course students", - () -> assertEquals(2, result.size()), - () -> assertTrue(result.contains(student1)), - () -> assertTrue(result.contains(student2)) - ); - } - -} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/DataJpaTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/DataJpaTest.java deleted file mode 100644 index 184fae20c0..0000000000 --- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/DataJpaTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.hibernate.associations; - -public @interface DataJpaTest { - -} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/UnidirectionalUnitTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/UnidirectionalUnitTest.java deleted file mode 100644 index 790110a6d7..0000000000 --- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/associations/UnidirectionalUnitTest.java +++ /dev/null @@ -1,128 +0,0 @@ - -// // import org.junit.jupiter.api.Assertions; -// // import org.junit.jupiter.api.Test; -// // import org.springframework.beans.factory.annotation.Autowired; -// // import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -// // import org.springframework.boot.test.context.SpringBootTest; -// // import org.springframework.transaction.annotation.Transactional; - -// // import java.util.Collections; -// // import java.util.List; - -// // @DataJpaTest -// // @Transactional -// // public class UnidirectionalUnitTest { - -// // @Autowired -// // private EntityManager entityManager; - -// // @Test -// // public void givenBookWithAuthor_whenSaved_thenFindBookByAuthor() { -// // // given -// // Author author = new Author(); -// // author.setName("John Doe"); - -// // Book book = new Book(); -// // book.setTitle("My Book"); -// // book.setAuthors(Collections.singleton(author)); - -// // entityManager.persist(author); -// // entityManager.persist(book); - -// // entityManager.flush(); -// // entityManager.clear(); - -// // // when -// // List booksByAuthor = entityManager.createQuery( -// // "select b from Book b join b.authors a where a.name = :name", Book.class) -// // .setParameter("name", "John Doe") -// // .getResultList(); - -// // // then -// // Assertions.assertEquals(1, booksByAuthor.size()); -// // Assertions.assertEquals(book, booksByAuthor.get(0)); -// // } -// // } - - -// package com.baeldung.hibernate.associations; - -// import com.baeldung.associations.unidirectional.*; - -// import org.junit.jupiter.api.Test; -// import org.springframework.beans.factory.annotation.Autowired; -// import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -// import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; - -// import java.util.List; -// import java.util.Set; - -// import static org.assertj.core.api.Assertions.assertThat; - -// @DataJpaTest -// public class UnidirectionalUnitTest { - -// @Autowired -// private TestEntityManager entityManager; - -// @Test -// public void givenDepartmentWithEmployees_whenFindById_thenDepartmentWithEmployeesReturned() { -// // given -// Employee employee1 = new Employee(); -// Employee employee2 = new Employee(); -// Department department = new Department(); -// department.setEmployees(List.of(employee1, employee2)); -// entityManager.persist(department); -// entityManager.flush(); - -// // when -// Department foundDepartment = entityManager.find(Department.class, department.getId()); - -// // then -// assertThat(foundDepartment).isEqualTo(department); -// assertThat(foundDepartment.getEmployees()).containsExactly(employee1, employee2); -// } - -// @Test -// public void givenEmployeeWithParkingSpot_whenFindById_thenEmployeeWithParkingSpotReturned() { -// // given -// ParkingSpot parkingSpot = new ParkingSpot(); -// entityManager.persist(parkingSpot); -// entityManager.flush(); -// Employee employee = new Employee(); -// employee.setParkingSpot(parkingSpot); -// entityManager.persist(employee); -// entityManager.flush(); - -// // when -// Employee foundEmployee = entityManager.find(Employee.class, employee.getId()); - -// // then -// assertThat(foundEmployee).isEqualTo(employee); -// assertThat(foundEmployee.getParkingSpot()).isEqualTo(parkingSpot); -// } - -// @Test -// public void givenBookWithAuthors_whenFindById_thenBookWithAuthorsReturned() { -// // given -// Author author1 = new Author(); -// Author author2 = new Author(); -// entityManager.persist(author1); -// entityManager.persist(author2); -// entityManager.flush(); -// Book book = new Book(); -// book.setAuthors(Set.of(author1, author2)); -// entityManager.persist(book); -// entityManager.flush(); - -// // when -// Book foundBook = entityManager.find(Book.class, book.getId()); - -// // then -// assertThat(foundBook).isEqualTo(book); -// assertThat(foundBook.getAuthors()).containsExactly(author1, author2); -// } - -// } - - From d650f7ace7d112794c36f0a4c638bbe023158277 Mon Sep 17 00:00:00 2001 From: Kingsley Amankwah Date: Sun, 30 Apr 2023 15:53:49 +0530 Subject: [PATCH 07/98] getters and setters removed from code --- .../associations/biredirectional/Course.java | 22 +++++++++++++-- .../biredirectional/Employee.java | 25 ++++++++++++++++- .../associations/biredirectional/Student.java | 27 +++++++++++++++++-- .../associations/unidirectional/Author.java | 23 ++++++++++++++++ .../associations/unidirectional/Book.java | 24 +++++++++++++++++ 5 files changed, 116 insertions(+), 5 deletions(-) diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Course.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Course.java index aadc08c090..52d01c027c 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Course.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Course.java @@ -16,9 +16,27 @@ public class Course { inverseJoinColumns = @JoinColumn(name = "student_id")) private List students; - public List getStudents() { + public List getStudents() { return students; } - //getters and setters + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setStudents(List students) { + this.students = students; + } } diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Employee.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Employee.java index 92514b9b8c..1e04379ae2 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Employee.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Employee.java @@ -15,5 +15,28 @@ public class Employee { @JoinColumn(name = "department_id") private Department department; - //getters and setters + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } } diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Student.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Student.java index a494f2475f..81e608f88e 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Student.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/biredirectional/Student.java @@ -14,7 +14,30 @@ public class Student { @ManyToMany(mappedBy = "students") private List courses; - - // getters and setters + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCourses() { + return courses; + } + + public void setCourses(List courses) { + this.courses = courses; + } } diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Author.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Author.java index 6a106071a1..7e023683dc 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Author.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Author.java @@ -14,4 +14,27 @@ public class Author { @ManyToMany(fetch = FetchType.LAZY, mappedBy = "authors") private Set books; + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getBooks() { + return books; + } + + public void setBooks(Set books) { + this.books = books; + } } diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Book.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Book.java index 1467a819a0..25b192fb6b 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Book.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/associations/unidirectional/Book.java @@ -1,4 +1,5 @@ package com.baeldung.associations.unidirectional; + import jakarta.persistence.*; import java.util.Set; @@ -17,4 +18,27 @@ public class Book { inverseJoinColumns = @JoinColumn(name = "author_id")) private Set authors; + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Set getAuthors() { + return authors; + } + + public void setAuthors(Set authors) { + this.authors = authors; + } } From 4e7d1ffd1fbf8932746ee33d81510a2be3f33b4c Mon Sep 17 00:00:00 2001 From: Kingsley Amankwah Date: Sun, 30 Apr 2023 15:58:54 +0530 Subject: [PATCH 08/98] Comments removed --- .../src/main/java/com/baeldung/HibernateUtil.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/HibernateUtil.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/HibernateUtil.java index 8af6b12bae..26ad7e77ba 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/HibernateUtil.java @@ -7,7 +7,6 @@ import org.hibernate.service.ServiceRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -// import com.baeldung.associations.unidirectional.Department; import com.baeldung.manytomany.model.Employee; import com.baeldung.manytomany.model.Project; import com.baeldung.uuids.WebSiteUser; @@ -30,7 +29,6 @@ public class HibernateUtil { configuration.addAnnotatedClass(Element.class); configuration.addAnnotatedClass(Reservation.class); configuration.addAnnotatedClass(Sale.class); - // configuration.addAnnotatedClass(Department.class); configuration.configure("manytomany.cfg.xml"); LOGGER.debug("Hibernate Annotation Configuration loaded"); From e18f13a12a0b4d9762ea8dce3445a8c53110c138 Mon Sep 17 00:00:00 2001 From: uzma Date: Mon, 1 May 2023 22:57:57 +0100 Subject: [PATCH 09/98] [BAEL-6105] code for correct use of flush --- .../java/com/baeldung/flush/AppConfig.java | 57 +++++ .../java/com/baeldung/flush/Customer.java | 36 +++ .../com/baeldung/flush/CustomerAddress.java | 47 ++++ .../boot/flush/FlushIntegrationTest.java | 205 ++++++++++++++++++ 4 files changed, 345 insertions(+) create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java new file mode 100644 index 0000000000..333dc4a956 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java @@ -0,0 +1,57 @@ +package com.baeldung.flush; + +import java.util.Properties; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +@Configuration +public class AppConfig { + + @Bean + public EntityManager entityManager(EntityManagerFactory entityManagerFactory) { + + return entityManagerFactory.createEntityManager(); + } + + @Bean + public DataSource dataSource() { + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .build(); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { + LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(dataSource); + emf.setPackagesToScan("com.baeldung.flush"); + emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + emf.setJpaProperties(getHibernateProperties()); + return emf; + } + + @Bean + public JpaTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory.getObject()); + } + + private Properties getHibernateProperties() { + Properties properties = new Properties(); + properties.setProperty("hibernate.hbm2ddl.auto", "create"); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + return properties; + } +} + + + + diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java new file mode 100644 index 0000000000..786762cbeb --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java @@ -0,0 +1,36 @@ +package com.baeldung.flush; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Customer { + + private String name; + private int age; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java new file mode 100644 index 0000000000..8e4953117a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java @@ -0,0 +1,47 @@ +package com.baeldung.flush; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class CustomerAddress { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String street; + + private String city; + + private long customer_id; + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public Long getId() { + return id; + } + + public long getCustomer_id() { + return customer_id; + } + + public void setCustomer_id(long customer_id) { + this.customer_id = customer_id; + } +} diff --git a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java new file mode 100644 index 0000000000..a134fe95d9 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java @@ -0,0 +1,205 @@ +package com.baeldung.boot.flush; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.FlushModeType; +import javax.persistence.TypedQuery; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.flush.AppConfig; +import com.baeldung.flush.Customer; +import com.baeldung.flush.CustomerAddress; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { AppConfig.class }) + +public class FlushIntegrationTest { + + @Autowired + private EntityManager entityManager; + + @Test + void givenANewCustomer_whenPersistAndNoFlush_thenDatabaseNotSynchronizedWithPersistentContextUsingCommitFlushMode() { + + entityManager.setFlushMode(FlushModeType.COMMIT); + + EntityTransaction transaction = entityManager.getTransaction(); + transaction.begin(); + Customer customer = new Customer(); + customer.setName("Alice"); + customer.setAge(30); + entityManager.persist(customer); + Customer customerInContext = entityManager.find(Customer.class, customer.getId()); + assertThat(customerInContext).isNotNull(); + assertThat(customerInContext.getName()).isEqualTo("Alice"); + + TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); + + List resultList = retrievedCustomer.getResultList(); + + assertThat(resultList).isEmpty(); + transaction.rollback(); + } + + @Test + void givenANewCustomer_whenPersistAndFlush_thenDatabaseSynchronizedWithPersistentContextUsingCommitFlushMode() { + entityManager.setFlushMode(FlushModeType.COMMIT); + + EntityTransaction transaction = entityManager.getTransaction(); + transaction.begin(); + Customer customer = new Customer(); + customer.setName("Alice"); + customer.setAge(30); + entityManager.persist(customer); + entityManager.flush(); + Long generatedCustomerID = customer.getId(); + Customer customerInContext = entityManager.find(Customer.class, generatedCustomerID); + assertThat(customerInContext).isNotNull(); + assertThat(customerInContext.getName()).isEqualTo("Alice"); + + TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); + + List resultList = retrievedCustomer.getResultList(); + + assertThat(resultList).isNotEmpty(); + assertThat(resultList.get(0) + .getName()).isEqualTo("Alice"); + assertThat(resultList.get(0) + .getAge()).isEqualTo(30); + assertThat(resultList.get(0) + .getId()).isEqualTo(generatedCustomerID); + transaction.rollback(); + } + + @Test + void givenANewCustomer_whenPersistAndNoFlush_thenDBIsSyncronizedWithThePersistentContextWithAutoFlushMode() { + entityManager.setFlushMode(FlushModeType.AUTO); + EntityTransaction transaction = entityManager.getTransaction(); + transaction.begin(); + Customer customer = new Customer(); + customer.setName("Alice"); + customer.setAge(30); + entityManager.persist(customer); + Customer customerInContext = entityManager.find(Customer.class, customer.getId()); + assertThat(customerInContext).isNotNull(); + assertThat(customerInContext.getName()).isEqualTo("Alice"); + + TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); + + List resultList = retrievedCustomer.getResultList(); + + assertThat(resultList).isNotEmpty(); + assertThat(resultList.get(0) + .getAge()).isEqualTo(30); + assertThat(resultList.get(0) + .getName()).isEqualTo("Alice"); + assertThat(resultList.get(0) + .getId()).isEqualTo(customer.getId()); + transaction.rollback(); + } + + @Test + public void givenANewCustomer_whenPersistAndFlush_thenCustomerIdGeneratedToBeAddedInAddress() { + entityManager.setFlushMode(FlushModeType.COMMIT); + EntityTransaction transaction = entityManager.getTransaction(); + transaction.begin(); + + Customer customer = new Customer(); + customer.setName("John"); + customer.setAge(25); + entityManager.persist(customer); + entityManager.flush(); + + Customer singleResult = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) + .getSingleResult(); + Long customerId = singleResult.getId(); + + CustomerAddress address = new CustomerAddress(); + address.setCustomer_id(customerId); + entityManager.persist(address); + entityManager.flush(); + + CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) + .setParameter("customerID", customerId) + .getSingleResult(); + + Assertions.assertThat(customerAddress) + .isNotNull(); + + transaction.rollback(); + } + + @Test + public void givenFlushModeAutoAndNewCustomer_whenPersistAndNoFlush_thenCustomerIdGeneratedToBeAddedInAddress() { + entityManager.setFlushMode(FlushModeType.AUTO); + EntityTransaction transaction = entityManager.getTransaction(); + transaction.begin(); + + Customer customer = new Customer(); + customer.setName("John"); + customer.setAge(25); + entityManager.persist(customer); + + Customer singleResult = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) + .getSingleResult(); + Long customerId = singleResult.getId(); + + CustomerAddress address = new CustomerAddress(); + address.setCustomer_id(customerId); + entityManager.persist(address); + + CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) + .setParameter("customerID", customerId) + .getSingleResult(); + + Assertions.assertThat(customerAddress) + .isNotNull(); + + transaction.rollback(); + } + + @Test + public void givenFlushModeCommitAndNewCustomer_whenPersistAndNoFlush_thenCustomerIdGeneratedToBeAddedInAddress() { + entityManager.setFlushMode(FlushModeType.AUTO); + EntityTransaction transaction = entityManager.getTransaction(); + transaction.begin(); + + Customer customer = new Customer(); + customer.setName("John"); + customer.setAge(25); + entityManager.persist(customer); + + Customer singleResult = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) + .getSingleResult(); + Long customerId = singleResult.getId(); + + CustomerAddress address = new CustomerAddress(); + address.setCustomer_id(customerId); + entityManager.persist(address); + + CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) + .setParameter("customerID", customerId) + .getSingleResult(); + + Assertions.assertThat(customerAddress) + .isNotNull(); + + transaction.rollback(); + } + + @AfterEach + public void cleanup() { + entityManager.clear(); + } +} From 3e04f00895077dcce2c8f8908d80c93a913bd9cb Mon Sep 17 00:00:00 2001 From: uzma Date: Mon, 1 May 2023 22:57:57 +0100 Subject: [PATCH 10/98] [BAEL-6105] code for correct use of flush --- .../java/com/baeldung/flush/AppConfig.java | 56 +++++ .../java/com/baeldung/flush/Customer.java | 52 +++++ .../com/baeldung/flush/CustomerAddress.java | 47 +++++ .../boot/flush/FlushIntegrationTest.java | 191 ++++++++++++++++++ 4 files changed, 346 insertions(+) create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java new file mode 100644 index 0000000000..96210fd4b8 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java @@ -0,0 +1,56 @@ +package com.baeldung.flush; + +import java.util.Properties; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +@Configuration +public class AppConfig { + + @Bean + public EntityManager entityManager(EntityManagerFactory entityManagerFactory) { + return entityManagerFactory.createEntityManager(); + } + + @Bean + public DataSource dataSource() { + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .build(); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { + LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(dataSource); + emf.setPackagesToScan("com.baeldung.flush"); + emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + emf.setJpaProperties(getHibernateProperties()); + return emf; + } + + @Bean + public JpaTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory.getObject()); + } + + private Properties getHibernateProperties() { + Properties properties = new Properties(); + properties.setProperty("hibernate.hbm2ddl.auto", "create"); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + return properties; + } +} + + + + diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java new file mode 100644 index 0000000000..a31620c653 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java @@ -0,0 +1,52 @@ +package com.baeldung.flush; + +import java.util.Objects; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Customer { + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Customer customer = (Customer) o; + return age == customer.age && name.equals(customer.name); + } + + @Override + public int hashCode() { + return Objects.hash(name, age); + } + + private String name; + private int age; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java new file mode 100644 index 0000000000..8e4953117a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java @@ -0,0 +1,47 @@ +package com.baeldung.flush; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class CustomerAddress { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String street; + + private String city; + + private long customer_id; + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public Long getId() { + return id; + } + + public long getCustomer_id() { + return customer_id; + } + + public void setCustomer_id(long customer_id) { + this.customer_id = customer_id; + } +} diff --git a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java new file mode 100644 index 0000000000..c678c59f9a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java @@ -0,0 +1,191 @@ +package com.baeldung.boot.flush; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.FlushModeType; +import javax.persistence.TypedQuery; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.flush.AppConfig; +import com.baeldung.flush.Customer; +import com.baeldung.flush.CustomerAddress; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { AppConfig.class }) + +public class FlushIntegrationTest { + + private static final Customer EXPECTED_CUSTOMER = aCustomer(); + + @Autowired + private EntityManager entityManager; + + @Test + void givenANewCustomer_whenPersistAndNoFlush_thenDatabaseNotSynchronizedWithPersistentContextUsingCommitFlushMode() { + + entityManager.setFlushMode(FlushModeType.COMMIT); + + EntityTransaction transaction = getTransaction(); + Customer customer = saveCustomerInPersistentContext("Alice", 30); + Customer customerInContext = entityManager.find(Customer.class, customer.getId()); + assertDataInPersitentContext(customerInContext); + + TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); + + List resultList = retrievedCustomer.getResultList(); + + assertThat(resultList).isEmpty(); + transaction.rollback(); + } + + @Test + void givenANewCustomer_whenPersistAndFlush_thenDatabaseSynchronizedWithPersistentContextUsingCommitFlushMode() { + entityManager.setFlushMode(FlushModeType.COMMIT); + + EntityTransaction transaction = getTransaction(); + Customer customer = saveCustomerInPersistentContext("Alice", 30); + entityManager.flush(); + Long generatedCustomerID = customer.getId(); + + Customer customerInContext = entityManager.find(Customer.class, generatedCustomerID); + assertDataInPersitentContext(customerInContext); + + TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); + + Customer result = retrievedCustomer.getSingleResult(); + assertThat(result).isEqualTo(EXPECTED_CUSTOMER); + transaction.rollback(); + } + + @Test + public void givenANewCustomer_whenPersistAndFlush_thenCustomerIdGeneratedToBeAddedInAddress() { + entityManager.setFlushMode(FlushModeType.COMMIT); + EntityTransaction transaction = getTransaction(); + + saveCustomerInPersistentContext("John", 25); + entityManager.flush(); + + Customer retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) + .getSingleResult(); + Long customerId = retrievedCustomer.getId(); + + CustomerAddress address = new CustomerAddress(); + address.setCustomer_id(customerId); + entityManager.persist(address); + entityManager.flush(); + + CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) + .setParameter("customerID", customerId) + .getSingleResult(); + + assertThat(customerAddress).isNotNull(); + transaction.rollback(); + } + + @Test + void givenANewCustomer_whenPersistAndNoFlush_thenDBIsSynchronizedWithThePersistentContextWithAutoFlushMode() { + entityManager.setFlushMode(FlushModeType.AUTO); + EntityTransaction transaction = getTransaction(); + + Customer customer = saveCustomerInPersistentContext("Alice", 30); + Customer customerInContext = entityManager.find(Customer.class, customer.getId()); + assertDataInPersitentContext(customerInContext); + + TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); + + Customer result = retrievedCustomer.getSingleResult(); + + assertThat(result).isEqualTo(EXPECTED_CUSTOMER); + + transaction.rollback(); + } + + @Test + public void givenFlushModeAutoAndNewCustomer_whenPersistAndNoFlush_thenCustomerIdGeneratedToBeAddedInAddress() { + entityManager.setFlushMode(FlushModeType.AUTO); + EntityTransaction transaction = getTransaction(); + + saveCustomerInPersistentContext("John", 25); + + Customer singleResult = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) + .getSingleResult(); + Long customerId = singleResult.getId(); + + CustomerAddress address = new CustomerAddress(); + address.setCustomer_id(customerId); + entityManager.persist(address); + + CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) + .setParameter("customerID", customerId) + .getSingleResult(); + + assertThat(customerAddress).isNotNull(); + transaction.rollback(); + } + + @Test + public void givenFlushModeAutoAndNewCustomer_whenPersistAndFlush_thenCustomerIdGeneratedToBeAddedInAddress() { + entityManager.setFlushMode(FlushModeType.AUTO); + EntityTransaction transaction = getTransaction(); + + saveCustomerInPersistentContext("John", 25); + + Customer singleResult = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) + .getSingleResult(); + Long customerId = singleResult.getId(); + + CustomerAddress address = new CustomerAddress(); + address.setCustomer_id(customerId); + entityManager.persist(address); + entityManager.flush(); + + CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) + .setParameter("customerID", customerId) + .getSingleResult(); + + assertThat(customerAddress).isNotNull(); + + transaction.rollback(); + } + + private static void assertDataInPersitentContext(Customer customerInContext) { + assertThat(customerInContext).isNotNull(); + assertThat(customerInContext.getName()).isEqualTo("Alice"); + } + + private Customer saveCustomerInPersistentContext(String name, int age) { + Customer customer = new Customer(); + customer.setName(name); + customer.setAge(age); + entityManager.persist(customer); + return customer; + } + + @AfterEach + public void cleanup() { + entityManager.clear(); + } + + private static Customer aCustomer() { + Customer customer = new Customer(); + customer.setName("Alice"); + customer.setAge(30); + return customer; + } + + private EntityTransaction getTransaction() { + EntityTransaction transaction = entityManager.getTransaction(); + transaction.begin(); + return transaction; + } +} \ No newline at end of file From 58d6a02c35e30a6997bbef39659d50443d5e2f21 Mon Sep 17 00:00:00 2001 From: technoddy Date: Sun, 14 May 2023 12:09:07 -0400 Subject: [PATCH 11/98] JPA Counting Row Implementation --- .../countrows/AccountStatsApplication.java | 11 ++ .../baeldung/countrows/entity/Account.java | 96 ++++++++++++ .../baeldung/countrows/entity/Permission.java | 39 +++++ .../repository/AccountRepository.java | 22 +++ .../repository/PermissionRepository.java | 12 ++ .../countrows/service/AccountStatsLogic.java | 123 +++++++++++++++ .../AccountStatsUnitTests.java | 147 ++++++++++++++++++ 7 files changed, 450 insertions(+) create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/AccountStatsApplication.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/PermissionRepository.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java create mode 100644 persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTests.java diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/AccountStatsApplication.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/AccountStatsApplication.java new file mode 100644 index 0000000000..f5a99f0ad8 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/AccountStatsApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.countrows; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AccountStatsApplication { + public static void main(String[] args) { + SpringApplication.run(AccountStatsApplication.class, args); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java new file mode 100644 index 0000000000..11e4cb412e --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java @@ -0,0 +1,96 @@ +package com.baeldung.countrows.entity; + +import javax.persistence.*; + +import java.security.PrivateKey; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.Date; + +@Entity +@Table(name="ACCOUNTS") +public class Account { + @Id + @GeneratedValue(strategy= GenerationType.SEQUENCE, generator = "accounts_seq") + @SequenceGenerator(name = "accounts_seq", sequenceName = "accounts_seq", allocationSize = 1) + @Column(name = "user_id") + private int userId; + private String username; + private String password; + private String email; + private Timestamp createdOn; + private Timestamp lastLogin; + + @OneToOne + @JoinColumn(name = "permissions_id") + private Permission permission; + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Timestamp getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(Timestamp createdOn) { + this.createdOn = createdOn; + } + + public Timestamp getLastLogin() { + return lastLogin; + } + + public void setLastLogin(Timestamp lastLogin) { + this.lastLogin = lastLogin; + } + + public Permission getPermission() { + return permission; + } + + public void setPermission(Permission permission) { + this.permission = permission; + } + + @Override + public String toString() { + return "Account{" + + "userId=" + userId + + ", username='" + username + '\'' + + ", password='" + password + '\'' + + ", email='" + email + '\'' + + ", createdOn=" + createdOn + + ", lastLogin=" + lastLogin + + ", permission=" + permission + + '}'; + } +} \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java new file mode 100644 index 0000000000..17e8ab9c12 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java @@ -0,0 +1,39 @@ +package com.baeldung.countrows.entity; + +import javax.persistence.*; + +@Entity +@Table(name="PERMISSIONS") +public class Permission { + + @Id + @GeneratedValue(strategy= GenerationType.SEQUENCE, generator = "permissions_id_sq") + @SequenceGenerator(name = "permissions_id_sq", sequenceName = "permissions_id_sq", allocationSize = 1) + private int id; + + private String type; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @Override + public String toString() { + return "Permission{" + + "id=" + id + + ", type='" + type + '\'' + + '}'; + } +} diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java new file mode 100644 index 0000000000..875a2e7160 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java @@ -0,0 +1,22 @@ +package com.baeldung.countrows.repository; + +import com.baeldung.countrows.entity.Account; +import com.baeldung.countrows.entity.Permission; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.Date; +import java.util.List; + +@Repository +public interface AccountRepository extends JpaRepository { + + long countByUsername(String username); + + long countByPermission(Permission permission); + + long countByPermissionAndCreatedOnGreaterThan(Permission permission, Timestamp ts); +} diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/PermissionRepository.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/PermissionRepository.java new file mode 100644 index 0000000000..5e598b52ef --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/PermissionRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.countrows.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.countrows.entity.Permission; + +@Repository +public interface PermissionRepository extends JpaRepository { + Permission findByType(String type); +} + diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java new file mode 100644 index 0000000000..f8f8d5905e --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java @@ -0,0 +1,123 @@ +package com.baeldung.countrows.service; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import javax.persistence.criteria.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.baeldung.countrows.entity.Account; +import com.baeldung.countrows.entity.Permission; +import com.baeldung.countrows.repository.AccountRepository; +import com.baeldung.countrows.repository.PermissionRepository; + +@Service +public class AccountStatsLogic { + @Autowired + private AccountRepository accountRepository; + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PermissionRepository permissionRepository; + + public long getAccountCount(){ + return accountRepository.count(); + } + + public long getAccountCountByUsername(String username){ + return accountRepository.countByUsername(username); + } + + public long getAccountCountByPermission(Permission permission){ + return accountRepository.countByPermission(permission); + } + + + public long getAccountCountByPermissionAndCreatedOn(Permission permission, Date date) throws ParseException { + return accountRepository.countByPermissionAndCreatedOnGreaterThan(permission, new Timestamp(date.getTime())); + } + + public long getAccountsUsingCQ() throws ParseException { + // creating criteria builder and query + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = builder.createQuery(Long.class); + Root accountRoot = criteriaQuery.from(Account.class); + + // select query + criteriaQuery + .select(builder.count(accountRoot)); + + // execute and get the result + return entityManager.createQuery(criteriaQuery).getSingleResult(); + } + + public long getAccountsByPermissionUsingCQ(Permission permission) throws ParseException { + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = builder.createQuery(Long.class); + Root accountRoot = criteriaQuery.from(Account.class); + + List predicateList = new ArrayList<>(); // list of predicates that will go in where clause + predicateList.add(builder.equal(accountRoot.get("permission"), permission)); + + criteriaQuery + .select(builder.count(accountRoot)) + .where(builder.and(predicateList.toArray(new Predicate[0]))); + + return entityManager.createQuery(criteriaQuery).getSingleResult(); + } + + public long getAccountsByPermissionAndCreateOnUsingCQ(Permission permission, Date date) throws ParseException { + // creating criteria builder and query + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); // create builder + CriteriaQuery criteriaQuery = builder.createQuery(Long.class);// query instance + Root accountRoot = criteriaQuery.from(Account.class); // root instance + + // list of predicates that will go in where clause + List predicateList = new ArrayList<>(); + predicateList.add(builder.equal(accountRoot.get("permission"), permission)); + predicateList.add(builder.greaterThan(accountRoot.get("createdOn"), new Timestamp(date.getTime()))); + + // select query + criteriaQuery + .select(builder.count(accountRoot)) + .where(builder.and(predicateList.toArray(new Predicate[0]))); + + // execute and get the result + return entityManager.createQuery(criteriaQuery).getSingleResult(); + } + + public long getAccountsUsingJPQL() throws ParseException { + Query query = entityManager.createQuery("SELECT COUNT(*) FROM Account a"); + return (long) query.getSingleResult(); + } + + public long getAccountsByPermissionUsingJPQL(Permission permission) throws ParseException { + Query query = entityManager.createQuery("SELECT COUNT(*) FROM Account a WHERE a.permission = ?1"); + query.setParameter(1, permission); + return (long) query.getSingleResult(); + } + + public long getAccountsByPermissionAndCreatedOnUsingJPQL(Permission permission, Date date) throws ParseException { + Query query = entityManager.createQuery("SELECT COUNT(*) FROM Account a WHERE a.permission = ?1 and a.createdOn > ?2"); + query.setParameter(1, permission); + query.setParameter(2, new Timestamp(date.getTime())); + return (long) query.getSingleResult(); + } + + private static Date getDate() throws ParseException { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + Date parsedDate = dateFormat.parse("2023-04-29"); + + System.out.println("parseDate: "+parsedDate); + return parsedDate; + } +} \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTests.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTests.java new file mode 100644 index 0000000000..2be8e910d9 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTests.java @@ -0,0 +1,147 @@ +package com.baeldung.boot.countrows.accountstatslogic; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.Date; +import java.util.UUID; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.baeldung.countrows.AccountStatsApplication; +import com.baeldung.countrows.entity.Account; +import com.baeldung.countrows.entity.Permission; +import com.baeldung.countrows.repository.AccountRepository; +import com.baeldung.countrows.repository.PermissionRepository; +import com.baeldung.countrows.service.AccountStatsLogic; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; + +@SpringBootTest(classes = AccountStatsApplication.class) +class AccountStatsUnitTests { + + @Autowired + private PermissionRepository permissionRepository; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private AccountStatsLogic accountStatsLogic; + + @AfterEach + public void afterEach(){ + accountRepository.deleteAll(); + permissionRepository.deleteAll(); + } + + @Test + public void givenAccountInTable_whenPerformCount_returnsAppropriateCount(){ + savePermissions(); + Account account = saveAccount(); + assertThat(accountStatsLogic.getAccountCount()).isEqualTo(1); + } + + @Test + public void givenAccountInTable_whenPerformCountByUsernameOrPermission_returnsAppropriateCount() { + savePermissions(); + Account account = saveAccount(); + assertThat(accountStatsLogic.getAccountCountByUsername(account.getUsername())).isEqualTo(1); + assertThat(accountStatsLogic.getAccountCountByPermission(account.getPermission())).isEqualTo(1); + } + + @Test + public void givenAccountInTable_whenPerformCountByPermissionAndCreatedOn_returnsAppropriateCount() throws ParseException { + savePermissions(); + Account account = saveAccount(); + long count = accountStatsLogic.getAccountCountByPermissionAndCreatedOn(account.getPermission(), account.getCreatedOn()); + assertThat(count).isEqualTo(1); + } + + @Test + public void givenAccountInTable_whenPerformCountUsingCQ_returnsAppropriateCount() throws ParseException { + savePermissions(); + Account account = saveAccount(); + long count = accountStatsLogic.getAccountsUsingCQ(); + assertThat(count).isEqualTo(1); + } + + @Test + public void givenAccountInTable_whenPerformCountByPermissionUsingCQ_returnsAppropriateCount() throws ParseException { + savePermissions(); + Account account = saveAccount(); + long count = accountStatsLogic.getAccountsByPermissionUsingCQ(account.getPermission()); + assertThat(count).isEqualTo(1); + } + + @Test + public void givenAccountInTable_whenPerformCountByPermissionAndCreatedOnUsingCQ_returnsAppropriateCount() throws ParseException { + savePermissions(); + Account account = saveAccount(); + long count = accountStatsLogic.getAccountsByPermissionAndCreateOnUsingCQ(account.getPermission(), account.getCreatedOn()); + assertThat(count).isEqualTo(1); + } + + @Test + public void givenAccountInTable_whenPerformCountUsingJPQL_returnsAppropriateCount() throws ParseException { + savePermissions(); + Account account = saveAccount(); + long count = accountStatsLogic.getAccountsUsingJPQL(); + assertThat(count).isEqualTo(1); + } + @Test + public void givenAccountInTable_whenPerformCountByPermissionUsingJPQL_returnsAppropriateCount() throws ParseException { + savePermissions(); + Account account = saveAccount(); + long count = accountStatsLogic.getAccountsByPermissionUsingJPQL(account.getPermission()); + assertThat(count).isEqualTo(1); + } + @Test + public void givenAccountInTable_whenPerformCountByPermissionAndCreatedOnUsingJPQL_returnsAppropriateCount() throws ParseException { + savePermissions(); + Account account = saveAccount(); + long count = accountStatsLogic.getAccountsByPermissionAndCreatedOnUsingJPQL(account.getPermission(), account.getCreatedOn()); + assertThat(count).isEqualTo(1); + } + + private Account saveAccount(){ + return accountRepository.save(getAccount()); + } + + private void savePermissions(){ + Permission editor = new Permission(); + editor.setType("editor"); + permissionRepository.save(editor); + + Permission admin = new Permission(); + admin.setType("admin"); + permissionRepository.save(admin); + } + + private static Date getDate() throws ParseException { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + Date parsedDate = dateFormat.parse("2023-04-29"); + return parsedDate; + } + + private Account getAccount() { + Permission permission = permissionRepository.findByType("admin"); + Account account = new Account(); + String seed = UUID.randomUUID().toString(); + account.setUsername("username_"+seed); + account.setEmail("username_"+seed+"@gmail.com"); + account.setPermission(permission); + account.setPassword("password_q1234"); + account.setCreatedOn(Timestamp.from(Instant.now())); + account.setLastLogin(Timestamp.from(Instant.now())); + return account; + } +} From ebbd80e6c7928fd05416e321c4870a265ab228fc Mon Sep 17 00:00:00 2001 From: technoddy Date: Sun, 14 May 2023 12:38:41 -0400 Subject: [PATCH 12/98] updating class name for tests to abide by policy --- ...{AccountStatsUnitTests.java => AccountStatsUnitTest.java} | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) rename persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/{AccountStatsUnitTests.java => AccountStatsUnitTest.java} (96%) diff --git a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTests.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java similarity index 96% rename from persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTests.java rename to persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java index 2be8e910d9..98269547c3 100644 --- a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTests.java +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java @@ -10,8 +10,6 @@ import java.util.Date; import java.util.UUID; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.baeldung.countrows.AccountStatsApplication; @@ -23,10 +21,9 @@ import com.baeldung.countrows.service.AccountStatsLogic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; @SpringBootTest(classes = AccountStatsApplication.class) -class AccountStatsUnitTests { +class AccountStatsUnitTest { @Autowired private PermissionRepository permissionRepository; From e42d7a6b8a011aa47df23fdfc9b2a99fa82efd91 Mon Sep 17 00:00:00 2001 From: "thibault.faure" Date: Mon, 22 May 2023 10:16:59 +0200 Subject: [PATCH 13/98] BAEL-6508 Code for the Solving Gson Parsing Errors article --- json-modules/gson-2/README.md | 7 +++ json-modules/gson-2/pom.xml | 27 +++++++++ .../baeldung/gson/parsingerrors/Person.java | 15 +++++ .../parsingerror/GsonErrorDemoUnitTest.java | 55 +++++++++++++++++++ json-modules/pom.xml | 1 + 5 files changed, 105 insertions(+) create mode 100644 json-modules/gson-2/README.md create mode 100644 json-modules/gson-2/pom.xml create mode 100644 json-modules/gson-2/src/main/java/com/baeldung/gson/parsingerrors/Person.java create mode 100644 json-modules/gson-2/src/test/java/com/baeldung/gson/parsingerror/GsonErrorDemoUnitTest.java diff --git a/json-modules/gson-2/README.md b/json-modules/gson-2/README.md new file mode 100644 index 0000000000..40d5515567 --- /dev/null +++ b/json-modules/gson-2/README.md @@ -0,0 +1,7 @@ +## GSON + +This module contains articles about Gson + +### Relevant Articles: + + diff --git a/json-modules/gson-2/pom.xml b/json-modules/gson-2/pom.xml new file mode 100644 index 0000000000..aa451bdeed --- /dev/null +++ b/json-modules/gson-2/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + gson-2 + gson-2 + + + com.baeldung + json-modules + 1.0.0-SNAPSHOT + + + + + com.google.code.gson + gson + ${gson.version} + + + + + 2.10.1 + + + \ No newline at end of file diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/parsingerrors/Person.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/parsingerrors/Person.java new file mode 100644 index 0000000000..387d6e1582 --- /dev/null +++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/parsingerrors/Person.java @@ -0,0 +1,15 @@ +package com.baeldung.gson.parsingerrors; + +public class Person { + + public String name; + + public String getName() { + return name; + } + + public Person(String name) { + this.name = name; + } + +} diff --git a/json-modules/gson-2/src/test/java/com/baeldung/gson/parsingerror/GsonErrorDemoUnitTest.java b/json-modules/gson-2/src/test/java/com/baeldung/gson/parsingerror/GsonErrorDemoUnitTest.java new file mode 100644 index 0000000000..d97f695ddf --- /dev/null +++ b/json-modules/gson-2/src/test/java/com/baeldung/gson/parsingerror/GsonErrorDemoUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.gson.parsingerror; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.lang.reflect.Type; +import java.util.Collection; + +import org.junit.jupiter.api.Test; + +import com.baeldung.gson.parsingerrors.Person; +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; +import com.google.gson.reflect.TypeToken; + +class GsonErrorDemoUnitTest { + + @Test + void givenAJsonArray_WhenTellingGsonToExpectAnObject_ThenThrows() { + assertThrows(JsonSyntaxException.class, () -> { + Person person = new Gson().fromJson("[{\"name\":\"John\"},{\"name\":\"James\"}]", Person.class); + }); + } + + @Test + void givenAJsonArray_WhenParsingIntoAnArray_ThenOK() { + Person[] personArray = new Gson().fromJson("[{\"name\":\"John\"},{\"name\":\"James\"}]", Person[].class); + assertThat(personArray).extracting(Person::getName) + .containsExactly("John", "James"); + } + + @Test + void givenAJsonArray_WhenParsingIntoACollection_ThenOK() { + Type collectionType = new TypeToken>() { + }.getType(); + Collection personCollection = new Gson().fromJson("[{\"name\":\"John\"},{\"name\":\"James\"}]", collectionType); + assertThat(personCollection).extracting(Person::getName) + .containsExactly("John", "James"); + } + + @Test + void givenAJsonObject_WhenTellingGsonToExpectAnArray_ThenThrows() { + assertThrows(JsonSyntaxException.class, () -> { + Person[] personArray = new Gson().fromJson("{\"name\":\"John\"}", Person[].class); + }); + } + + @Test + void givenAJsonObject_WhenParsingIntoAnObject_ThenOK() { + Person person = new Gson().fromJson("{\"name\":\"John\"}", Person.class); + assertEquals("John", person.getName()); + } + +} diff --git a/json-modules/pom.xml b/json-modules/pom.xml index 2deb53d533..15a066daa4 100644 --- a/json-modules/pom.xml +++ b/json-modules/pom.xml @@ -18,6 +18,7 @@ json-2 json-path gson + gson-2 From 2ea83407d3327cffc1b09ea568a0ed3456f2f334 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Tue, 23 May 2023 23:50:10 +0200 Subject: [PATCH 14/98] =?UTF-8?q?[scanner-with-spaces]=20how=20to=20take?= =?UTF-8?q?=20input=20as=20String=20with=20spaces=20in=20Java=E2=80=A6=20(?= =?UTF-8?q?#14044)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [scanner-with-spaces] how to take input as String with spaces in Java using Scanner?y * [scanner-with-spaces] fix typo --- .../scanner/InputWithSpacesUnitTest.java | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java new file mode 100644 index 0000000000..8a93c6ce65 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java @@ -0,0 +1,97 @@ +package com.baeldung.scanner; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +public class InputWithSpacesUnitTest { + @Test + void whenValuesContainSpaces_thenNextBreaksTheValue() { + String input = new StringBuilder().append("Michael Jackson\n") + .append("He was the 'King of Pop'.\n") + .toString(); + + Scanner sc = new Scanner(input); + String name = sc.next(); + String description = sc.next(); + assertEquals("Michael", name); + assertEquals("Jackson", description); + } + + @Test + void whenOneValuePerLineUsingNextLine_thenGetExpectedResult() { + String input = new StringBuilder().append("Michael Jackson\n") + .append("He was the 'King of Pop'.\n") + .toString(); + + Scanner sc = new Scanner(input); + String name = sc.nextLine(); + String description = sc.nextLine(); + assertEquals("Michael Jackson", name); + assertEquals("He was the 'King of Pop'.", description); + } + + @Test + void whenOneValuePerLineUsingNewLineAsDelimiter_thenGetExpectedResult() { + String input = new StringBuilder().append("Michael Jackson\n") + .append("He was the 'King of Pop'.\n") + .toString(); + + Scanner sc = new Scanner(input); + sc.useDelimiter("\\n"); + String name = sc.next(); + String description = sc.next(); + assertEquals("Michael Jackson", name); + assertEquals("He was the 'King of Pop'.", description); + } + + @Test + void whenValuesAreSeparatedByCommaUsingSplit_thenGetExpectedResult() { + String input = "Michael Jackson, Whitney Houston, John Lennon\n"; + + Scanner sc = new Scanner(input); + String[] names = sc.nextLine() + .split(", "); + assertArrayEquals(new String[] { "Michael Jackson", "Whitney Houston", "John Lennon" }, names); + } + + @Test + void whenValuesAreSeparatedByCommaSettingDelimiterWithoutNewline_thenGetExpectedResult() { + String input = new StringBuilder().append("Michael Jackson, Whitney Houston, John Lennon\n") + .append("Elvis Presley\n") + .toString(); + + Scanner sc = new Scanner(input); + sc.useDelimiter(", "); + List names = new ArrayList<>(); + while (sc.hasNext()) { + names.add(sc.next()); + } + //assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names); <-- Fail + assertEquals(3, names.size()); + assertEquals("John Lennon\nElvis Presley\n", names.get(2)); + + } + + @Test + void whenValuesAreSeparatedByCommaSettingDelimiter_thenGetExpectedResult() { + String input = new StringBuilder().append("Michael Jackson, Whitney Houston, John Lennon\n") + .append("Elvis Presley\n") + .toString(); + + Scanner sc = new Scanner(input); + sc.useDelimiter(", |\\n"); + List names = new ArrayList<>(); + while (sc.hasNext()) { + names.add(sc.next()); + } + assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names); + } +} \ No newline at end of file From df15627edcf3e143a48f5d2b29aec5018e414df8 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Tue, 23 May 2023 23:56:31 +0200 Subject: [PATCH 15/98] [output-to-file] Write Console Output to Text File in Java (#14082) * [output-to-file] Write Console Output to Text File in Java * [output-to-file] rebase on the master --- core-java-modules/core-java-io-apis-2/pom.xml | 7 +- .../ConsoleOutputToFileUnitTest.java | 94 +++++++++++++++++++ 2 files changed, 97 insertions(+), 4 deletions(-) create mode 100644 core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java diff --git a/core-java-modules/core-java-io-apis-2/pom.xml b/core-java-modules/core-java-io-apis-2/pom.xml index 22c04cdc58..e828b730d2 100644 --- a/core-java-modules/core-java-io-apis-2/pom.xml +++ b/core-java-modules/core-java-io-apis-2/pom.xml @@ -99,9 +99,6 @@ compile - - 5.2.0 - core-java-io-apis-2 @@ -111,5 +108,7 @@ - + + 5.9.3 + \ No newline at end of file diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java new file mode 100644 index 0000000000..c7f643b148 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.outputtofile; + +import static org.junit.jupiter.api.Assertions.assertLinesMatch; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.google.common.collect.Lists; + +class DualPrintStream extends PrintStream { + private final PrintStream second; + + public DualPrintStream(OutputStream main, PrintStream second) { + super(main); + this.second = second; + } + + @Override + public void close() { + super.close(); + second.close(); + } + + @Override + public void flush() { + super.flush(); + second.flush(); + } + + @Override + public void write(byte[] buf, int off, int len) { + super.write(buf, off, len); + second.write(buf, off, len); + } + + @Override + public void write(int b) { + super.write(b); + second.write(b); + } + + @Override + public void write(byte[] b) throws IOException { + super.write(b); + second.write(b); + } +} + +public class ConsoleOutputToFileUnitTest { + + // @formatter:off + private final static List OUTPUT_LINES = Lists.newArrayList( + "I came", + "I saw", + "I conquered"); + // @formatter:on + + @Test + void whenReplacingSystemOutPrintStreamWithFileOutputStream_thenOutputsGoToFile(@TempDir Path tempDir) throws IOException { + PrintStream originalOut = System.out; + Path outputFilePath = tempDir.resolve("file-output.txt"); + PrintStream out = new PrintStream(Files.newOutputStream(outputFilePath), true); + System.setOut(out); + + OUTPUT_LINES.forEach(line -> System.out.println(line)); + assertTrue(outputFilePath.toFile() + .exists(), "The file exists"); + assertLinesMatch(OUTPUT_LINES, Files.readAllLines(outputFilePath)); + System.setOut(originalOut); + } + + @Test + void whenUsingDualPrintStream_thenOutputsGoToConsoleAndFile(@TempDir Path tempDir) throws IOException { + PrintStream originalOut = System.out; + Path outputFilePath = tempDir.resolve("dual-output.txt"); + DualPrintStream dualOut = new DualPrintStream(Files.newOutputStream(outputFilePath), System.out); + System.setOut(dualOut); + + OUTPUT_LINES.forEach(line -> System.out.println(line)); + assertTrue(outputFilePath.toFile() + .exists(), "The file exists"); + assertLinesMatch(OUTPUT_LINES, Files.readAllLines(outputFilePath)); + System.setOut(originalOut); + + } +} \ No newline at end of file From 05a672410df8d65d9f96a0a62c08bf43a3372047 Mon Sep 17 00:00:00 2001 From: Bahaa El-Din Helmy Date: Wed, 24 May 2023 03:05:20 +0300 Subject: [PATCH 16/98] Convert Hashmap to JSON object in Java (#14110) This commit is for Convert Hashmap to JSON object in Java --- .../baeldung/maptojson/MapToJsonUnitTest.java | 75 ++++++++----------- 1 file changed, 33 insertions(+), 42 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java index 7a9f046a94..d9b13f4f4a 100644 --- a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java +++ b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java @@ -17,49 +17,40 @@ import java.util.HashMap; import java.util.Map; public class MapToJsonUnitTest { - final TypeAdapter strictAdapter = new Gson().getAdapter(JsonElement.class); +String originalJsonData = "{\"CS\":\"Post1\",\"Linux\":\"Post1\",\"Kotlin\":\"Post1\"}"; - public boolean isValid(String json) { - try { - strictAdapter.fromJson(json); - } catch (JsonSyntaxException | IOException e) { - return false; - } - return true; - } +@Test +public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException { + Map data = new HashMap(); + data.put("CS", "Post1"); + data.put("Linux", "Post1"); + data.put("Kotlin", "Post1"); + ObjectMapper objectMapper = new ObjectMapper(); + String jacksonData = objectMapper.writeValueAsString(data); + Assertions.assertEquals(jacksonData,originalJsonData); +} - @Test - public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException { - Map data = new HashMap(); - data.put("CS", "Post1"); - data.put("Linux", "Post1"); - data.put("Kotlin", "Post1"); - ObjectMapper objectMapper = new ObjectMapper(); - String jacksonData = objectMapper.writeValueAsString(data); - Assertions.assertTrue(isValid(jacksonData)); - } +@Test +public void given_HashMapData_whenUsingGson_thenConvertToJson() { + Map data = new HashMap<>(); + data.put("CS", "Post1"); + data.put("Linux", "Post1"); + data.put("Kotlin", "Post1"); + Gson gson = new Gson(); + Type typeObject = new TypeToken() { + }.getType(); + String gsonData = gson.toJson(data, typeObject); + Assertions.assertEquals(gsonData,originalJsonData); +} - @Test - public void given_HashMapData_whenUsingGson_thenConvertToJson() { - Map data = new HashMap<>(); - data.put("CS", "Post1"); - data.put("Linux", "Post1"); - data.put("Kotlin", "Post1"); - Gson gson = new Gson(); - Type typeObject = new TypeToken() { - }.getType(); - String gsonData = gson.toJson(data, typeObject); - Assertions.assertTrue(isValid(gsonData)); - } - - @Test - public void given_HashMapData_whenOrgJson_thenConvertToJsonUsing() { - Map data = new HashMap<>(); - data.put("CS", "Post1"); - data.put("Linux", "Post1"); - data.put("Kotlin", "Post1"); - JSONObject jsonObject = new JSONObject(data); - String orgJsonData = jsonObject.toString(); - Assertions.assertTrue(isValid(orgJsonData)); - } +@Test +public void given_HashMapData_whenOrgJson_thenConvertToJsonUsing() { + Map data = new HashMap<>(); + data.put("CS", "Post1"); + data.put("Linux", "Post1"); + data.put("Kotlin", "Post1"); + JSONObject jsonObject = new JSONObject(data); + String orgJsonData = jsonObject.toString(); + Assertions.assertEquals(orgJsonData,originalJsonData); +} } \ No newline at end of file From 0bf96a83d3d765c8109c3f473e119c67e9a85653 Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Wed, 24 May 2023 03:10:50 +0000 Subject: [PATCH 17/98] Generating Javadoc with Gradle (#14091) * Generating Javadoc with Gradle * Generating Javadoc with Gradle * Generating Javadoc with Gradle --- .../gradle-7/gradle-javadoc/.gitignore | 42 +++ .../gradle-7/gradle-javadoc/build.gradle | 25 ++ .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 60756 bytes .../gradle/wrapper/gradle-wrapper.properties | 5 + .../gradle-7/gradle-javadoc/gradlew | 240 ++++++++++++++++++ .../gradle-7/gradle-javadoc/gradlew.bat | 91 +++++++ .../gradle-7/gradle-javadoc/settings.gradle | 2 + .../main/java/com/baeldung/addition/Sum.java | 17 ++ .../com/baeldung/subtraction/Difference.java | 17 ++ 9 files changed, 439 insertions(+) create mode 100644 gradle-modules/gradle-7/gradle-javadoc/.gitignore create mode 100644 gradle-modules/gradle-7/gradle-javadoc/build.gradle create mode 100644 gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.properties create mode 100755 gradle-modules/gradle-7/gradle-javadoc/gradlew create mode 100644 gradle-modules/gradle-7/gradle-javadoc/gradlew.bat create mode 100644 gradle-modules/gradle-7/gradle-javadoc/settings.gradle create mode 100644 gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/addition/Sum.java create mode 100644 gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/subtraction/Difference.java diff --git a/gradle-modules/gradle-7/gradle-javadoc/.gitignore b/gradle-modules/gradle-7/gradle-javadoc/.gitignore new file mode 100644 index 0000000000..b63da4551b --- /dev/null +++ b/gradle-modules/gradle-7/gradle-javadoc/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/gradle-modules/gradle-7/gradle-javadoc/build.gradle b/gradle-modules/gradle-7/gradle-javadoc/build.gradle new file mode 100644 index 0000000000..5d8303d64c --- /dev/null +++ b/gradle-modules/gradle-7/gradle-javadoc/build.gradle @@ -0,0 +1,25 @@ +plugins { + id 'java' +} + +group 'org.example' +version '1.0-SNAPSHOT' + +javadoc { + destinationDir = file("${buildDir}/docs/javadoc") + include 'com/baeldung/addition/**' + exclude 'com/baeldung/subtraction/**' +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.jar b/gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..249e5832f090a2944b7473328c07c9755baa3196 GIT binary patch literal 60756 zcmb5WV{~QRw(p$^Dz@00IL3?^hro$gg*4VI_WAaTyVM5Foj~O|-84 z$;06hMwt*rV;^8iB z1~&0XWpYJmG?Ts^K9PC62H*`G}xom%S%yq|xvG~FIfP=9*f zZoDRJBm*Y0aId=qJ?7dyb)6)JGWGwe)MHeNSzhi)Ko6J<-m@v=a%NsP537lHe0R* z`If4$aaBA#S=w!2z&m>{lpTy^Lm^mg*3?M&7HFv}7K6x*cukLIGX;bQG|QWdn{%_6 zHnwBKr84#B7Z+AnBXa16a?or^R?+>$4`}{*a_>IhbjvyTtWkHw)|ay)ahWUd-qq$~ zMbh6roVsj;_qnC-R{G+Cy6bApVOinSU-;(DxUEl!i2)1EeQ9`hrfqj(nKI7?Z>Xur zoJz-a`PxkYit1HEbv|jy%~DO^13J-ut986EEG=66S}D3!L}Efp;Bez~7tNq{QsUMm zh9~(HYg1pA*=37C0}n4g&bFbQ+?-h-W}onYeE{q;cI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u%GcJ!4?lObt0z_$mZ4rbQ0o=^curCs3bJK6sq z9fu-aW-l#>z~ca(B;4yv;2RZ?tGYAU)^)Kz{L|4oPj zdOf_?de|#yS)p2v8-N||+XL=O*%3+y)oI(HbM)Ds?q8~HPzIP(vs*G`iddbWq}! z(2!VjP&{Z1w+%eUq^ '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# 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/gradle-modules/gradle-7/gradle-javadoc/gradlew.bat b/gradle-modules/gradle-7/gradle-javadoc/gradlew.bat new file mode 100644 index 0000000000..53a6b238d4 --- /dev/null +++ b/gradle-modules/gradle-7/gradle-javadoc/gradlew.bat @@ -0,0 +1,91 @@ +@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=. +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/gradle-modules/gradle-7/gradle-javadoc/settings.gradle b/gradle-modules/gradle-7/gradle-javadoc/settings.gradle new file mode 100644 index 0000000000..3a648ffa2f --- /dev/null +++ b/gradle-modules/gradle-7/gradle-javadoc/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'gradle-javadoc' + diff --git a/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/addition/Sum.java b/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/addition/Sum.java new file mode 100644 index 0000000000..612196fb9d --- /dev/null +++ b/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/addition/Sum.java @@ -0,0 +1,17 @@ +package com.baeldung.addition; + +/** + * This is a sample class that demonstrates Javadoc comments. + */ +public class Sum { + /** + * This method returns the sum of two integers. + * + * @param a the first integer + * @param b the second integer + * @return the sum of a and b + */ + public int add(int a, int b) { + return a + b; + } +} \ No newline at end of file diff --git a/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/subtraction/Difference.java b/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/subtraction/Difference.java new file mode 100644 index 0000000000..083cf2d1b8 --- /dev/null +++ b/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/subtraction/Difference.java @@ -0,0 +1,17 @@ +package com.baeldung.subtraction; + +/** + * This is a sample class that demonstrates Javadoc comments. + */ +public class Difference { + /** + * This method returns the difference between the two integers. + * + * @param a the first integer + * @param b the second integer + * @return the difference between a and b + */ + public int subtract(int a, int b) { + return a - b; + } +} \ No newline at end of file From bb28902afdfe2c30d6f3c41660393911546f7b3c Mon Sep 17 00:00:00 2001 From: Ralf Ueberfuhr <40685729+ueberfuhr@users.noreply.github.com> Date: Wed, 24 May 2023 06:50:36 +0200 Subject: [PATCH 18/98] BAEL-6179: Fix readme (#14088) * BAEL-6179: Add Actuator sample without Spring Boot * BAEL-6179: Simplify custom health indicator * BAEL-6179: Fix description in README.md --- parent-spring-6/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/parent-spring-6/README.md b/parent-spring-6/README.md index 791a6ca197..d43bba4513 100644 --- a/parent-spring-6/README.md +++ b/parent-spring-6/README.md @@ -1,3 +1,3 @@ -## Parent Spring 5 +## Parent Spring 6 -This is a parent module for all projects using Spring 5 +This is a parent module for all projects using Spring 6 From 74686f60a0b918c5ebaf518ebb6719507cc4abb1 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 24 May 2023 19:37:51 +0530 Subject: [PATCH 19/98] JAVA-21189: changes made for formatting modules starting from S (#14106) --- saas-modules/jira-rest-integration/pom.xml | 2 +- saas-modules/sentry-servlet/pom.xml | 64 ++++---- spring-boot-modules/pom.xml | 2 +- .../spring-boot-3-native/pom.xml | 10 +- .../spring-boot-3-observation/pom.xml | 4 +- .../spring-boot-3-test-pitfalls/pom.xml | 4 +- spring-boot-modules/spring-boot-ci-cd/pom.xml | 3 +- spring-boot-modules/spring-boot-cli/pom.xml | 4 +- .../spring-boot-environment/pom.xml | 2 +- .../spring-boot-graphql/pom.xml | 4 +- .../spring-boot-keycloak-2/pom.xml | 8 +- .../spring-boot-keycloak/pom.xml | 8 +- .../spring-boot-logging-logback/pom.xml | 4 +- .../spring-boot-properties/pom.xml | 4 +- spring-boot-modules/spring-boot-redis/pom.xml | 10 +- .../spring-boot-swagger-keycloak/pom.xml | 126 +++++++-------- .../spring-boot-testing-2/pom.xml | 4 +- spring-boot-modules/spring-caching/pom.xml | 2 +- spring-boot-rest/pom.xml | 66 ++++---- .../spring-cloud-azure/pom.xml | 4 +- .../spring-cloud-bootstrap/gateway/pom.xml | 10 +- .../spring-cloud-open-telemetry/pom.xml | 4 +- .../spring-cloud-open-telemetry1/pom.xml | 4 +- .../spring-cloud-open-telemetry2/pom.xml | 2 +- .../spring-cloud-stream-kinesis/pom.xml | 94 +++++------ spring-core-2/pom.xml | 4 +- spring-credhub/pom.xml | 4 +- .../spring-5-data-reactive/pom.xml | 4 +- .../spring-reactive-exceptions/pom.xml | 6 +- spring-roo/pom.xml | 2 +- .../spring-security-azuread/pom.xml | 147 +++++++++--------- .../spring-security-saml2/pom.xml | 12 +- spring-web-modules/spring-mvc-webflow/pom.xml | 3 +- .../spring-thymeleaf-attributes/pom.xml | 44 +++--- 34 files changed, 338 insertions(+), 337 deletions(-) diff --git a/saas-modules/jira-rest-integration/pom.xml b/saas-modules/jira-rest-integration/pom.xml index ebf36646e4..f98320bafa 100644 --- a/saas-modules/jira-rest-integration/pom.xml +++ b/saas-modules/jira-rest-integration/pom.xml @@ -45,7 +45,7 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed diff --git a/saas-modules/sentry-servlet/pom.xml b/saas-modules/sentry-servlet/pom.xml index 2e4f95b5fb..11dd2ad0ff 100644 --- a/saas-modules/sentry-servlet/pom.xml +++ b/saas-modules/sentry-servlet/pom.xml @@ -11,40 +11,40 @@ sentry-servlet sentry-servlet war - - - 6.11.0 - 1.10.4 - 3.3.2 - - - - - io.sentry - sentry-servlet - ${sentry.version} - - - javax.servlet - javax.servlet-api - provided - + + 6.11.0 + 1.10.4 + 3.3.2 + + + + + io.sentry + sentry-servlet + ${sentry.version} + + + + javax.servlet + javax.servlet-api + provided + - + - - - org.codehaus.cargo - cargo-maven3-plugin - ${cargo.version} - - - tomcat9x - embedded - - - - + + + org.codehaus.cargo + cargo-maven3-plugin + ${cargo.version} + + + tomcat9x + embedded + + + + \ No newline at end of file diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 2fe146e065..d46612393d 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -80,7 +80,7 @@ spring-boot-data-2 spring-boot-validation spring-boot-data-3 - spring-caching + spring-caching spring-caching-2 spring-boot-redis spring-boot-cassandre diff --git a/spring-boot-modules/spring-boot-3-native/pom.xml b/spring-boot-modules/spring-boot-3-native/pom.xml index 1e93c3d8ed..2bbc11afd2 100644 --- a/spring-boot-modules/spring-boot-3-native/pom.xml +++ b/spring-boot-modules/spring-boot-3-native/pom.xml @@ -66,12 +66,12 @@ --> - - - + + + - - + + diff --git a/spring-boot-modules/spring-boot-3-observation/pom.xml b/spring-boot-modules/spring-boot-3-observation/pom.xml index ddd81e3ca4..f69ce699bc 100644 --- a/spring-boot-modules/spring-boot-3-observation/pom.xml +++ b/spring-boot-modules/spring-boot-3-observation/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-observation 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml b/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml index 90e4ba022a..21a7e5f702 100644 --- a/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/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-test-pitfalls 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-ci-cd/pom.xml b/spring-boot-modules/spring-boot-ci-cd/pom.xml index 39b90a0777..8c12c98236 100644 --- a/spring-boot-modules/spring-boot-ci-cd/pom.xml +++ b/spring-boot-modules/spring-boot-ci-cd/pom.xml @@ -70,7 +70,8 @@ spring-boot-ci-cd java $JAVA_OPTS -jar -Dserver.port=$PORT - target/${project.build.finalName}.jar + target/${project.build.finalName}.jar + diff --git a/spring-boot-modules/spring-boot-cli/pom.xml b/spring-boot-modules/spring-boot-cli/pom.xml index d2c50590ab..76b14b2103 100644 --- a/spring-boot-modules/spring-boot-cli/pom.xml +++ b/spring-boot-modules/spring-boot-cli/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-cli spring-boot-cli diff --git a/spring-boot-modules/spring-boot-environment/pom.xml b/spring-boot-modules/spring-boot-environment/pom.xml index 013156fa7f..4bdb35358c 100644 --- a/spring-boot-modules/spring-boot-environment/pom.xml +++ b/spring-boot-modules/spring-boot-environment/pom.xml @@ -149,7 +149,7 @@ - + 2.2 3.1.7 diff --git a/spring-boot-modules/spring-boot-graphql/pom.xml b/spring-boot-modules/spring-boot-graphql/pom.xml index bb475679ad..628babbd3f 100644 --- a/spring-boot-modules/spring-boot-graphql/pom.xml +++ b/spring-boot-modules/spring-boot-graphql/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-graphql spring-boot-graphql diff --git a/spring-boot-modules/spring-boot-keycloak-2/pom.xml b/spring-boot-modules/spring-boot-keycloak-2/pom.xml index 572986e8c4..c5bb97fb21 100644 --- a/spring-boot-modules/spring-boot-keycloak-2/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak-2/pom.xml @@ -16,9 +16,9 @@ 0.0.1-SNAPSHOT ../../parent-boot-2 - + - 21.0.1 + 21.0.1 @@ -49,8 +49,8 @@ org.keycloak keycloak-admin-client ${keycloak.version} - - + + org.keycloak keycloak-core diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index 688b45d6d0..a4d6e18fd5 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -101,11 +101,11 @@ - - + + com.baeldung.keycloak.SpringBoot - 4.0.0 - 2.5.0 + 4.0.0 + 2.5.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-logging-logback/pom.xml b/spring-boot-modules/spring-boot-logging-logback/pom.xml index deb591c9f0..68ef231ed9 100644 --- a/spring-boot-modules/spring-boot-logging-logback/pom.xml +++ b/spring-boot-modules/spring-boot-logging-logback/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-logging-logback spring-boot-logging-logback diff --git a/spring-boot-modules/spring-boot-properties/pom.xml b/spring-boot-modules/spring-boot-properties/pom.xml index 4ad5aeed1d..bf5f514725 100644 --- a/spring-boot-modules/spring-boot-properties/pom.xml +++ b/spring-boot-modules/spring-boot-properties/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-properties 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-redis/pom.xml b/spring-boot-modules/spring-boot-redis/pom.xml index 5b85ad00ca..4467e38dbe 100644 --- a/spring-boot-modules/spring-boot-redis/pom.xml +++ b/spring-boot-modules/spring-boot-redis/pom.xml @@ -1,20 +1,20 @@ + 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-redis 0.0.1-SNAPSHOT spring-boot-redis Demo project for Spring Boot with Spring Data Redis - + com.baeldung parent-boot-3 0.0.1-SNAPSHOT ../../parent-boot-3 - + org.springframework.boot @@ -71,8 +71,8 @@ - + 15 - + diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml index e7950fe393..3b1a4ca988 100644 --- a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml @@ -1,72 +1,72 @@ - 4.0.0 - spring-boot-swagger-keycloak - 0.1.0-SNAPSHOT - spring-boot-swagger-keycloak - jar - Module For Spring Boot Swagger UI with Keycloak + 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-swagger-keycloak + 0.1.0-SNAPSHOT + spring-boot-swagger-keycloak + jar + Module For Spring Boot Swagger UI with Keycloak - - com.baeldung - parent-boot-3 - 0.0.1-SNAPSHOT - ../../parent-boot-3 - + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + - - - - org.apache.logging.log4j - log4j-bom - ${log4j2.version} - import - pom - - - + + + + org.apache.logging.log4j + log4j-bom + ${log4j2.version} + import + pom + + + - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-oauth2-resource-server - - - - org.springframework.boot - spring-boot-starter-security - - - org.springdoc - springdoc-openapi-starter-webmvc-ui - ${springdoc.version} - - - javax.annotation - javax.annotation-api - ${javax.version} - - + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + + org.springframework.boot + spring-boot-starter-security + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${springdoc.version} + + + javax.annotation + javax.annotation-api + ${javax.version} + + - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + - - 2.1.0 - 2.17.1 - 1.3.2 - + + 2.1.0 + 2.17.1 + 1.3.2 + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing-2/pom.xml b/spring-boot-modules/spring-boot-testing-2/pom.xml index cf16407e76..be8beaf700 100644 --- a/spring-boot-modules/spring-boot-testing-2/pom.xml +++ b/spring-boot-modules/spring-boot-testing-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 spring-boot-testing-2 spring-boot-testing-2 diff --git a/spring-boot-modules/spring-caching/pom.xml b/spring-boot-modules/spring-caching/pom.xml index fa36b3af8b..7f68dbf3ec 100644 --- a/spring-boot-modules/spring-caching/pom.xml +++ b/spring-boot-modules/spring-caching/pom.xml @@ -8,7 +8,7 @@ spring-caching war - + com.baeldung.spring-boot-modules spring-boot-modules 1.0.0-SNAPSHOT diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index 46563b725f..74d46f0651 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -22,10 +22,10 @@ spring-boot-starter-web - tomcat-embed-el - org.apache.tomcat.embed + tomcat-embed-el + org.apache.tomcat.embed - + com.fasterxml.jackson.dataformat @@ -50,12 +50,12 @@ spring-boot-starter-data-jpa - jakarta.xml.bind-api - jakarta.xml.bind + jakarta.xml.bind-api + jakarta.xml.bind - txw2 - org.glassfish.jaxb + txw2 + org.glassfish.jaxb @@ -64,8 +64,8 @@ spring-boot-starter-data-rest - spring-boot-starter-web - org.springframework.boot + spring-boot-starter-web + org.springframework.boot @@ -75,8 +75,8 @@ spring-boot-starter-hateoas - spring-boot-starter-web - org.springframework.boot + spring-boot-starter-web + org.springframework.boot @@ -87,20 +87,20 @@ ${guava.version} - listenablefuture - com.google.guava + listenablefuture + com.google.guava - jsr305 - com.google.code.findbugs + jsr305 + com.google.code.findbugs - error_prone_annotations - com.google.errorprone + error_prone_annotations + com.google.errorprone - j2objc-annotations - com.google.j2objc + j2objc-annotations + com.google.j2objc @@ -110,8 +110,8 @@ test - jakarta.xml.bind-api - jakarta.xml.bind + jakarta.xml.bind-api + jakarta.xml.bind @@ -121,8 +121,8 @@ test - commons-logging - commons-logging + commons-logging + commons-logging @@ -132,16 +132,16 @@ ${modelmapper.version} - io.rest-assured - rest-assured - 3.3.0 - provided - - - hamcrest-library - org.hamcrest - - + io.rest-assured + rest-assured + 3.3.0 + provided + + + hamcrest-library + org.hamcrest + + org.glassfish.jaxb diff --git a/spring-cloud-modules/spring-cloud-azure/pom.xml b/spring-cloud-modules/spring-cloud-azure/pom.xml index 86706c794f..5153eecc9f 100644 --- a/spring-cloud-modules/spring-cloud-azure/pom.xml +++ b/spring-cloud-modules/spring-cloud-azure/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 com.baeldung.spring.cloud spring-cloud-azure diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml index 1a6296ac4f..e1041516c4 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml @@ -76,14 +76,14 @@ - - - + + + - - + + diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/pom.xml b/spring-cloud-modules/spring-cloud-open-telemetry/pom.xml index 69b3a1a478..a45f824313 100644 --- a/spring-cloud-modules/spring-cloud-open-telemetry/pom.xml +++ b/spring-cloud-modules/spring-cloud-open-telemetry/pom.xml @@ -1,6 +1,6 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud spring-cloud-open-telemetry diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml index 3003113085..8be1dcf9f9 100644 --- a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/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-cloud-open-telemetry1 com.baeldung.spring.cloud diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml index 4f56cc717e..ecf275fac6 100644 --- a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-cloud-open-telemetry2 com.baeldung.spring.cloud diff --git a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml index 9d0d91b2c0..850f805f1c 100644 --- a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml +++ b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml @@ -1,54 +1,54 @@ - 4.0.0 - spring-cloud-stream-kinesis - spring-cloud-stream-kinesis + 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-cloud-stream-kinesis + spring-cloud-stream-kinesis - - com.baeldung - spring-cloud-stream - 1.0.0-SNAPSHOT - + + com.baeldung + spring-cloud-stream + 1.0.0-SNAPSHOT + - - - org.springframework.boot - spring-boot-starter-web - - - com.amazonaws - aws-java-sdk-kinesis - ${aws-sdk.version} - - - org.springframework.cloud - spring-cloud-stream-test-support - ${spring-cloud-stream-test.version} - test - - - com.amazonaws - amazon-kinesis-producer - 0.13.1 - - - com.amazonaws - amazon-kinesis-client - 1.14.9 - - - org.springframework.cloud - spring-cloud-stream-binder-kinesis - ${spring-cloud-stream-kinesis-binder.version} - - + + + org.springframework.boot + spring-boot-starter-web + + + com.amazonaws + aws-java-sdk-kinesis + ${aws-sdk.version} + + + org.springframework.cloud + spring-cloud-stream-test-support + ${spring-cloud-stream-test.version} + test + + + com.amazonaws + amazon-kinesis-producer + 0.13.1 + + + com.amazonaws + amazon-kinesis-client + 1.14.9 + + + org.springframework.cloud + spring-cloud-stream-binder-kinesis + ${spring-cloud-stream-kinesis-binder.version} + + - - 1.12.380 - 2.2.0 - 4.0.0 - + + 1.12.380 + 2.2.0 + 4.0.0 + \ No newline at end of file diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index bab47cb70c..f6142cffb0 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -16,7 +16,7 @@ - + org.springframework.boot spring-boot-starter @@ -134,7 +134,7 @@ org.projectlombok lombok - + diff --git a/spring-credhub/pom.xml b/spring-credhub/pom.xml index 57fbe5c9d6..4604833d0b 100644 --- a/spring-credhub/pom.xml +++ b/spring-credhub/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 com.baeldung.spring-credhub diff --git a/spring-reactive-modules/spring-5-data-reactive/pom.xml b/spring-reactive-modules/spring-5-data-reactive/pom.xml index 3c7b4eefad..e4d3aeeddd 100644 --- a/spring-reactive-modules/spring-5-data-reactive/pom.xml +++ b/spring-reactive-modules/spring-5-data-reactive/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-5-data-reactive spring-5-data-reactive diff --git a/spring-reactive-modules/spring-reactive-exceptions/pom.xml b/spring-reactive-modules/spring-reactive-exceptions/pom.xml index 940ae90de3..0dca81c529 100644 --- a/spring-reactive-modules/spring-reactive-exceptions/pom.xml +++ b/spring-reactive-modules/spring-reactive-exceptions/pom.xml @@ -8,11 +8,11 @@ spring-reactive-exceptions A module to hold demo examples related to exception in Spring Reactive - + com.baeldung - parent-boot-3 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-3 + ../../parent-boot-3 diff --git a/spring-roo/pom.xml b/spring-roo/pom.xml index fcfafcdaac..6b398ac752 100644 --- a/spring-roo/pom.xml +++ b/spring-roo/pom.xml @@ -18,7 +18,7 @@ io.spring.platform platform-bom Athens-RELEASE - + diff --git a/spring-security-modules/spring-security-azuread/pom.xml b/spring-security-modules/spring-security-azuread/pom.xml index c4dbbd14b9..c1fe08b47a 100644 --- a/spring-security-modules/spring-security-azuread/pom.xml +++ b/spring-security-modules/spring-security-azuread/pom.xml @@ -1,76 +1,75 @@ - - - 4.0.0 - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - spring-security-azuread - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-oauth2-client - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - + + + 4.0.0 + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + spring-security-azuread + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-saml2/pom.xml b/spring-security-modules/spring-security-saml2/pom.xml index 43a6099022..0e92339bc0 100644 --- a/spring-security-modules/spring-security-saml2/pom.xml +++ b/spring-security-modules/spring-security-saml2/pom.xml @@ -1,12 +1,12 @@ - + 4.0.0 spring-security-saml2 1.0-SNAPSHOT spring-security-saml2 - + shib-build-releases @@ -14,14 +14,14 @@ https://build.shibboleth.net/nexus/content/repositories/releases/ - + com.baeldung parent-boot-3 0.0.1-SNAPSHOT ../../parent-boot-3 - + org.springframework.boot @@ -70,7 +70,7 @@ spring-security-saml2-service-provider - + @@ -79,7 +79,7 @@ - + 17 4.1.1 diff --git a/spring-web-modules/spring-mvc-webflow/pom.xml b/spring-web-modules/spring-mvc-webflow/pom.xml index 49037e7186..69985a7b9d 100644 --- a/spring-web-modules/spring-mvc-webflow/pom.xml +++ b/spring-web-modules/spring-mvc-webflow/pom.xml @@ -83,7 +83,8 @@ -Xmx2048m -XX:PermSize=256m -Dtomee.serialization.class.blacklist=- - -Dtomee.serialization.class.whitelist=* + -Dtomee.serialization.class.whitelist=* + true diff --git a/spring-web-modules/spring-thymeleaf-attributes/pom.xml b/spring-web-modules/spring-thymeleaf-attributes/pom.xml index 41ea8b4dd1..44806cc29f 100644 --- a/spring-web-modules/spring-thymeleaf-attributes/pom.xml +++ b/spring-web-modules/spring-thymeleaf-attributes/pom.xml @@ -1,29 +1,29 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd"> - 4.0.0 + 4.0.0 - com.baeldung.spring-thymeleaf-attributes - spring-thymeleaf-attributes-modules - 0.0.1-SNAPSHOT - pom - - - com.baeldung - parent-boot-3 + com.baeldung.spring-thymeleaf-attributes + spring-thymeleaf-attributes-modules 0.0.1-SNAPSHOT - ../../parent-boot-3 - + pom - - - org.springframework.boot - spring-boot-devtools - - + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + - - accessing-session-attributes - + + + org.springframework.boot + spring-boot-devtools + + + + + accessing-session-attributes + \ No newline at end of file From 1cdf7489ee8f84d9c37d5a174cf7d11e165c85b6 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 24 May 2023 19:38:09 +0530 Subject: [PATCH 20/98] JAVA-21189: changes made for formatting modules starting from TVWX (#14107) --- pom.xml | 4 ++-- testing-modules/gatling-java/pom.xml | 4 ++-- testing-modules/junit-5-advanced/pom.xml | 4 ++-- vertx-modules/vertx/pom.xml | 2 +- web-modules/dropwizard/pom.xml | 2 +- web-modules/jooby/pom.xml | 4 ++-- web-modules/ninja/pom.xml | 2 +- web-modules/pom.xml | 2 +- 8 files changed, 12 insertions(+), 12 deletions(-) diff --git a/pom.xml b/pom.xml index 1c59d323b8..c3787e417d 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 diff --git a/testing-modules/gatling-java/pom.xml b/testing-modules/gatling-java/pom.xml index c759928cc5..54e18b3ac1 100644 --- a/testing-modules/gatling-java/pom.xml +++ b/testing-modules/gatling-java/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 org.baeldung gatling-java diff --git a/testing-modules/junit-5-advanced/pom.xml b/testing-modules/junit-5-advanced/pom.xml index 5a65b0f6f3..998f6561ea 100644 --- a/testing-modules/junit-5-advanced/pom.xml +++ b/testing-modules/junit-5-advanced/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 junit-5-advanced 1.0-SNAPSHOT diff --git a/vertx-modules/vertx/pom.xml b/vertx-modules/vertx/pom.xml index 786ce44e79..75df2fae69 100644 --- a/vertx-modules/vertx/pom.xml +++ b/vertx-modules/vertx/pom.xml @@ -55,7 +55,7 @@ - + ${project.build.directory}/${project.artifactId}-${project.version}-app.jar diff --git a/web-modules/dropwizard/pom.xml b/web-modules/dropwizard/pom.xml index 999aa5c805..03562acded 100644 --- a/web-modules/dropwizard/pom.xml +++ b/web-modules/dropwizard/pom.xml @@ -49,7 +49,7 @@ + implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> com.baeldung.dropwizard.introduction.IntroductionApplication diff --git a/web-modules/jooby/pom.xml b/web-modules/jooby/pom.xml index 024a41e1d9..238f17571f 100644 --- a/web-modules/jooby/pom.xml +++ b/web-modules/jooby/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/maven-v4_0_0.xsd"> 4.0.0 com.baeldung.jooby jooby diff --git a/web-modules/ninja/pom.xml b/web-modules/ninja/pom.xml index b8ddb641cd..cb3e234172 100644 --- a/web-modules/ninja/pom.xml +++ b/web-modules/ninja/pom.xml @@ -170,7 +170,7 @@ + implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> ninja.standalone.NinjaJetty diff --git a/web-modules/pom.xml b/web-modules/pom.xml index 97ef2a25e1..97134ee31c 100644 --- a/web-modules/pom.xml +++ b/web-modules/pom.xml @@ -20,7 +20,7 @@ dropwizard google-web-toolkit jakarta-ee - + javax-servlets javax-servlets-2 jee-7 From 9e287cf3f3ca80dc9f43d3ce40307d9a9d04f138 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 24 May 2023 19:39:23 +0530 Subject: [PATCH 21/98] JAVA_21305: Changes made for fix the Integration test faliures (#14113) --- web-modules/ratpack/pom.xml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/web-modules/ratpack/pom.xml b/web-modules/ratpack/pom.xml index 156080ccca..1ef358cc55 100644 --- a/web-modules/ratpack/pom.xml +++ b/web-modules/ratpack/pom.xml @@ -85,6 +85,20 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + + + + + + 1.9.0 4.5.3 From 67b76b53a5063d69ae179d841b4e5c9c27c5b530 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Wed, 24 May 2023 17:22:01 +0300 Subject: [PATCH 22/98] JAVA-20164 Fix .._SEQ.NEXTVAL error (#14109) Co-authored-by: timis1 --- .../java-jpa/src/main/resources/META-INF/persistence.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 5d0c79c2a7..b4816885b5 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -97,7 +97,7 @@ true - + From 984913be76affac3f6c8e01b69e1a5583ff1baa6 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Wed, 24 May 2023 17:32:13 +0300 Subject: [PATCH 23/98] JAVA-15022 (#14099) * [JAVA-15022] Moved 4.5 version code to apache-httpclient4 module * [JAVA-15022] Upgraded code to 5.x version --- .../httpclient/HttpAsyncClientLiveTest.java | 169 +++++++++++------ .../httpclient/HttpAsyncClientV4LiveTest.java | 174 ++++++++++++++++++ 2 files changed, 286 insertions(+), 57 deletions(-) create mode 100644 apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java index 082c282306..ab0e4e6308 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -1,7 +1,7 @@ package com.baeldung.httpclient; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import java.io.IOException; import java.util.concurrent.ExecutionException; @@ -9,30 +9,36 @@ import java.util.concurrent.Future; import javax.net.ssl.SSLContext; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.apache.http.conn.ssl.TrustStrategy; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.cookie.BasicClientCookie; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.apache.http.impl.nio.client.HttpAsyncClients; -import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; -import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; -import org.apache.http.nio.reactor.ConnectingIOReactor; -import org.apache.http.protocol.BasicHttpContext; -import org.apache.http.protocol.HttpContext; -import org.apache.http.ssl.SSLContexts; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class HttpAsyncClientLiveTest { +import org.apache.hc.client5.http.async.methods.SimpleHttpRequest; +import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; +import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder; +import org.apache.hc.client5.http.auth.AuthScope; +import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.cookie.BasicCookieStore; +import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; +import org.apache.hc.client5.http.impl.async.HttpAsyncClients; +import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider; +import org.apache.hc.client5.http.impl.cookie.BasicClientCookie; +import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; +import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder; +import org.apache.hc.core5.concurrent.FutureCallback; +import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.nio.ssl.TlsStrategy; +import org.apache.hc.core5.http.protocol.BasicHttpContext; +import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.reactor.IOReactorConfig; +import org.apache.hc.core5.ssl.SSLContexts; +import org.apache.hc.core5.ssl.TrustStrategy; + + +class HttpAsyncClientLiveTest { private static final String HOST = "http://www.google.com"; private static final String HOST_WITH_SSL = "https://mms.nw.ru/"; @@ -48,23 +54,33 @@ public class HttpAsyncClientLiveTest { // tests @Test - public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException { + void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException { + final HttpHost target = new HttpHost(HOST); + final SimpleHttpRequest request = SimpleRequestBuilder.get() + .setHttpHost(target) + .build(); + final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); client.start(); - final HttpGet request = new HttpGet(HOST); - final Future future = client.execute(request, null); + + final Future future = client.execute(request, null); final HttpResponse response = future.get(); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getCode(), equalTo(200)); client.close(); } @Test - public void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception { - final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); - final PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor); - final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build(); + void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception { + final IOReactorConfig ioReactorConfig = IOReactorConfig + .custom() + .build(); + + final CloseableHttpAsyncClient client = HttpAsyncClients.custom() + .setIOReactorConfig(ioReactorConfig) + .build(); + client.start(); final String[] toGet = { "http://www.google.com/", "http://www.apache.org/", "http://www.bing.com/" }; @@ -85,36 +101,68 @@ public class HttpAsyncClientLiveTest { } @Test - public void whenUseProxyWithHttpClient_thenCorrect() throws Exception { + void whenUseProxyWithHttpClient_thenCorrect() throws Exception { final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); client.start(); final HttpHost proxy = new HttpHost("127.0.0.1", 8080); final RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); - final HttpGet request = new HttpGet(HOST_WITH_PROXY); + final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_PROXY); request.setConfig(config); - final Future future = client.execute(request, null); - final HttpResponse response = future.get(); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + final Future future = client.execute(request, new FutureCallback<>(){ + @Override + public void completed(SimpleHttpResponse response) { + + System.out.println("responseData"); + } + + @Override + public void failed(Exception ex) { + System.out.println("Error executing HTTP request: " + ex.getMessage()); + } + + @Override + public void cancelled() { + System.out.println("HTTP request execution cancelled"); + } + }); + + final HttpResponse response = future.get(); + assertThat(response.getCode(), equalTo(200)); client.close(); } @Test - public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception { + void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception { final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; - final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); - final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build(); + final SSLContext sslContext = SSLContexts.custom() + .loadTrustMaterial(null, acceptingTrustStrategy) + .build(); + + final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create() + .setSslContext(sslContext) + .build(); + + final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create() + .setTlsStrategy(tlsStrategy) + .build(); + + final CloseableHttpAsyncClient client = HttpAsyncClients.custom() + .setConnectionManager(cm) + .build(); client.start(); - final HttpGet request = new HttpGet(HOST_WITH_SSL); - final Future future = client.execute(request, null); + + final SimpleHttpRequest request = new SimpleHttpRequest("GET",HOST_WITH_SSL); + final Future future = client.execute(request, null); + final HttpResponse response = future.get(); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getCode(), equalTo(200)); client.close(); } @Test - public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception { + void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234"); cookie.setDomain(COOKIE_DOMAIN); @@ -122,29 +170,36 @@ public class HttpAsyncClientLiveTest { cookieStore.addCookie(cookie); final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build(); client.start(); - final HttpGet request = new HttpGet(HOST_WITH_COOKIE); + final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_COOKIE); final HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); - final Future future = client.execute(request, localContext, null); + final Future future = client.execute(request, localContext, null); + final HttpResponse response = future.get(); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getCode(), equalTo(200)); client.close(); } @Test - public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception { - final CredentialsProvider provider = new BasicCredentialsProvider(); - final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); - provider.setCredentials(AuthScope.ANY, creds); - final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build(); + void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception { + final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); + final UsernamePasswordCredentials credentials = + new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS.toCharArray()); + credsProvider.setCredentials(new AuthScope(URL_SECURED_BY_BASIC_AUTHENTICATION, 80) ,credentials); + final CloseableHttpAsyncClient client = HttpAsyncClients + .custom() + .setDefaultCredentialsProvider(credsProvider).build(); + + final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,URL_SECURED_BY_BASIC_AUTHENTICATION); - final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); client.start(); - final Future future = client.execute(request, null); + + final Future future = client.execute(request, null); + final HttpResponse response = future.get(); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getCode(), equalTo(200)); client.close(); } @@ -163,9 +218,9 @@ public class HttpAsyncClientLiveTest { @Override public void run() { try { - final Future future = client.execute(request, context, null); + final Future future = client.execute(SimpleHttpRequest.copy(request), context, null); final HttpResponse response = future.get(); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getCode(), equalTo(200)); } catch (final Exception ex) { System.out.println(ex.getLocalizedMessage()); } diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java new file mode 100644 index 0000000000..dc0055c5ae --- /dev/null +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java @@ -0,0 +1,174 @@ +package com.baeldung.httpclient; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import javax.net.ssl.SSLContext; + +import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.cookie.BasicClientCookie; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; +import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; +import org.apache.http.nio.reactor.ConnectingIOReactor; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; +import org.apache.http.ssl.SSLContexts; +import org.junit.jupiter.api.Test; + +class HttpAsyncClientV4LiveTest { + + private static final String HOST = "http://www.google.com"; + private static final String HOST_WITH_SSL = "https://mms.nw.ru/"; + private static final String HOST_WITH_PROXY = "http://httpbin.org/"; + private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";// "http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"; + private static final String DEFAULT_USER = "test";// "user1"; + private static final String DEFAULT_PASS = "test";// "user1Pass"; + + private static final String HOST_WITH_COOKIE = "http://yuilibrary.com/yui/docs/cookie/cookie-simple-example.html"; // "http://github.com"; + private static final String COOKIE_DOMAIN = ".yuilibrary.com"; // ".github.com"; + private static final String COOKIE_NAME = "example"; // "JSESSIONID"; + + // tests + + @Test + void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException { + final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); + client.start(); + final HttpGet request = new HttpGet(HOST); + + final Future future = client.execute(request, null); + final HttpResponse response = future.get(); + + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + client.close(); + } + + @Test + void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception { + final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); + final PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor); + final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build(); + client.start(); + final String[] toGet = { "http://www.google.com/", "http://www.apache.org/", "http://www.bing.com/" }; + + final GetThread[] threads = new GetThread[toGet.length]; + for (int i = 0; i < threads.length; i++) { + final HttpGet request = new HttpGet(toGet[i]); + threads[i] = new GetThread(client, request); + } + + for (final GetThread thread : threads) { + thread.start(); + } + + for (final GetThread thread : threads) { + thread.join(); + } + + } + + @Test + void whenUseProxyWithHttpClient_thenCorrect() throws Exception { + final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); + client.start(); + final HttpHost proxy = new HttpHost("127.0.0.1", 8080); + final RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); + final HttpGet request = new HttpGet(HOST_WITH_PROXY); + request.setConfig(config); + final Future future = client.execute(request, null); + final HttpResponse response = future.get(); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + client.close(); + } + + @Test + void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception { + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; + final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); + + final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build(); + + client.start(); + final HttpGet request = new HttpGet(HOST_WITH_SSL); + final Future future = client.execute(request, null); + final HttpResponse response = future.get(); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + client.close(); + } + + @Test + void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception { + final BasicCookieStore cookieStore = new BasicCookieStore(); + final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234"); + cookie.setDomain(COOKIE_DOMAIN); + cookie.setPath("/"); + cookieStore.addCookie(cookie); + final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build(); + client.start(); + final HttpGet request = new HttpGet(HOST_WITH_COOKIE); + + final HttpContext localContext = new BasicHttpContext(); + localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); + + final Future future = client.execute(request, localContext, null); + final HttpResponse response = future.get(); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + client.close(); + } + + @Test + void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception { + final CredentialsProvider provider = new BasicCredentialsProvider(); + final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); + provider.setCredentials(AuthScope.ANY, creds); + final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build(); + + final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); + client.start(); + final Future future = client.execute(request, null); + final HttpResponse response = future.get(); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + client.close(); + } + + static class GetThread extends Thread { + + private final CloseableHttpAsyncClient client; + private final HttpContext context; + private final HttpGet request; + + GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { + this.client = client; + context = HttpClientContext.create(); + this.request = request; + } + + @Override + public void run() { + try { + final Future future = client.execute(request, context, null); + final HttpResponse response = future.get(); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + } catch (final Exception ex) { + System.out.println(ex.getLocalizedMessage()); + } + } + + } +} \ No newline at end of file From 82500be545723688d609824cbfbfac006e8a8f31 Mon Sep 17 00:00:00 2001 From: Bahaa El-Din Helmy Date: Wed, 24 May 2023 17:59:59 +0300 Subject: [PATCH 24/98] Array vs List Performance in Java (#14114) This commit is related to the article entitled "Array vs List Performance in Java" --- .../ArrayAndArrayListPerformance.java | 116 ++++++++++-------- 1 file changed, 64 insertions(+), 52 deletions(-) diff --git a/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java index 3b8fa8c9f3..59540c69b9 100644 --- a/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java +++ b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java @@ -1,65 +1,77 @@ package com.baeldung.arrayandlistperformance; + import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.options.OptionsBuilder; + import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.concurrent.TimeUnit; + @State(Scope.Benchmark) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public class ArrayAndArrayListPerformance { - @Benchmark - public void arrayCreation() { - int[] array = new int[1000000]; - } - - @Benchmark - public void arrayListCreation() { - ArrayList list = new ArrayList<>(1000000); - } - - @Benchmark - public void arrayItemSetting() { - int[] array = new int[1000000]; - array[0] = 10; - } - - @Benchmark - public void arrayListItemSetting() { - ArrayList list = new ArrayList<>(1000000); - list.add(0, 10); - } - - @Benchmark - public void arrayItemRetrieval() { - int[] array = new int[1000000]; - array[0] = 10; - int item = array[0]; - } - - @Benchmark - public void arrayListItemRetrieval() { - ArrayList list = new ArrayList<>(1000000); - list.add(0, 10); - int item2 = list.get(0); - } - - @Benchmark - public void arrayCloning() { - int[] array = new int[1000000]; - int[] newArray = array.clone(); - } - - @Benchmark - public void arrayListCloning() { - ArrayList list = new ArrayList<>(1000000); - ArrayList newList = new ArrayList<>(list); - } public static void main(String[] args) throws Exception { - org.openjdk.jmh.runner.Runner runner = new org.openjdk.jmh.runner.Runner(new OptionsBuilder() - .include(ArrayAndArrayListPerformance.class.getSimpleName()) - .forks(1) - .build()); + org.openjdk.jmh.runner.Runner runner = new org.openjdk.jmh.runner.Runner(new OptionsBuilder().include(ArrayAndArrayListPerformance.class.getSimpleName()).forks(1).build()); runner.run(); } - } \ No newline at end of file + public static Integer[] array = Collections.nCopies(256, 1).toArray(new Integer[0]); + public static ArrayList list = new ArrayList( + Arrays.asList(array)); + @Benchmark + public Integer[] arrayCreation() { + return new Integer[256]; + } + + @Benchmark + public ArrayList arrayListCreation() { + return new ArrayList<>(256); + } + + @Benchmark + public Integer[] arrayItemsSetting() { + for (int i = 0; i < 256; i++) { + array[i] = i; + } + return array; + } + + @Benchmark + public ArrayList arrayListItemsSetting() { + for (int i = 0; i < 256; i++) { + list.set(i,i); + } + return list; + } + + @Benchmark + public void arrayItemsRetrieval(Blackhole blackhole) { + for (int i = 0; i < 256; i++) { + int item = array[i]; + blackhole.consume(item); + } + } + + @Benchmark + public void arrayListItemsRetrieval(Blackhole blackhole) { + for (int i = 0; i < 256; i++) { + int item = list.get(i); + blackhole.consume(item); + } + } + + @Benchmark + public void arrayCloning(Blackhole blackhole) { + Integer[] newArray = array.clone(); + blackhole.consume(newArray); + } + + @Benchmark + public void arrayListCloning(Blackhole blackhole) { + ArrayList newList = new ArrayList<>(list); + blackhole.consume(newList); + } +} \ No newline at end of file From 752b49ba02dd2f4974ee393946c41839c7d57e42 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Wed, 24 May 2023 17:26:01 +0200 Subject: [PATCH 25/98] BAEL-6461: What's the difference between Scanner next() and nextLine() methods? (#14057) --- .../scanner/NextVsNextLineUnitTest.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java new file mode 100644 index 0000000000..08d2ebe288 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.scanner; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Scanner; + +import org.junit.jupiter.api.Test; + +class NextVsNextLineUnitTest { + + @Test + void givenInput_whenUsingNextMethod_thenReturnToken() { + String input = "Hello world"; + try (Scanner scanner = new Scanner(input)) { + assertEquals("Hello", scanner.next()); + assertEquals("world", scanner.next()); + } + } + + @Test + void givenInput_whenUsingNextMethodWithCustomDelimiter_thenReturnToken() { + String input = "Hello :world"; + try (Scanner scanner = new Scanner(input)) { + scanner.useDelimiter(":"); + + assertEquals("Hello ", scanner.next()); + assertEquals("world", scanner.next()); + } + } + + @Test + void givenInput_whenUsingNextLineMethod_thenReturnEntireLine() { + String input = "Hello world\nWelcome to baeldung.com"; + try (Scanner scanner = new Scanner(input)) { + assertEquals("Hello world", scanner.nextLine()); + assertEquals("Welcome to baeldung.com", scanner.nextLine()); + } + } + + @Test + void givenInput_whenUsingNextLineWithCustomDelimiter_thenIgnoreDelimiter() { + String input = "Hello:world\nWelcome:to baeldung.com"; + try (Scanner scanner = new Scanner(input)) { + scanner.useDelimiter(":"); + + assertEquals("Hello:world", scanner.nextLine()); + assertEquals("Welcome:to baeldung.com", scanner.nextLine()); + } + } + +} From 2ef1a51767716650c0d5d1cab4ecec9ad53cb6ef Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 24 May 2023 23:06:41 +0530 Subject: [PATCH 26/98] JAVA-19670: changes made for upgrading jenkins module to jdk-9 above (#14105) * JAVA-19670: changes made for upgrading jenkins module to jdk-9 above * JAVA-19670: Changes made for adding jenkins-modules in jdk-9 and above profile --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index c3787e417d..764eccdac9 100644 --- a/pom.xml +++ b/pom.xml @@ -473,7 +473,6 @@ image-processing - jenkins-modules jhipster-modules @@ -633,7 +632,6 @@ image-processing - jenkins-modules jhipster-modules @@ -926,6 +924,7 @@ vaadin libraries-3 web-modules + jenkins-modules xml xml-2 @@ -1187,6 +1186,7 @@ vaadin libraries-3 web-modules + jenkins-modules xml xml-2 From d483eed2b664edc1365bfc9d6e2f65b6d3a8a16e Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 24 May 2023 23:08:41 +0530 Subject: [PATCH 27/98] JAVA_21106: Changes made for fixing test cases for jee-7 (#14115) --- web-modules/jee-7/pom.xml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/web-modules/jee-7/pom.xml b/web-modules/jee-7/pom.xml index 00314ab35f..33ecfb3d2b 100644 --- a/web-modules/jee-7/pom.xml +++ b/web-modules/jee-7/pom.xml @@ -337,6 +337,15 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + + + From f993296b0be3737c6e10fecf9cae2fa6f7a1997f Mon Sep 17 00:00:00 2001 From: Hamid Reza Sharifi Date: Thu, 25 May 2023 13:17:53 +0330 Subject: [PATCH 28/98] Bael 5711: Securing Spring Boot API with API key and secret (#14102) * #bael-5711: add source * #bael-5711: remove extra space * #bael-5711: remove extra space * #bael-5711: remove extra space * #bael-5711: add custom message * #bael-5711: refactor return null --------- Co-authored-by: h_sharifi --- .../configuration/AuthenticationFilter.java | 18 ++++++++++++++++-- .../configuration/AuthenticationService.java | 7 ++++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationFilter.java b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationFilter.java index 6c82f9c9ef..aa4badcfb0 100644 --- a/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationFilter.java +++ b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationFilter.java @@ -1,5 +1,6 @@ package com.baeldung.apikeyauthentication.configuration; +import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.GenericFilterBean; @@ -8,15 +9,28 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.io.IOException; +import java.io.PrintWriter; public class AuthenticationFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { - Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request); - SecurityContextHolder.getContext().setAuthentication(authentication); + try { + Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request); + SecurityContextHolder.getContext().setAuthentication(authentication); + } catch (Exception exp) { + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); + PrintWriter writer = httpResponse.getWriter(); + writer.print(exp.getMessage()); + writer.flush(); + writer.close(); + } + filterChain.doFilter(request, response); } } diff --git a/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationService.java b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationService.java index 14183f9f62..c788f7cdd8 100644 --- a/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationService.java +++ b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationService.java @@ -1,5 +1,6 @@ package com.baeldung.apikeyauthentication.configuration; +import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import javax.servlet.http.HttpServletRequest; @@ -11,10 +12,10 @@ public class AuthenticationService { public static Authentication getAuthentication(HttpServletRequest request) { String apiKey = request.getHeader(AUTH_TOKEN_HEADER_NAME); - if (apiKey != null && apiKey.equals(AUTH_TOKEN)) { - return new ApiKeyAuthentication(apiKey, AuthorityUtils.NO_AUTHORITIES); + if (apiKey == null || !apiKey.equals(AUTH_TOKEN)) { + throw new BadCredentialsException("Invalid API Key"); } - return null; + return new ApiKeyAuthentication(apiKey, AuthorityUtils.NO_AUTHORITIES); } } From 317b7dcd0dfacbf6a0ddae17f7c64017fb3c6b3a Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 25 May 2023 23:20:07 +0800 Subject: [PATCH 29/98] Update README.md [skip ci] --- core-java-modules/core-java-security-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-security-3/README.md b/core-java-modules/core-java-security-3/README.md index a5cfa5bdca..222834d06b 100644 --- a/core-java-modules/core-java-security-3/README.md +++ b/core-java-modules/core-java-security-3/README.md @@ -12,4 +12,5 @@ This module contains articles about core Java Security - [Computing an X509 Certificate’s Thumbprint in Java](https://www.baeldung.com/java-x509-certificate-thumbprint) - [Error: “trustAnchors parameter must be non-empty”](https://www.baeldung.com/java-trustanchors-parameter-must-be-non-empty) - [Common Exceptions of Crypto APIs in Java](https://www.baeldung.com/java-crypto-apis-exceptions) +- [Hashing With Argon2 in Java](https://www.baeldung.com/java-argon2-hashing) - More articles: [[<-- prev]](/core-java-modules/core-java-security-2) From aac4faa5fe1decfc8875dfbb8a94f49adde9620c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 25 May 2023 23:31:28 +0800 Subject: [PATCH 30/98] Update README.md [skip ci] --- testing-modules/rest-assured/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/rest-assured/README.md b/testing-modules/rest-assured/README.md index 96d3c5e353..aa66965fd3 100644 --- a/testing-modules/rest-assured/README.md +++ b/testing-modules/rest-assured/README.md @@ -7,4 +7,4 @@ - [REST-assured with Groovy](http://www.baeldung.com/rest-assured-groovy) - [Headers, Cookies and Parameters with REST-assured](http://www.baeldung.com/rest-assured-header-cookie-parameter) - [JSON Schema Validation with REST-assured](http://www.baeldung.com/rest-assured-json-schema) - +- [Send MultipartFile Request With RestAssured](https://www.baeldung.com/restassured-send-multipartfile-request) From 87001cac68497d4b8e0213b86e785de7bffc97c9 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 25 May 2023 23:40:52 +0800 Subject: [PATCH 31/98] Create README.md [skip ci] --- spring-security-modules/spring-security-web-boot-5/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 spring-security-modules/spring-security-web-boot-5/README.md diff --git a/spring-security-modules/spring-security-web-boot-5/README.md b/spring-security-modules/spring-security-web-boot-5/README.md new file mode 100644 index 0000000000..baccebf8bd --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Shared Secret Authentication in Spring Boot Application](https://www.baeldung.com/spring-boot-shared-secret-authentication) From dcc1b2c453354088bab1c95cf8fc26049a5f5a9b Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 25 May 2023 23:49:41 +0800 Subject: [PATCH 32/98] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-repo-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-repo-3/README.md b/persistence-modules/spring-data-jpa-repo-3/README.md index d3782eb1e6..2ed2dc8896 100644 --- a/persistence-modules/spring-data-jpa-repo-3/README.md +++ b/persistence-modules/spring-data-jpa-repo-3/README.md @@ -5,4 +5,5 @@ This module contains articles about Spring Data JPA. ### Relevant Articles: - [New CRUD Repository Interfaces in Spring Data 3](https://www.baeldung.com/spring-data-3-crud-repository-interfaces) - [How to Persist a List of String in JPA?](https://www.baeldung.com/java-jpa-persist-string-list) +- [Hibernate Natural IDs in Spring Boot](https://www.baeldung.com/spring-boot-hibernate-natural-ids) - More articles: [[<-- prev]](../spring-data-jpa-repo-2) From 81b05716ff33616ef39263cdaacecb5fefd77806 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 00:00:50 +0800 Subject: [PATCH 33/98] Update README.md [skip ci] --- apache-kafka-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/apache-kafka-2/README.md b/apache-kafka-2/README.md index 157078f023..e86504d605 100644 --- a/apache-kafka-2/README.md +++ b/apache-kafka-2/README.md @@ -8,3 +8,4 @@ You can build the project from the command line using: *mvn clean install*, or i ### Relevant Articles: - [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running) - [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers) +- [Get Last N Messages in Apache Kafka Topic](https://www.baeldung.com/java-apache-kafka-get-last-n-messages) From 30f033702006542a70cd1d6ff6ba69ad5ac8d369 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 00:09:07 +0800 Subject: [PATCH 34/98] 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 0d9b12b842..1769d11686 100644 --- a/core-java-modules/core-java-collections-5/README.md +++ b/core-java-modules/core-java-collections-5/README.md @@ -4,4 +4,5 @@ ### Relevant Articles: - [Introduction to Roaring Bitmap](https://www.baeldung.com/java-roaring-bitmap-intro) +- [Creating Custom Iterator in Java](https://www.baeldung.com/java-creating-custom-iterator) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-4) From 5ff88e9dab08434b9b176c4ce1d4a33849a02b61 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 00:19:08 +0800 Subject: [PATCH 35/98] Update README.md [skip ci] --- core-java-modules/core-java-streams-5/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-java-modules/core-java-streams-5/README.md b/core-java-modules/core-java-streams-5/README.md index 4f367799f2..c0df5990c4 100644 --- a/core-java-modules/core-java-streams-5/README.md +++ b/core-java-modules/core-java-streams-5/README.md @@ -1 +1,3 @@ +## Relevant Articles - [Difference Between parallelStream() and stream().parallel() in Java](https://www.baeldung.com/java-parallelstream-vs-stream-parallel) +- [Working With Empty Stream in Java](https://www.baeldung.com/java-empty-stream) From 85ae160de40df22a1b6b64dda4bba22aad8b9837 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 00:22:10 +0800 Subject: [PATCH 36/98] Update README.md [skip ci] --- spring-reactive-modules/spring-reactive-exceptions/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-reactive-modules/spring-reactive-exceptions/README.md b/spring-reactive-modules/spring-reactive-exceptions/README.md index 8c5bc4f537..fc1a31b26f 100644 --- a/spring-reactive-modules/spring-reactive-exceptions/README.md +++ b/spring-reactive-modules/spring-reactive-exceptions/README.md @@ -1,2 +1,3 @@ - +## Relevant Articles - [How to Resolve Spring Webflux DataBufferLimitException](https://www.baeldung.com/spring-webflux-databufferlimitexception) +- [Custom WebFlux Exceptions in Spring Boot 3](https://www.baeldung.com/spring-boot-custom-webflux-exceptions) From 8975978757abd26835d0c95d81152b40bb8aaad1 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 00:34:00 +0800 Subject: [PATCH 37/98] Create README.md [skip ci] --- core-java-modules/core-java-string-conversions-3/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 core-java-modules/core-java-string-conversions-3/README.md diff --git a/core-java-modules/core-java-string-conversions-3/README.md b/core-java-modules/core-java-string-conversions-3/README.md new file mode 100644 index 0000000000..2a2fcca1fe --- /dev/null +++ b/core-java-modules/core-java-string-conversions-3/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Object.toString() vs String.valueOf()](https://www.baeldung.com/java-object-tostring-vs-string-valueof) From 73de91bf9b1c7592544227ffbec35aa1e7fe2156 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 00:38:16 +0800 Subject: [PATCH 38/98] Update README.md [skip ci] --- core-java-modules/core-java-string-conversions-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-conversions-3/README.md b/core-java-modules/core-java-string-conversions-3/README.md index 2a2fcca1fe..e62f7e9b39 100644 --- a/core-java-modules/core-java-string-conversions-3/README.md +++ b/core-java-modules/core-java-string-conversions-3/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Object.toString() vs String.valueOf()](https://www.baeldung.com/java-object-tostring-vs-string-valueof) +- [Converting List to Page Using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-convert-list-page) From 7ed8ff9e9fdbc82b3d6b53a0b0bf3fa684573ff1 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 00:46:34 +0800 Subject: [PATCH 39/98] Update README.md [skip ci] --- core-java-modules/core-java-string-conversions-3/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java-string-conversions-3/README.md b/core-java-modules/core-java-string-conversions-3/README.md index e62f7e9b39..2a2fcca1fe 100644 --- a/core-java-modules/core-java-string-conversions-3/README.md +++ b/core-java-modules/core-java-string-conversions-3/README.md @@ -1,3 +1,2 @@ ## Relevant Articles - [Object.toString() vs String.valueOf()](https://www.baeldung.com/java-object-tostring-vs-string-valueof) -- [Converting List to Page Using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-convert-list-page) From 2b06a2453364cd4be29220f7d67d7f4b5b88c6b3 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 00:53:15 +0800 Subject: [PATCH 40/98] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-query-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-query-3/README.md b/persistence-modules/spring-data-jpa-query-3/README.md index c0cc4f6511..8b094e66b2 100644 --- a/persistence-modules/spring-data-jpa-query-3/README.md +++ b/persistence-modules/spring-data-jpa-query-3/README.md @@ -8,6 +8,7 @@ This module contains articles about querying data using Spring Data JPA. - [Joining Tables With Spring Data JPA Specifications](https://www.baeldung.com/spring-jpa-joining-tables) - [NonUniqueResultException in Spring Data JPA](https://www.baeldung.com/spring-jpa-non-unique-result-exception) - [Spring Data Repositories – Collections vs. Stream](https://www.baeldung.com/spring-data-collections-vs-stream) +- [Converting List to Page Using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-convert-list-page) - More articles: [[<-- prev]](../spring-data-jpa-query-2) ### Eclipse Config From 4a479efd69d408dbc0eb422cd26b1101c84bebf4 Mon Sep 17 00:00:00 2001 From: uzma Date: Thu, 25 May 2023 23:36:24 +0100 Subject: [PATCH 41/98] [BAEL-6105] code for correct use of flush --- .../java/com/baeldung/flush/AppConfig.java | 49 +++++ .../java/com/baeldung/flush/Customer.java | 52 +++++ .../com/baeldung/flush/CustomerAddress.java | 47 +++++ .../data/jpa/flush/FlushIntegrationTest.java | 199 ++++++++++++++++++ 4 files changed, 347 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/AppConfig.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/Customer.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/CustomerAddress.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/flush/FlushIntegrationTest.java diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/AppConfig.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/AppConfig.java new file mode 100644 index 0000000000..e408b77d5f --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/AppConfig.java @@ -0,0 +1,49 @@ +package com.baeldung.flush; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +@Configuration +public class AppConfig { + + @Bean + public DataSource dataSource() { + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .build(); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { + LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(dataSource); + emf.setPackagesToScan("com.baeldung.flush"); + emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + emf.setJpaProperties(getHibernateProperties()); + return emf; + } + + @Bean + public JpaTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory.getObject()); + } + + private Properties getHibernateProperties() { + Properties properties = new Properties(); + properties.setProperty("hibernate.hbm2ddl.auto", "create"); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + return properties; + } +} + + + + diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/Customer.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/Customer.java new file mode 100644 index 0000000000..f4fc3c5b1f --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/Customer.java @@ -0,0 +1,52 @@ +package com.baeldung.flush; + +import java.util.Objects; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; + +@Entity +public class Customer { + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Customer customer = (Customer) o; + return age == customer.age && name.equals(customer.name); + } + + @Override + public int hashCode() { + return Objects.hash(name, age); + } + + private String name; + private int age; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/CustomerAddress.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/CustomerAddress.java new file mode 100644 index 0000000000..eb8caef19d --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/flush/CustomerAddress.java @@ -0,0 +1,47 @@ +package com.baeldung.flush; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; + +@Entity +public class CustomerAddress { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String street; + + private String city; + + private long customer_id; + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public Long getId() { + return id; + } + + public long getCustomer_id() { + return customer_id; + } + + public void setCustomer_id(long customer_id) { + this.customer_id = customer_id; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/flush/FlushIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/flush/FlushIntegrationTest.java new file mode 100644 index 0000000000..0b301532a5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/flush/FlushIntegrationTest.java @@ -0,0 +1,199 @@ +package com.baeldung.spring.data.jpa.flush; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.flush.AppConfig; +import com.baeldung.flush.Customer; +import com.baeldung.flush.CustomerAddress; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; +import jakarta.persistence.FlushModeType; +import jakarta.persistence.PersistenceUnit; +import jakarta.persistence.TypedQuery; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { AppConfig.class }) +public class FlushIntegrationTest { + + private static final Customer EXPECTED_CUSTOMER = aCustomer(); + + @PersistenceUnit + private EntityManagerFactory entityManagerFactory; + + private EntityManager entityManager; + + @BeforeEach + void setup() { + entityManager = entityManagerFactory.createEntityManager(); + } + + @Test + void givenANewCustomer_whenPersistAndNoFlush_thenDatabaseNotSynchronizedWithPersistentContextUsingCommitFlushMode() { + + entityManager.setFlushMode(FlushModeType.COMMIT); + + EntityTransaction transaction = getTransaction(); + Customer customer = saveCustomerInPersistentContext("Alice", 30); + Customer customerInContext = entityManager.find(Customer.class, customer.getId()); + assertDataInPersitentContext(customerInContext); + + TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); + + List resultList = retrievedCustomer.getResultList(); + + assertThat(resultList).isEmpty(); + transaction.rollback(); + } + + @Test + void givenANewCustomer_whenPersistAndFlush_thenDatabaseSynchronizedWithPersistentContextUsingCommitFlushMode() { + entityManager.setFlushMode(FlushModeType.COMMIT); + + EntityTransaction transaction = getTransaction(); + Customer customer = saveCustomerInPersistentContext("Alice", 30); + entityManager.flush(); + Long generatedCustomerID = customer.getId(); + + Customer customerInContext = entityManager.find(Customer.class, generatedCustomerID); + assertDataInPersitentContext(customerInContext); + + TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); + + Customer result = retrievedCustomer.getSingleResult(); + assertThat(result).isEqualTo(EXPECTED_CUSTOMER); + transaction.rollback(); + } + + @Test + public void givenANewCustomer_whenPersistAndFlush_thenCustomerIdGeneratedToBeAddedInAddress() { + entityManager.setFlushMode(FlushModeType.COMMIT); + EntityTransaction transaction = getTransaction(); + + saveCustomerInPersistentContext("John", 25); + entityManager.flush(); + + Customer retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) + .getSingleResult(); + Long customerId = retrievedCustomer.getId(); + + CustomerAddress address = new CustomerAddress(); + address.setCustomer_id(customerId); + entityManager.persist(address); + entityManager.flush(); + + CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) + .setParameter("customerID", customerId) + .getSingleResult(); + + assertThat(customerAddress).isNotNull(); + transaction.rollback(); + } + + @Test + void givenANewCustomer_whenPersistAndNoFlush_thenDBIsSynchronizedWithThePersistentContextWithAutoFlushMode() { + entityManager.setFlushMode(FlushModeType.AUTO); + EntityTransaction transaction = getTransaction(); + + Customer customer = saveCustomerInPersistentContext("Alice", 30); + Customer customerInContext = entityManager.find(Customer.class, customer.getId()); + assertDataInPersitentContext(customerInContext); + + TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); + + Customer result = retrievedCustomer.getSingleResult(); + + assertThat(result).isEqualTo(EXPECTED_CUSTOMER); + + transaction.rollback(); + } + + @Test + public void givenFlushModeAutoAndNewCustomer_whenPersistAndNoFlush_thenCustomerIdGeneratedToBeAddedInAddress() { + entityManager.setFlushMode(FlushModeType.AUTO); + EntityTransaction transaction = getTransaction(); + + saveCustomerInPersistentContext("John", 25); + + Customer singleResult = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) + .getSingleResult(); + Long customerId = singleResult.getId(); + + CustomerAddress address = new CustomerAddress(); + address.setCustomer_id(customerId); + entityManager.persist(address); + + CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) + .setParameter("customerID", customerId) + .getSingleResult(); + + assertThat(customerAddress).isNotNull(); + transaction.rollback(); + } + + @Test + public void givenFlushModeAutoAndNewCustomer_whenPersistAndFlush_thenCustomerIdGeneratedToBeAddedInAddress() { + entityManager.setFlushMode(FlushModeType.AUTO); + EntityTransaction transaction = getTransaction(); + + saveCustomerInPersistentContext("John", 25); + + Customer singleResult = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) + .getSingleResult(); + Long customerId = singleResult.getId(); + + CustomerAddress address = new CustomerAddress(); + address.setCustomer_id(customerId); + entityManager.persist(address); + entityManager.flush(); + + CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) + .setParameter("customerID", customerId) + .getSingleResult(); + + assertThat(customerAddress).isNotNull(); + + transaction.rollback(); + } + + private static void assertDataInPersitentContext(Customer customerInContext) { + assertThat(customerInContext).isNotNull(); + assertThat(customerInContext.getName()).isEqualTo("Alice"); + } + + private Customer saveCustomerInPersistentContext(String name, int age) { + Customer customer = new Customer(); + customer.setName(name); + customer.setAge(age); + entityManager.persist(customer); + return customer; + } + + @AfterEach + public void cleanup() { + entityManager.clear(); + } + + private static Customer aCustomer() { + Customer customer = new Customer(); + customer.setName("Alice"); + customer.setAge(30); + return customer; + } + + private EntityTransaction getTransaction() { + EntityTransaction transaction = entityManager.getTransaction(); + transaction.begin(); + return transaction; + } +} \ No newline at end of file From 14fb1775e17fa2c991853958c198b436c5c29bbc Mon Sep 17 00:00:00 2001 From: uzma Date: Thu, 25 May 2023 23:38:09 +0100 Subject: [PATCH 42/98] [BAEL-6105] delete code from the old module --- .../java/com/baeldung/flush/AppConfig.java | 56 ----- .../java/com/baeldung/flush/Customer.java | 52 ----- .../com/baeldung/flush/CustomerAddress.java | 47 ----- .../boot/flush/FlushIntegrationTest.java | 191 ------------------ 4 files changed, 346 deletions(-) delete mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java delete mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java delete mode 100644 persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java delete mode 100644 persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java deleted file mode 100644 index 96210fd4b8..0000000000 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/AppConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.flush; - -import java.util.Properties; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; - -@Configuration -public class AppConfig { - - @Bean - public EntityManager entityManager(EntityManagerFactory entityManagerFactory) { - return entityManagerFactory.createEntityManager(); - } - - @Bean - public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) - .build(); - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { - LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); - emf.setDataSource(dataSource); - emf.setPackagesToScan("com.baeldung.flush"); - emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); - emf.setJpaProperties(getHibernateProperties()); - return emf; - } - - @Bean - public JpaTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactory) { - return new JpaTransactionManager(entityManagerFactory.getObject()); - } - - private Properties getHibernateProperties() { - Properties properties = new Properties(); - properties.setProperty("hibernate.hbm2ddl.auto", "create"); - properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); - return properties; - } -} - - - - diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java deleted file mode 100644 index a31620c653..0000000000 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/Customer.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.flush; - -import java.util.Objects; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Customer { - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - Customer customer = (Customer) o; - return age == customer.age && name.equals(customer.name); - } - - @Override - public int hashCode() { - return Objects.hash(name, age); - } - - private String name; - private int age; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - public Long getId() { - return id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } -} diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java deleted file mode 100644 index 8e4953117a..0000000000 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/flush/CustomerAddress.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.flush; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class CustomerAddress { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - private String street; - - private String city; - - private long customer_id; - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public Long getId() { - return id; - } - - public long getCustomer_id() { - return customer_id; - } - - public void setCustomer_id(long customer_id) { - this.customer_id = customer_id; - } -} diff --git a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java deleted file mode 100644 index c678c59f9a..0000000000 --- a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/flush/FlushIntegrationTest.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.baeldung.boot.flush; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.persistence.FlushModeType; -import javax.persistence.TypedQuery; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import com.baeldung.flush.AppConfig; -import com.baeldung.flush.Customer; -import com.baeldung.flush.CustomerAddress; - -@ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = { AppConfig.class }) - -public class FlushIntegrationTest { - - private static final Customer EXPECTED_CUSTOMER = aCustomer(); - - @Autowired - private EntityManager entityManager; - - @Test - void givenANewCustomer_whenPersistAndNoFlush_thenDatabaseNotSynchronizedWithPersistentContextUsingCommitFlushMode() { - - entityManager.setFlushMode(FlushModeType.COMMIT); - - EntityTransaction transaction = getTransaction(); - Customer customer = saveCustomerInPersistentContext("Alice", 30); - Customer customerInContext = entityManager.find(Customer.class, customer.getId()); - assertDataInPersitentContext(customerInContext); - - TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); - - List resultList = retrievedCustomer.getResultList(); - - assertThat(resultList).isEmpty(); - transaction.rollback(); - } - - @Test - void givenANewCustomer_whenPersistAndFlush_thenDatabaseSynchronizedWithPersistentContextUsingCommitFlushMode() { - entityManager.setFlushMode(FlushModeType.COMMIT); - - EntityTransaction transaction = getTransaction(); - Customer customer = saveCustomerInPersistentContext("Alice", 30); - entityManager.flush(); - Long generatedCustomerID = customer.getId(); - - Customer customerInContext = entityManager.find(Customer.class, generatedCustomerID); - assertDataInPersitentContext(customerInContext); - - TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); - - Customer result = retrievedCustomer.getSingleResult(); - assertThat(result).isEqualTo(EXPECTED_CUSTOMER); - transaction.rollback(); - } - - @Test - public void givenANewCustomer_whenPersistAndFlush_thenCustomerIdGeneratedToBeAddedInAddress() { - entityManager.setFlushMode(FlushModeType.COMMIT); - EntityTransaction transaction = getTransaction(); - - saveCustomerInPersistentContext("John", 25); - entityManager.flush(); - - Customer retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) - .getSingleResult(); - Long customerId = retrievedCustomer.getId(); - - CustomerAddress address = new CustomerAddress(); - address.setCustomer_id(customerId); - entityManager.persist(address); - entityManager.flush(); - - CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) - .setParameter("customerID", customerId) - .getSingleResult(); - - assertThat(customerAddress).isNotNull(); - transaction.rollback(); - } - - @Test - void givenANewCustomer_whenPersistAndNoFlush_thenDBIsSynchronizedWithThePersistentContextWithAutoFlushMode() { - entityManager.setFlushMode(FlushModeType.AUTO); - EntityTransaction transaction = getTransaction(); - - Customer customer = saveCustomerInPersistentContext("Alice", 30); - Customer customerInContext = entityManager.find(Customer.class, customer.getId()); - assertDataInPersitentContext(customerInContext); - - TypedQuery retrievedCustomer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'Alice'", Customer.class); - - Customer result = retrievedCustomer.getSingleResult(); - - assertThat(result).isEqualTo(EXPECTED_CUSTOMER); - - transaction.rollback(); - } - - @Test - public void givenFlushModeAutoAndNewCustomer_whenPersistAndNoFlush_thenCustomerIdGeneratedToBeAddedInAddress() { - entityManager.setFlushMode(FlushModeType.AUTO); - EntityTransaction transaction = getTransaction(); - - saveCustomerInPersistentContext("John", 25); - - Customer singleResult = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) - .getSingleResult(); - Long customerId = singleResult.getId(); - - CustomerAddress address = new CustomerAddress(); - address.setCustomer_id(customerId); - entityManager.persist(address); - - CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) - .setParameter("customerID", customerId) - .getSingleResult(); - - assertThat(customerAddress).isNotNull(); - transaction.rollback(); - } - - @Test - public void givenFlushModeAutoAndNewCustomer_whenPersistAndFlush_thenCustomerIdGeneratedToBeAddedInAddress() { - entityManager.setFlushMode(FlushModeType.AUTO); - EntityTransaction transaction = getTransaction(); - - saveCustomerInPersistentContext("John", 25); - - Customer singleResult = entityManager.createQuery("SELECT c FROM Customer c WHERE c.name = 'John'", Customer.class) - .getSingleResult(); - Long customerId = singleResult.getId(); - - CustomerAddress address = new CustomerAddress(); - address.setCustomer_id(customerId); - entityManager.persist(address); - entityManager.flush(); - - CustomerAddress customerAddress = entityManager.createQuery("SELECT a FROM CustomerAddress a WHERE a.customer_id = :customerID", CustomerAddress.class) - .setParameter("customerID", customerId) - .getSingleResult(); - - assertThat(customerAddress).isNotNull(); - - transaction.rollback(); - } - - private static void assertDataInPersitentContext(Customer customerInContext) { - assertThat(customerInContext).isNotNull(); - assertThat(customerInContext.getName()).isEqualTo("Alice"); - } - - private Customer saveCustomerInPersistentContext(String name, int age) { - Customer customer = new Customer(); - customer.setName(name); - customer.setAge(age); - entityManager.persist(customer); - return customer; - } - - @AfterEach - public void cleanup() { - entityManager.clear(); - } - - private static Customer aCustomer() { - Customer customer = new Customer(); - customer.setName("Alice"); - customer.setAge(30); - return customer; - } - - private EntityTransaction getTransaction() { - EntityTransaction transaction = entityManager.getTransaction(); - transaction.begin(); - return transaction; - } -} \ No newline at end of file From 296be923ce36f479274d9342a93d7c04b20678c0 Mon Sep 17 00:00:00 2001 From: Bahaa El-Din Helmy Date: Fri, 26 May 2023 03:45:29 +0300 Subject: [PATCH 43/98] Convert Hashmap to JSON object in Java (#14118) This commit is related to the article "Convert Hashmap to JSON object in Java" --- .../baeldung/maptojson/MapToJsonUnitTest.java | 66 +++++++++---------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java index d9b13f4f4a..d9c3ac57ff 100644 --- a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java +++ b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java @@ -17,40 +17,40 @@ import java.util.HashMap; import java.util.Map; public class MapToJsonUnitTest { -String originalJsonData = "{\"CS\":\"Post1\",\"Linux\":\"Post1\",\"Kotlin\":\"Post1\"}"; + String originalJsonData = "{\"CS\":\"Post1\",\"Linux\":\"Post1\",\"Kotlin\":\"Post1\"}"; -@Test -public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException { - Map data = new HashMap(); - data.put("CS", "Post1"); - data.put("Linux", "Post1"); - data.put("Kotlin", "Post1"); - ObjectMapper objectMapper = new ObjectMapper(); - String jacksonData = objectMapper.writeValueAsString(data); - Assertions.assertEquals(jacksonData,originalJsonData); -} + @Test + public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException { + Map data = new HashMap(); + data.put("CS", "Post1"); + data.put("Linux", "Post1"); + data.put("Kotlin", "Post1"); + ObjectMapper objectMapper = new ObjectMapper(); + String jacksonData = objectMapper.writeValueAsString(data); + Assertions.assertEquals(originalJsonData,jacksonData); + } -@Test -public void given_HashMapData_whenUsingGson_thenConvertToJson() { - Map data = new HashMap<>(); - data.put("CS", "Post1"); - data.put("Linux", "Post1"); - data.put("Kotlin", "Post1"); - Gson gson = new Gson(); - Type typeObject = new TypeToken() { - }.getType(); - String gsonData = gson.toJson(data, typeObject); - Assertions.assertEquals(gsonData,originalJsonData); -} + @Test + public void given_HashMapData_whenUsingGson_thenConvertToJson() { + Map data = new HashMap<>(); + data.put("CS", "Post1"); + data.put("Linux", "Post1"); + data.put("Kotlin", "Post1"); + Gson gson = new Gson(); + Type typeObject = new TypeToken() { + }.getType(); + String gsonData = gson.toJson(data, typeObject); + Assertions.assertEquals(originalJsonData,gsonData); + } -@Test -public void given_HashMapData_whenOrgJson_thenConvertToJsonUsing() { - Map data = new HashMap<>(); - data.put("CS", "Post1"); - data.put("Linux", "Post1"); - data.put("Kotlin", "Post1"); - JSONObject jsonObject = new JSONObject(data); - String orgJsonData = jsonObject.toString(); - Assertions.assertEquals(orgJsonData,originalJsonData); -} + @Test + public void given_HashMapData_whenOrgJson_thenConvertToJsonUsing() { + Map data = new HashMap<>(); + data.put("CS", "Post1"); + data.put("Linux", "Post1"); + data.put("Kotlin", "Post1"); + JSONObject jsonObject = new JSONObject(data); + String orgJsonData = jsonObject.toString(); + Assertions.assertEquals(originalJsonData,orgJsonData); + } } \ No newline at end of file From c6b2b99bb2bba96f5e0853b0e032c992b1e31697 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 10:21:02 +0800 Subject: [PATCH 44/98] Update README.md [skip ci] --- core-java-modules/core-java-string-conversions-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-conversions-3/README.md b/core-java-modules/core-java-string-conversions-3/README.md index 2a2fcca1fe..96799d1660 100644 --- a/core-java-modules/core-java-string-conversions-3/README.md +++ b/core-java-modules/core-java-string-conversions-3/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Object.toString() vs String.valueOf()](https://www.baeldung.com/java-object-tostring-vs-string-valueof) +- [Convert String to Int Using Encapsulation](https://www.baeldung.com/java-encapsulation-convert-string-to-int) From c12c8c1ceb81866bcce0355c3b6bc25c823a2f69 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 10:28:23 +0800 Subject: [PATCH 45/98] Update README.md [skip ci] --- gradle-modules/gradle-7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/gradle-modules/gradle-7/README.md b/gradle-modules/gradle-7/README.md index ef1e536229..d7b2054a4f 100644 --- a/gradle-modules/gradle-7/README.md +++ b/gradle-modules/gradle-7/README.md @@ -3,3 +3,4 @@ - [How to Configure Conditional Dependencies in Gradle](https://www.baeldung.com/gradle-conditional-dependencies) - [Working With Multiple Repositories in Gradle](https://www.baeldung.com/java-gradle-multiple-repositories) +- [Different Dependency Version Declarations in Gradle](https://www.baeldung.com/gradle-different-dependency-version-declarations) From cd3684d0b480c1849946cd05bdc992c14f2283ed Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 10:35:47 +0800 Subject: [PATCH 46/98] 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 a4ea869946..ab0b81138e 100644 --- a/core-java-modules/core-java-io-apis-2/README.md +++ b/core-java-modules/core-java-io-apis-2/README.md @@ -10,3 +10,4 @@ This module contains articles about core Java input/output(IO) APIs. - [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader) - [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line) - [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array) +- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces) From 7d85e9e8dc1da00a8255b38b717aed83269ccd67 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 10:43:38 +0800 Subject: [PATCH 47/98] 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 ab0b81138e..9bd55abac4 100644 --- a/core-java-modules/core-java-io-apis-2/README.md +++ b/core-java-modules/core-java-io-apis-2/README.md @@ -11,3 +11,4 @@ This module contains articles about core Java input/output(IO) APIs. - [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line) - [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array) - [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces) +- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file) From a7786e4990258e3d7044ae03d9c343ae3d808216 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 10:47:28 +0800 Subject: [PATCH 48/98] Update README.md [skip ci] --- gradle-modules/gradle-7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/gradle-modules/gradle-7/README.md b/gradle-modules/gradle-7/README.md index d7b2054a4f..6e29e3db30 100644 --- a/gradle-modules/gradle-7/README.md +++ b/gradle-modules/gradle-7/README.md @@ -4,3 +4,4 @@ - [How to Configure Conditional Dependencies in Gradle](https://www.baeldung.com/gradle-conditional-dependencies) - [Working With Multiple Repositories in Gradle](https://www.baeldung.com/java-gradle-multiple-repositories) - [Different Dependency Version Declarations in Gradle](https://www.baeldung.com/gradle-different-dependency-version-declarations) +- [Generating Javadoc With Gradle](https://www.baeldung.com/java-gradle-javadoc) From 620ee5ee40cd2855500088e5e2bc3b2eead85cd9 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 10:51:25 +0800 Subject: [PATCH 49/98] Create README.md [skip ci] --- spring-actuator/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 spring-actuator/README.md diff --git a/spring-actuator/README.md b/spring-actuator/README.md new file mode 100644 index 0000000000..bf6b4fb257 --- /dev/null +++ b/spring-actuator/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Spring Boot Actuator Without Spring Boot](https://www.baeldung.com/spring-boot-actuator-without-spring-boot) From 2b7abfca026e2b8fe85014e738de9ff1c1a8db79 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 26 May 2023 11:00:47 +0800 Subject: [PATCH 50/98] Update README.md [skip ci] --- core-java-modules/core-java-collections-list-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-list-5/README.md b/core-java-modules/core-java-collections-list-5/README.md index 4929ca4e4e..31688bc9b1 100644 --- a/core-java-modules/core-java-collections-list-5/README.md +++ b/core-java-modules/core-java-collections-list-5/README.md @@ -6,3 +6,4 @@ This module contains articles about the Java List collection - [Java List Interface](https://www.baeldung.com/java-list-interface) - [Finding All Duplicates in a List in Java](https://www.baeldung.com/java-list-find-duplicates) - [Moving Items Around in an Arraylist](https://www.baeldung.com/java-arraylist-move-items) +- [Check if a List Contains an Element From Another List in Java](https://www.baeldung.com/java-check-elements-between-lists) From 1c9c15b203a4482e80b6f7c5a9af5143105d9067 Mon Sep 17 00:00:00 2001 From: Anastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com> Date: Fri, 26 May 2023 23:22:03 +0300 Subject: [PATCH 51/98] JAVA-20409 Uncommented spring-roo (#13949) * JAVA-20409 Uncommented spring-roo * JAVA-20409 Comment that roo is not supported * JAVA-21133 Updated comment for commented feign module --- pom.xml | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 764eccdac9..cedad1d59a 100644 --- a/pom.xml +++ b/pom.xml @@ -418,7 +418,12 @@ spring-cloud-modules - + + spring-exceptions + spring-integration + spring-jenkins-pipeline + + spring-security-modules spring-soap @@ -585,7 +590,12 @@ spring-cloud-modules - + + spring-exceptions + spring-integration + spring-jenkins-pipeline + + spring-security-modules spring-soap @@ -829,7 +839,7 @@ disruptor dozer dubbo - + google-cloud graphql-modules grpc @@ -1091,7 +1101,7 @@ dozer dubbo - + google-cloud graphql-modules grpc From cd86d338ff12e144a23c35896eb1ec312a6222b1 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Fri, 26 May 2023 23:51:17 +0300 Subject: [PATCH 52/98] JAVA-20163 Add instruction for running Morphia Test manually (#14128) Co-authored-by: timis1 --- ...MorphiaIntegrationTest.java => MorphiaManualTest.java} | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) rename persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/{MorphiaIntegrationTest.java => MorphiaManualTest.java} (92%) diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaManualTest.java similarity index 92% rename from persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java rename to persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaManualTest.java index d702c691d6..8e92945e10 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaManualTest.java @@ -31,7 +31,13 @@ import dev.morphia.query.FindOptions; import dev.morphia.query.Query; import dev.morphia.query.experimental.updates.UpdateOperators; -public class MorphiaIntegrationTest { +/** + * 1. Firstly you have to install a docker service where you can run a docker container. For Windows you can use Docker desktop (where you can have pretty + * much the seme functionality as on linux) + * 2. Secondly run a mongodb instance: with this command: docker run -d --rm -p 27017:27017 --name mongo2 mongo:5 + * 3. Thirdly run this test + */ +public class MorphiaManualTest { private static Datastore datastore; private static ObjectId id = new ObjectId(); From 498cc8aa98706736090fba456a86bfd8f1702877 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 27 May 2023 02:21:32 +0530 Subject: [PATCH 53/98] Revert "JAVA-19670: changes made for upgrading jenkins module to jdk-9 above (#14105)" (#14127) This reverts commit 2ef1a51767716650c0d5d1cab4ecec9ad53cb6ef. --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index cedad1d59a..9cd8f4722f 100644 --- a/pom.xml +++ b/pom.xml @@ -478,6 +478,7 @@ image-processing + jenkins-modules jhipster-modules @@ -642,6 +643,7 @@ image-processing + jenkins-modules jhipster-modules @@ -934,7 +936,6 @@ vaadin libraries-3 web-modules - jenkins-modules xml xml-2 @@ -1196,7 +1197,6 @@ vaadin libraries-3 web-modules - jenkins-modules xml xml-2 From fc41d4b12a52a6b139458dda31a9206ca8cb4ae0 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 14:35:34 +0530 Subject: [PATCH 54/98] added backlink --- persistence-modules/spring-data-jpa-repo/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index 43097a8c1e..c666f41f5b 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -10,6 +10,7 @@ This module contains articles about repositories in Spring Data JPA - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) - [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) - [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) +- [SAML with Spring Boot and Spring Security](https://www.baeldung.com/spring-security-saml) - More articles: [[--> next]](../spring-data-jpa-repo-2) ### Eclipse Config From 0f2bf326820150b89820b2af701a84cc5524a83e Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 14:38:11 +0530 Subject: [PATCH 55/98] added backlink --- persistence-modules/spring-data-jpa-repo/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index c666f41f5b..fc0288793c 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -11,6 +11,7 @@ This module contains articles about repositories in Spring Data JPA - [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) - [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) - [SAML with Spring Boot and Spring Security](https://www.baeldung.com/spring-security-saml) +- [TRUNCATE TABLE in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-truncate-table) - More articles: [[--> next]](../spring-data-jpa-repo-2) ### Eclipse Config From e276aa621226112e5f84661373904dbaf27de52a Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 14:41:40 +0530 Subject: [PATCH 56/98] added --- patterns-modules/idd/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/patterns-modules/idd/README.md b/patterns-modules/idd/README.md index 7d843af9ea..22fe277f0b 100644 --- a/patterns-modules/idd/README.md +++ b/patterns-modules/idd/README.md @@ -1 +1,2 @@ ### Relevant Articles: +- [Introduction to Interface Driven Development (IDD)](https://www.baeldung.com/java-idd) From ad43ae8005e9cf9f7c7034ce3ec6bb2911ecb457 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 14:42:28 +0530 Subject: [PATCH 57/98] backlink added --- patterns-modules/idd/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/patterns-modules/idd/README.md b/patterns-modules/idd/README.md index 22fe277f0b..78986f1724 100644 --- a/patterns-modules/idd/README.md +++ b/patterns-modules/idd/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: -- [Introduction to Interface Driven Development (IDD)](https://www.baeldung.com/java-idd) +-[Introduction to Interface Driven Development (IDD)](https://www.baeldung.com/java-idd) From 05c2b6f2f2736b0c56aaa62926987b952bd8f760 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 14:43:17 +0530 Subject: [PATCH 58/98] added backlink --- patterns-modules/idd/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/patterns-modules/idd/README.md b/patterns-modules/idd/README.md index 78986f1724..22fe277f0b 100644 --- a/patterns-modules/idd/README.md +++ b/patterns-modules/idd/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: --[Introduction to Interface Driven Development (IDD)](https://www.baeldung.com/java-idd) +- [Introduction to Interface Driven Development (IDD)](https://www.baeldung.com/java-idd) From 7ec425625f1ba343f9f697b12508a083fbb9dedd Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 14:47:34 +0530 Subject: [PATCH 59/98] updated title --- axon/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/axon/README.md b/axon/README.md index 9aeef05dd6..459a264502 100644 --- a/axon/README.md +++ b/axon/README.md @@ -21,4 +21,4 @@ Two scripts are included to easily start middleware using Docker matching the pr - [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates) - [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching) - [Persisting the Query Model](https://www.baeldung.com/persisting-the-query-model) -- [Using and testing Axon applications via REST](https://www.baeldung.com/using-and-testing-axon-applications-via-rest) +- [Using and Testing Axon Applications via REST](https://www.baeldung.com/using-and-testing-axon-applications-via-rest) From a01853ce5921348aa4fbc96d62592bd4f27413f3 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 14:49:34 +0530 Subject: [PATCH 60/98] added backlink --- jenkins-modules/jenkins-jobs/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jenkins-modules/jenkins-jobs/README.md b/jenkins-modules/jenkins-jobs/README.md index e6de0d57e0..091b944166 100644 --- a/jenkins-modules/jenkins-jobs/README.md +++ b/jenkins-modules/jenkins-jobs/README.md @@ -5,3 +5,4 @@ - [How to Stop a Zombie Job on Jenkins Without Restarting the Server?](https://www.baeldung.com/ops/stop-zombie-job-on-jenkins-without-restarting-the-server) - [Running Stages in Parallel With Jenkins Workflow / Pipeline](https://www.baeldung.com/ops/running-stages-in-parallel-jenkins-workflow-pipeline) - [Skip a Stage in a Jenkins Pipeline](https://www.baeldung.com/ops/jenkins-pipeline-skip-stage) +- [Prevent Jenkins Build From Failing When Execute Shell Step Fails](https://www.baeldung.com/linux/jenkins-build-execute-shell-step-fails) From 932f63d2b14ebee319c3ae745fc20b97ece04df8 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 14:55:17 +0530 Subject: [PATCH 61/98] updated link --- axon/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/axon/README.md b/axon/README.md index 459a264502..28b559b9ea 100644 --- a/axon/README.md +++ b/axon/README.md @@ -20,5 +20,5 @@ Two scripts are included to easily start middleware using Docker matching the pr - [Multi-Entity Aggregates in Axon](https://www.baeldung.com/java-axon-multi-entity-aggregates) - [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates) - [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching) -- [Persisting the Query Model](https://www.baeldung.com/persisting-the-query-model) +- [Persisting the Query Model](https://www.baeldung.com/axon-persisting-query-model) - [Using and Testing Axon Applications via REST](https://www.baeldung.com/using-and-testing-axon-applications-via-rest) From 20d8fe1ff73e8ffb1f38d8342afc524d8a01d832 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:00:11 +0530 Subject: [PATCH 62/98] updated link --- spring-security-modules/spring-security-saml/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-modules/spring-security-saml/README.md b/spring-security-modules/spring-security-saml/README.md index b6a11ed91b..213b56fb8c 100644 --- a/spring-security-modules/spring-security-saml/README.md +++ b/spring-security-modules/spring-security-saml/README.md @@ -1,4 +1,4 @@ ### Relevant Articles: -- [A Guide to SAML with Spring Security](https://www.baeldung.com/spring-security-saml) +- [A Guide to SAML with Spring Security](https://www.baeldung.com/spring-security-saml-legacy) - [SAML with Spring Boot and Spring Security](https://www.baeldung.com/spring-security-saml) From 2e6778c72238bf79edf55669c7b0ed244bae04f0 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:03:04 +0530 Subject: [PATCH 63/98] added backlink --- jhipster-modules/jhipster-microservice/car-app/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jhipster-modules/jhipster-microservice/car-app/README.md b/jhipster-modules/jhipster-microservice/car-app/README.md index 7dcbb23bb1..686df825fe 100644 --- a/jhipster-modules/jhipster-microservice/car-app/README.md +++ b/jhipster-modules/jhipster-microservice/car-app/README.md @@ -73,3 +73,5 @@ To configure CI for your project, run the ci-cd sub-generator (`yo jhipster:ci-c [Setting up Continuous Integration]: https://jhipster.github.io/documentation-archive/v4.0.8/setting-up-ci/ +## Relevant Articles: +[Use Liquibase to Safely Evolve Your Database Schema](https://www.baeldung.com/liquibase-refactor-schema-of-java-app) From 519d886deb3940947a10d621baa16d4959330a1d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:04:18 +0530 Subject: [PATCH 64/98] added backlink --- jhipster-modules/jhipster-microservice/car-app/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jhipster-modules/jhipster-microservice/car-app/README.md b/jhipster-modules/jhipster-microservice/car-app/README.md index 686df825fe..706e242469 100644 --- a/jhipster-modules/jhipster-microservice/car-app/README.md +++ b/jhipster-modules/jhipster-microservice/car-app/README.md @@ -74,4 +74,4 @@ To configure CI for your project, run the ci-cd sub-generator (`yo jhipster:ci-c ## Relevant Articles: -[Use Liquibase to Safely Evolve Your Database Schema](https://www.baeldung.com/liquibase-refactor-schema-of-java-app) +- [Use Liquibase to Safely Evolve Your Database Schema](https://www.baeldung.com/liquibase-refactor-schema-of-java-app) From deda69da7b6c5e386d76cc21d1f63f0199f71c6f Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:16:58 +0530 Subject: [PATCH 65/98] updated backlink --- core-java-modules/core-java-numbers-6/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-numbers-6/README.md b/core-java-modules/core-java-numbers-6/README.md index 97e4e2ca28..959d434935 100644 --- a/core-java-modules/core-java-numbers-6/README.md +++ b/core-java-modules/core-java-numbers-6/README.md @@ -1,4 +1,4 @@ ### Relevant Articles: -- [Java Program to Calculate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi) +- [Java Program to Estimate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi) - [Convert Integer to Hexadecimal in Java](https://www.baeldung.com/java-convert-int-to-hex) - More articles: [[<-- prev]](../core-java-numbers-5) From 8e9f2e39efdcb6158491163786d54e8e6c533178 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:20:01 +0530 Subject: [PATCH 66/98] updated backlink --- spring-web-modules/spring-resttemplate-3/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-resttemplate-3/README.md b/spring-web-modules/spring-resttemplate-3/README.md index 1944221138..f3cfb1d671 100644 --- a/spring-web-modules/spring-resttemplate-3/README.md +++ b/spring-web-modules/spring-resttemplate-3/README.md @@ -11,4 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file) - [Access HTTPS REST Service Using Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-secure-https-service) - [Encoding of URI Variables on RestTemplate](https://www.baeldung.com/spring-resttemplate-uri-variables-encode) -- [Difference Between exchange(), postForEntity() and execute() in RestTemplate](https://www.baeldung.com/spring-resttemplate-exchange-postforentity-execute) +- [Difference Between exchange(), postForEntity(), and execute() in RestTemplate](https://www.baeldung.com/spring-resttemplate-exchange-postforentity-execute) From f5cd3dcdba2d55f1be19087a45732d615fa3327d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:28:39 +0530 Subject: [PATCH 67/98] backlink updated --- core-java-modules/core-java-numbers-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-numbers-5/README.md b/core-java-modules/core-java-numbers-5/README.md index fcc3d55dd9..1a8d0abf34 100644 --- a/core-java-modules/core-java-numbers-5/README.md +++ b/core-java-modules/core-java-numbers-5/README.md @@ -7,5 +7,5 @@ - [Make Division of Two Integers Result in a Float](https://www.baeldung.com/java-integer-division-float-result) - [Creating Random Numbers With No Duplicates in Java](https://www.baeldung.com/java-unique-random-numbers) - [Multiply a BigDecimal by an Integer in Java](https://www.baeldung.com/java-bigdecimal-multiply-integer) -- [Check if an Integer Value is null or Zero in Java](https://www.baeldung.com/java-check-integer-null-or-zero) +- [Check if an Integer Value Is Null or Zero in Java](https://www.baeldung.com/java-check-integer-null-or-zero) - [Return Absolute Difference of Two Integers in Java](https://www.baeldung.com/java-absolute-difference-of-two-integers) From 004c5ad41f2bbd0808cb5687fd018c5cfcd8d3dc Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:30:38 +0530 Subject: [PATCH 68/98] backlink updated --- spring-kafka-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka-2/README.md b/spring-kafka-2/README.md index 60d7d8b607..ea2af99e35 100644 --- a/spring-kafka-2/README.md +++ b/spring-kafka-2/README.md @@ -4,5 +4,5 @@ This module contains articles about Spring with Kafka ### Relevant articles -- [Implementing Retry In Kafka Consumer](https://www.baeldung.com/spring-retry-kafka-consumer) +- [Implementing Retry in Kafka Consumer](https://www.baeldung.com/spring-retry-kafka-consumer) - [Spring Kafka: Configure Multiple Listeners on Same Topic](https://www.baeldung.com/spring-kafka-multiple-listeners-same-topic) From 31e63d3ab511cb5a31bcddaf92bfa5429a447dec Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:41:27 +0530 Subject: [PATCH 69/98] backlink added --- spring-boot-modules/spring-boot-properties-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-properties-3/README.md b/spring-boot-modules/spring-boot-properties-3/README.md index 4bc4a2325f..cb09a0ab81 100644 --- a/spring-boot-modules/spring-boot-properties-3/README.md +++ b/spring-boot-modules/spring-boot-properties-3/README.md @@ -12,4 +12,5 @@ - [Log Properties in a Spring Boot Application](https://www.baeldung.com/spring-boot-log-properties) - [Using Environment Variables in Spring Boot’s application.properties](https://www.baeldung.com/spring-boot-properties-env-variables) - [Loading Multiple YAML Configuration Files in Spring Boot](https://www.baeldung.com/spring-boot-load-multiple-yaml-configuration-files) +- [Using Environment Variables in Spring Boot’s Properties Files](https://www.baeldung.com/spring-boot-properties-env-variables) - More articles: [[<-- prev]](../spring-boot-properties-2) From 3d013aa16d321f38e84f8442c06772f90da87f13 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:43:10 +0530 Subject: [PATCH 70/98] backlink updated --- spring-boot-modules/spring-boot-libraries-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-libraries-2/README.md b/spring-boot-modules/spring-boot-libraries-2/README.md index 5c6b93469d..29693c3e15 100644 --- a/spring-boot-modules/spring-boot-libraries-2/README.md +++ b/spring-boot-modules/spring-boot-libraries-2/README.md @@ -7,7 +7,7 @@ This module contains articles about various Spring Boot libraries - [Background Jobs in Spring with JobRunr](https://www.baeldung.com/java-jobrunr-spring) - [Open API Server Implementation Using OpenAPI Generator](https://www.baeldung.com/java-openapi-generator-server) - [An Introduction to Kong](https://www.baeldung.com/kong) -- [Scanning Java Annotations At Runtime](https://www.baeldung.com/java-scan-annotations-runtime) +- [Scanning Java Annotations at Runtime](https://www.baeldung.com/java-scan-annotations-runtime) - [Guide to Resilience4j With Spring Boot](https://www.baeldung.com/spring-boot-resilience4j) - [Using OpenAI ChatGPT APIs in Spring Boot](https://www.baeldung.com/spring-boot-chatgpt-api-openai) - [Introduction to Spring Modulith](https://www.baeldung.com/spring-modulith) From 57ee0e82a89b0ade85290bb34bf13db87aaee61b Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 15:53:08 +0530 Subject: [PATCH 71/98] backlink updated --- xml-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xml-2/README.md b/xml-2/README.md index cfbd9d9911..383d0763d4 100644 --- a/xml-2/README.md +++ b/xml-2/README.md @@ -5,4 +5,4 @@ This module contains articles about eXtensible Markup Language (XML) ### Relevant Articles: - [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) +- [Validate an XML File Against an XSD File](https://www.baeldung.com/java-validate-xml-xsd) From 60c9ad3923d39086ede01b99d776943a334fe83b Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:07:03 +0530 Subject: [PATCH 72/98] backlink updated --- core-java-modules/core-java-string-operations-4/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-operations-4/README.md b/core-java-modules/core-java-string-operations-4/README.md index d420edff52..a3106e157b 100644 --- a/core-java-modules/core-java-string-operations-4/README.md +++ b/core-java-modules/core-java-string-operations-4/README.md @@ -6,7 +6,7 @@ - [Split a String Every n Characters in Java](https://www.baeldung.com/java-string-split-every-n-characters) - [String equals() Vs contentEquals() in Java](https://www.baeldung.com/java-string-equals-vs-contentequals) - [Check if a String Ends with a Certain Pattern in Java](https://www.baeldung.com/java-string-ends-pattern) -- [Check if a Character is a Vowel in Java](https://www.baeldung.com/java-check-character-vowel) +- [Check if a Character Is a Vowel in Java](https://www.baeldung.com/java-check-character-vowel) - [How to Truncate a String in Java](https://www.baeldung.com/java-truncating-strings) - [Remove Whitespace From a String in Java](https://www.baeldung.com/java-string-remove-whitespace) - [Named Placeholders in String Formatting](https://www.baeldung.com/java-string-formatting-named-placeholders) From b43539194388147a1e18eb2d1fa051ab289c3fc2 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:09:46 +0530 Subject: [PATCH 73/98] backlink updated --- core-java-modules/core-java-nio-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-nio-2/README.md b/core-java-modules/core-java-nio-2/README.md index 527600779a..4c5f5a2c16 100644 --- a/core-java-modules/core-java-nio-2/README.md +++ b/core-java-modules/core-java-nio-2/README.md @@ -13,5 +13,5 @@ This module contains articles about core Java non-blocking input and output (IO) - [Java – Path vs File](https://www.baeldung.com/java-path-vs-file) - [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2) - [Guide to ByteBuffer](https://www.baeldung.com/java-bytebuffer) -- [Find Files that Match Wildcard Strings in Java](https://www.baeldung.com/java-files-match-wildcard-strings) +- [Find Files That Match Wildcard Strings in Java](https://www.baeldung.com/java-files-match-wildcard-strings) - [[<-- Prev]](/core-java-modules/core-java-nio) From badc1e342cae24612add102691feb185d7703d07 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:11:33 +0530 Subject: [PATCH 74/98] backlink updated --- json-modules/json-2/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/json-modules/json-2/README.md b/json-modules/json-2/README.md index 750bb064c8..bf2cb06aba 100644 --- a/json-modules/json-2/README.md +++ b/json-modules/json-2/README.md @@ -9,8 +9,7 @@ This module contains articles about JSON. - [Hypermedia Serialization With JSON-LD](https://www.baeldung.com/json-linked-data) - [Generate a Java Class From JSON](https://www.baeldung.com/java-generate-class-from-json) - [A Guide to FastJson](https://www.baeldung.com/fastjson) -- [Check Whether a String is Valid JSON in Java](https://www.baeldung.com/java-validate-json-string) +- [Check Whether a String Is Valid JSON in Java](https://www.baeldung.com/java-validate-json-string) - [Getting a Value in JSONObject](https://www.baeldung.com/java-jsonobject-get-value) - - More Articles: [[<-- prev]](/json-modules/json) From 9aad77c8f7b1cec90921c4e4517429617eeb0860 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:17:36 +0530 Subject: [PATCH 75/98] backlink updated --- core-java-modules/core-java-io-4/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-io-4/README.md b/core-java-modules/core-java-io-4/README.md index 738cbb5895..7856fbaf41 100644 --- a/core-java-modules/core-java-io-4/README.md +++ b/core-java-modules/core-java-io-4/README.md @@ -8,7 +8,7 @@ This module contains articles about core Java input and output (IO) - [Simulate touch Command in Java](https://www.baeldung.com/java-simulate-touch-command) - [SequenceInputStream Class in Java](https://www.baeldung.com/java-sequenceinputstream) - [Read a File Into a Map in Java](https://www.baeldung.com/java-read-file-into-map) -- [Read User Input Until a Condition is Met](https://www.baeldung.com/java-read-input-until-condition) +- [Read User Input Until a Condition Is Met](https://www.baeldung.com/java-read-input-until-condition) - [Java Scanner.skip method with examples](https://www.baeldung.com/java-scanner-skip) - [Generate the MD5 Checksum for a File in Java](https://www.baeldung.com/java-md5-checksum-file) - [Getting the Filename From a String Containing an Absolute File Path](https://www.baeldung.com/java-filename-full-path) From 65f892919d6d457c9a4b38ad0c5dbb59c628a6ab Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:22:54 +0530 Subject: [PATCH 76/98] backlink updated --- persistence-modules/fauna/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/fauna/README.md b/persistence-modules/fauna/README.md index 245c2a613b..a442caab6e 100644 --- a/persistence-modules/fauna/README.md +++ b/persistence-modules/fauna/README.md @@ -1,4 +1,4 @@ ### Relevant Articles: -- [Building a web app Using Fauna and Spring for Your First web Agency Client](https://www.baeldung.com/faunadb-spring-web-app) +- [Building a Web App Using Fauna and Spring for Your First Web Agency Client](https://www.baeldung.com/faunadb-spring-web-app) - [Building IoT Applications Using Fauna and Spring](https://www.baeldung.com/fauna-spring-building-iot-applications) From bd37791f566109ee646b1e0989cccbc4ca385b93 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:39:31 +0530 Subject: [PATCH 77/98] backlink updated --- testing-modules/testing-assertions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/testing-assertions/README.md b/testing-modules/testing-assertions/README.md index 2349834fa3..55a39ec606 100644 --- a/testing-modules/testing-assertions/README.md +++ b/testing-modules/testing-assertions/README.md @@ -3,4 +3,4 @@ - [Asserting Log Messages With JUnit](https://www.baeldung.com/junit-asserting-logs) - [Assert Two Lists for Equality Ignoring Order in Java](https://www.baeldung.com/java-assert-lists-equality-ignore-order) - [Assert That a Java Optional Has a Certain Value](https://www.baeldung.com/java-optional-assert-value) -- [Assert that an Object is from a Specific Type](https://www.baeldung.com/java-assert-object-of-type) +- [Assert That an Object Is From a Specific Type](https://www.baeldung.com/java-assert-object-of-type) From 32b277b9f5b034b84d406159770e0a7023771620 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:45:37 +0530 Subject: [PATCH 78/98] backlink updated --- core-java-modules/core-java-string-algorithms-3/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-algorithms-3/README.md b/core-java-modules/core-java-string-algorithms-3/README.md index c9e7e7d7d4..bc6b6f2167 100644 --- a/core-java-modules/core-java-string-algorithms-3/README.md +++ b/core-java-modules/core-java-string-algorithms-3/README.md @@ -7,7 +7,7 @@ This module contains articles about string-related algorithms. - [Generating a Java String of N Repeated Characters](https://www.baeldung.com/java-string-of-repeated-characters) - [Check if Two Strings are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams) - [Email Validation in Java](https://www.baeldung.com/java-email-validation-regex) -- [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase) +- [Check if the First Letter of a String Is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase) - [Find the First Non Repeating Character in a String in Java](https://www.baeldung.com/java-find-the-first-non-repeating-character) - [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer) - [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters) From ec9350d9d3865580dbc1ec9119fca13cca1a323a Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:47:38 +0530 Subject: [PATCH 79/98] backlink updated --- spring-web-modules/spring-mvc-basics-4/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-mvc-basics-4/README.md b/spring-web-modules/spring-mvc-basics-4/README.md index d4578f6ca4..5681c2292c 100644 --- a/spring-web-modules/spring-mvc-basics-4/README.md +++ b/spring-web-modules/spring-mvc-basics-4/README.md @@ -9,6 +9,6 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring - [Spring Web Contexts](https://www.baeldung.com/spring-web-contexts) - [Spring Optional Path Variables](https://www.baeldung.com/spring-optional-path-variables) - [JSON Parameters with Spring MVC](https://www.baeldung.com/spring-mvc-send-json-parameters) -- [How to Set JSON Content Type In Spring MVC](https://www.baeldung.com/spring-mvc-set-json-content-type) +- [How to Set JSON Content Type in Spring MVC](https://www.baeldung.com/spring-mvc-set-json-content-type) - [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller) - More articles: [[<-- prev]](../spring-mvc-basics-3)[[next -->]](../spring-mvc-basics-5) From 7adf1c1900ae894be2eeb180ea3834d19e4f275f Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:48:50 +0530 Subject: [PATCH 80/98] backlink updated --- data-structures/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data-structures/README.md b/data-structures/README.md index cfcfbc6a0a..4a01edbb06 100644 --- a/data-structures/README.md +++ b/data-structures/README.md @@ -12,5 +12,5 @@ This module contains articles about data structures in Java - [Guide to AVL Trees in Java](https://www.baeldung.com/java-avl-trees) - [Graphs in Java](https://www.baeldung.com/java-graphs) - [Implementing a Ring Buffer in Java](https://www.baeldung.com/java-ring-buffer) -- [How to Implement Min-Max Heap In Java](https://www.baeldung.com/java-min-max-heap) +- [How to Implement Min-Max Heap in Java](https://staging8.baeldung.com/java-min-max-heap) - [How to Implement LRU Cache in Java](https://www.baeldung.com/java-lru-cache) From 01f7087847597a6ffa750edf5cf0987f3bea31c3 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:54:13 +0530 Subject: [PATCH 81/98] backlink updated --- data-structures/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data-structures/README.md b/data-structures/README.md index 4a01edbb06..764a854516 100644 --- a/data-structures/README.md +++ b/data-structures/README.md @@ -12,5 +12,5 @@ This module contains articles about data structures in Java - [Guide to AVL Trees in Java](https://www.baeldung.com/java-avl-trees) - [Graphs in Java](https://www.baeldung.com/java-graphs) - [Implementing a Ring Buffer in Java](https://www.baeldung.com/java-ring-buffer) -- [How to Implement Min-Max Heap in Java](https://staging8.baeldung.com/java-min-max-heap) +- [How to Implement Min-Max Heap in Java](https://www.baeldung.com/java-min-max-heap) - [How to Implement LRU Cache in Java](https://www.baeldung.com/java-lru-cache) From 866eb0a47cc37a7e564b4355869a4e2f0eb8a30b Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:56:07 +0530 Subject: [PATCH 82/98] backlink updated --- image-processing/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/image-processing/README.md b/image-processing/README.md index 12b061bf41..075dc61484 100644 --- a/image-processing/README.md +++ b/image-processing/README.md @@ -8,4 +8,4 @@ This module contains articles about image processing. - [Optical Character Recognition with Tesseract](https://www.baeldung.com/java-ocr-tesseract) - [How Can I Resize an Image Using Java?](https://www.baeldung.com/java-resize-image) - [Adding Text to an Image in Java](https://www.baeldung.com/java-add-text-to-image) -- [Capturing Image From Webcam In Java](https://www.baeldung.com/java-capture-image-from-webcam) +- [Capturing Image From Webcam in Java](https://www.baeldung.com/java-capture-image-from-webcam) From 46ec18e86a8a53e32307e32601f93c9df9c6c9fe Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:57:24 +0530 Subject: [PATCH 83/98] backlink updated --- persistence-modules/java-jpa-3/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-jpa-3/README.md b/persistence-modules/java-jpa-3/README.md index aa33644b17..1cf7055413 100644 --- a/persistence-modules/java-jpa-3/README.md +++ b/persistence-modules/java-jpa-3/README.md @@ -11,6 +11,6 @@ This module contains articles about the Java Persistence API (JPA) in Java. - [A Guide to MultipleBagFetchException in Hibernate](https://www.baeldung.com/java-hibernate-multiplebagfetchexception) - [How to Convert a Hibernate Proxy to a Real Entity Object](https://www.baeldung.com/hibernate-proxy-to-real-entity-object) - [Returning an Auto-Generated Id with JPA](https://www.baeldung.com/jpa-get-auto-generated-id) -- [How to Return Multiple Entities In JPA Query](https://www.baeldung.com/jpa-return-multiple-entities) +- [How to Return Multiple Entities in JPA Query](https://www.baeldung.com/jpa-return-multiple-entities) - [Defining Unique Constraints in JPA](https://www.baeldung.com/jpa-unique-constraints) - [Connecting to a Specific Schema in JDBC](https://www.baeldung.com/jdbc-connect-to-schema) From e3805a44cb7e93ad38e704c1467b474b14f0452d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 16:59:40 +0530 Subject: [PATCH 84/98] backlink updated --- core-java-modules/core-java-lang-4/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-lang-4/README.md b/core-java-modules/core-java-lang-4/README.md index befef0b6eb..7bdbaff295 100644 --- a/core-java-modules/core-java-lang-4/README.md +++ b/core-java-modules/core-java-lang-4/README.md @@ -4,7 +4,7 @@ This module contains articles about core features in the Java language - [The Java final Keyword – Impact on Performance](https://www.baeldung.com/java-final-performance) - [The package-info.java File](https://www.baeldung.com/java-package-info) -- [What are Compile-time Constants in Java?](https://www.baeldung.com/java-compile-time-constants) +- [What Are Compile-Time Constants in Java?](https://www.baeldung.com/java-compile-time-constants) - [Java Objects.hash() vs Objects.hashCode()](https://www.baeldung.com/java-objects-hash-vs-objects-hashcode) - [Referencing a Method in Javadoc Comments](https://www.baeldung.com/java-method-in-javadoc) - [Tiered Compilation in JVM](https://www.baeldung.com/jvm-tiered-compilation) From 2260ff6e454f7b54277f4658533ae4dc351d9f3c Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 17:01:25 +0530 Subject: [PATCH 85/98] backlink updated --- persistence-modules/core-java-persistence-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/core-java-persistence-2/README.md b/persistence-modules/core-java-persistence-2/README.md index 56cb2fb1d0..afabf9ecb3 100644 --- a/persistence-modules/core-java-persistence-2/README.md +++ b/persistence-modules/core-java-persistence-2/README.md @@ -1,7 +1,7 @@ ### Relevant Articles: - [Getting Database URL From JDBC Connection Object](https://www.baeldung.com/jdbc-get-url-from-connection) -- [JDBC URL Format For Different Databases](https://www.baeldung.com/java-jdbc-url-format) +- [Jdbc URL Format for Different Databases](https://www.baeldung.com/java-jdbc-url-format) - [How to Check if a Database Table Exists with JDBC](https://www.baeldung.com/jdbc-check-table-exists) - [Inserting Null Into an Integer Column Using JDBC](https://www.baeldung.com/jdbc-insert-null-into-integer-column) - [A Guide to Auto-Commit in JDBC](https://www.baeldung.com/java-jdbc-auto-commit) From 47ae1bdc3598674e9f3c6e87c6a7b4a7f7e3e6ca Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 17:06:19 +0530 Subject: [PATCH 86/98] backlink updated --- core-java-modules/core-java-reflection-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-reflection-2/README.md b/core-java-modules/core-java-reflection-2/README.md index 8613845d4f..48f49eb173 100644 --- a/core-java-modules/core-java-reflection-2/README.md +++ b/core-java-modules/core-java-reflection-2/README.md @@ -3,7 +3,7 @@ - [Reading the Value of ‘private’ Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value) - [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value) - [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static) -- [Checking if a Java Class is ‘abstract’ Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract) +- [Checking if a Java Class Is ‘Abstract’ Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract) - [Invoking a Private Method in Java](https://www.baeldung.com/java-call-private-method) - [Finding All Classes in a Java Package](https://www.baeldung.com/java-find-all-classes-in-package) - [Invoke a Static Method Using Java Reflection API](https://www.baeldung.com/java-invoke-static-method-reflection) From a4ef6abdff492de900f5f08ec36de6cc9726fd96 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 17:12:28 +0530 Subject: [PATCH 87/98] backlink updated --- core-java-modules/core-java-reflection-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-reflection-2/README.md b/core-java-modules/core-java-reflection-2/README.md index 48f49eb173..4918b1fe98 100644 --- a/core-java-modules/core-java-reflection-2/README.md +++ b/core-java-modules/core-java-reflection-2/README.md @@ -2,7 +2,7 @@ - [Reading the Value of ‘private’ Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value) - [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value) -- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static) +- [Checking if a Method Is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static) - [Checking if a Java Class Is ‘Abstract’ Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract) - [Invoking a Private Method in Java](https://www.baeldung.com/java-call-private-method) - [Finding All Classes in a Java Package](https://www.baeldung.com/java-find-all-classes-in-package) From 71bc8122b7e48c3b97485941feee2acf7bf9344b Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 27 May 2023 17:16:00 +0530 Subject: [PATCH 88/98] backlink updated --- core-java-modules/core-java-lang-oop-types/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-lang-oop-types/README.md b/core-java-modules/core-java-lang-oop-types/README.md index 4ebbf501ec..7978cb7730 100644 --- a/core-java-modules/core-java-lang-oop-types/README.md +++ b/core-java-modules/core-java-lang-oop-types/README.md @@ -11,6 +11,6 @@ This module contains articles about types in Java - [Iterating over Enum Values in Java](https://www.baeldung.com/java-enum-iteration) - [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values) - [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums) -- [Determine if an Object is of Primitive Type](https://www.baeldung.com/java-object-primitive-type) +- [Determine if an Object Is of Primitive Type](https://www.baeldung.com/java-object-primitive-type) - [Extending Enums in Java](https://www.baeldung.com/java-extending-enums) - [Java Class File Naming Conventions](https://www.baeldung.com/java-class-file-naming) From 668b8f0b77038841c21145ae5359b7fff544aa72 Mon Sep 17 00:00:00 2001 From: Tapan Avasthi Date: Sat, 27 May 2023 19:14:01 +0530 Subject: [PATCH 89/98] BAEL-6293: Add builder pattern for ObjectMapper creation (#14112) Co-authored-by: Tapan Avasthi --- .../objectmapper/ObjectMapperBuilder.java | 45 +++++++++++++++++++ .../ObjectMapperBuilderUnitTest.java | 44 ++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 jackson-simple/src/main/java/com/baeldung/jackson/objectmapper/ObjectMapperBuilder.java create mode 100644 jackson-simple/src/test/java/com/baeldung/jackson/objectmapper/ObjectMapperBuilderUnitTest.java diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/objectmapper/ObjectMapperBuilder.java b/jackson-simple/src/main/java/com/baeldung/jackson/objectmapper/ObjectMapperBuilder.java new file mode 100644 index 0000000000..0810d68da5 --- /dev/null +++ b/jackson-simple/src/main/java/com/baeldung/jackson/objectmapper/ObjectMapperBuilder.java @@ -0,0 +1,45 @@ +package com.baeldung.jackson.objectmapper; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.ZoneId; +import java.util.TimeZone; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +public class ObjectMapperBuilder { + private boolean enableIndentation; + private boolean preserveOrder; + private DateFormat dateFormat; + + public ObjectMapperBuilder enableIndentation() { + this.enableIndentation = true; + return this; + } + + public ObjectMapperBuilder dateFormat() { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm a z"); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("Asia/Kolkata"))); + this.dateFormat = simpleDateFormat; + return this; + } + + public ObjectMapperBuilder preserveOrder(boolean order) { + this.preserveOrder = order; + return this; + } + + public ObjectMapper build() { + ObjectMapper objectMapper = new ObjectMapper(); + + objectMapper.configure(SerializationFeature.INDENT_OUTPUT, this.enableIndentation); + objectMapper.setDateFormat(this.dateFormat); + if (this.preserveOrder) { + objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + } + + return objectMapper; + } + +} \ No newline at end of file diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/objectmapper/ObjectMapperBuilderUnitTest.java b/jackson-simple/src/test/java/com/baeldung/jackson/objectmapper/ObjectMapperBuilderUnitTest.java new file mode 100644 index 0000000000..355e86798d --- /dev/null +++ b/jackson-simple/src/test/java/com/baeldung/jackson/objectmapper/ObjectMapperBuilderUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.jackson.objectmapper; + +import java.util.Date; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +import com.baeldung.jackson.objectmapper.dto.Car; +import com.baeldung.jackson.objectmapper.dto.Request; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ObjectMapperBuilderUnitTest { + + ObjectMapper mapper = new ObjectMapperBuilder() + .enableIndentation() + .dateFormat() + .preserveOrder(true) + .build(); + + Car givenCar = new Car("White", "Sedan"); + String givenCarJsonStr = "{ \"color\" : \"White\", \"type\" : \"Sedan\" }"; + + @Test + public void whenReadCarJsonStr_thenReturnCarObjectCorrectly() throws JsonProcessingException { + Car actual = mapper.readValue(givenCarJsonStr, Car.class); + Assertions.assertEquals("White", actual.getColor()); + Assertions.assertEquals("Sedan", actual.getType()); + } + + @Test + public void whenWriteRequestObject_thenReturnRequestJsonStrCorrectly() throws JsonProcessingException { + Request request = new Request(); + request.setCar(givenCar); + Date date = new Date(1684909857000L); + request.setDatePurchased(date); + + String actual = mapper.writeValueAsString(request); + String expected = "{\n" + " \"car\" : {\n" + " \"color\" : \"White\",\n" + + " \"type\" : \"Sedan\"\n" + " },\n" + " \"datePurchased\" : \"2023-05-24 12:00 PM IST\"\n" + + "}"; + Assertions.assertEquals(expected, actual); + } +} From d9027f6a1ba504f873eb3ee6656672a57c1dbb71 Mon Sep 17 00:00:00 2001 From: Abhinav Pandey Date: Sat, 27 May 2023 21:08:50 +0530 Subject: [PATCH 90/98] BAEL-6509 - JSON to XML conversion in Java (#14050) * BAEL-6509 - JSON to XML conversion * BAEL-6509 - CRLF to LF --- xml-2/pom.xml | 23 ++++++ .../xml/json2xml/JsonToXmlUnitTest.java | 77 +++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 xml-2/src/test/java/com/baeldung/xml/json2xml/JsonToXmlUnitTest.java diff --git a/xml-2/pom.xml b/xml-2/pom.xml index c4882b0a53..6b25d66b6a 100644 --- a/xml-2/pom.xml +++ b/xml-2/pom.xml @@ -26,6 +26,26 @@ ${junit-jupiter.version} test + + org.json + json + ${json.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson.version} + + + com.github.javadev + underscore + ${underscore.version} + @@ -51,6 +71,9 @@ 2.1.3 + 2.14.1 + 20230227 + 1.89 \ No newline at end of file diff --git a/xml-2/src/test/java/com/baeldung/xml/json2xml/JsonToXmlUnitTest.java b/xml-2/src/test/java/com/baeldung/xml/json2xml/JsonToXmlUnitTest.java new file mode 100644 index 0000000000..6c8486f14b --- /dev/null +++ b/xml-2/src/test/java/com/baeldung/xml/json2xml/JsonToXmlUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.xml.json2xml; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; +import com.github.underscore.U; +import org.json.JSONObject; +import org.json.XML; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class JsonToXmlUnitTest { + + @Test + public void givenJsonString_whenConvertToXMLUsingJsonJava_thenConverted() { + String jsonString = "{\"name\":\"John\", \"age\":20, \"address\":{\"street\":\"Wall Street\", \"city\":\"New York\"}}"; + JSONObject jsonObject = new JSONObject(jsonString); + String xmlString = XML.toString(jsonObject); + Assertions.assertEquals("

New YorkWall Street
John20", xmlString); + } + + @Test + public void givenJsonString_whenConvertToXMLUsingJackson_thenConverted() throws JsonProcessingException { + String jsonString = "{\"name\":\"John\", \"age\":20, \"address\":{\"street\":\"Wall Street\", \"city\":\"New York\"}}"; + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(jsonString); + String xmlString = new XmlMapper().writeValueAsString(jsonNode); + Assertions.assertEquals("John20
Wall StreetNew York
", xmlString); + } + + @Test + public void givenJsonString_whenConvertToXMLUsingJacksonWithXMLDeclarationAndRoot_thenConverted() throws JsonProcessingException { + String jsonString = "{\"name\":\"John\", \"age\":20, \"address\":{\"street\":\"Wall Street\", \"city\":\"New York\"}}"; + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(jsonString); + XmlMapper xmlMapper = new XmlMapper(); + xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true); + xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); + xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_1, true); + String xmlString = xmlMapper.writer().withRootName("root").withDefaultPrettyPrinter().writeValueAsString(jsonNode); + Assertions.assertEquals("\n" + + "\n" + + " John\n" + + " 20\n" + + "
\n" + + " Wall Street\n" + + " New York\n" + + "
\n" + + "
\n", xmlString); + } + + @Test + public void givenJsonString_whenConvertToXMLUsingUnderscoreJava_thenConverted() { + String jsonString = "{\"name\":\"John\", \"age\":20}"; + String xmlString = U.jsonToXml(jsonString); + Assertions.assertEquals("\n" + + "\n" + + " John\n" + + " 20\n" + + "", xmlString); + } + + @Test + public void givenJsonString_whenConvertToXMLUsingUnderscoreJavaWithoutAttributes_thenConverted() { + String jsonString = "{\"name\":\"John\", \"age\":20}"; + String xmlString = U.jsonToXml(jsonString, U.JsonToXmlMode.REMOVE_ATTRIBUTES); + Assertions.assertEquals("\n" + + "\n" + + " John\n" + + " 20\n" + + "", xmlString); + } +} + From 01e8fa41fddeabd892f7c52f46044d7a3bebda54 Mon Sep 17 00:00:00 2001 From: technoddy Date: Thu, 25 May 2023 23:40:16 -0400 Subject: [PATCH 91/98] Addressing PR feedback --- .../baeldung/countrows/entity/Account.java | 34 ++---------------- .../baeldung/countrows/entity/Permission.java | 21 ++--------- .../repository/AccountRepository.java | 1 + .../countrows/service/AccountStatsLogic.java | 35 ++++++++----------- .../AccountStatsUnitTest.java | 29 +++++++-------- 5 files changed, 34 insertions(+), 86 deletions(-) diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java index 11e4cb412e..d422c30a0e 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java @@ -8,10 +8,10 @@ import java.time.Instant; import java.util.Date; @Entity -@Table(name="ACCOUNTS") +@Table(name = "ACCOUNTS") public class Account { @Id - @GeneratedValue(strategy= GenerationType.SEQUENCE, generator = "accounts_seq") + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "accounts_seq") @SequenceGenerator(name = "accounts_seq", sequenceName = "accounts_seq", allocationSize = 1) @Column(name = "user_id") private int userId; @@ -25,14 +25,6 @@ public class Account { @JoinColumn(name = "permissions_id") private Permission permission; - public int getUserId() { - return userId; - } - - public void setUserId(int userId) { - this.userId = userId; - } - public String getUsername() { return username; } @@ -41,18 +33,10 @@ public class Account { this.username = username; } - public String getPassword() { - return password; - } - public void setPassword(String password) { this.password = password; } - public String getEmail() { - return email; - } - public void setEmail(String email) { this.email = email; } @@ -65,10 +49,6 @@ public class Account { this.createdOn = createdOn; } - public Timestamp getLastLogin() { - return lastLogin; - } - public void setLastLogin(Timestamp lastLogin) { this.lastLogin = lastLogin; } @@ -83,14 +63,6 @@ public class Account { @Override public String toString() { - return "Account{" + - "userId=" + userId + - ", username='" + username + '\'' + - ", password='" + password + '\'' + - ", email='" + email + '\'' + - ", createdOn=" + createdOn + - ", lastLogin=" + lastLogin + - ", permission=" + permission + - '}'; + return "Account{" + "userId=" + userId + ", username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + ", createdOn=" + createdOn + ", lastLogin=" + lastLogin + ", permission=" + permission + '}'; } } \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java index 17e8ab9c12..9acedf0558 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java @@ -3,37 +3,22 @@ package com.baeldung.countrows.entity; import javax.persistence.*; @Entity -@Table(name="PERMISSIONS") +@Table(name = "PERMISSIONS") public class Permission { @Id - @GeneratedValue(strategy= GenerationType.SEQUENCE, generator = "permissions_id_sq") + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "permissions_id_sq") @SequenceGenerator(name = "permissions_id_sq", sequenceName = "permissions_id_sq", allocationSize = 1) private int id; private String type; - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getType() { - return type; - } - public void setType(String type) { this.type = type; } @Override public String toString() { - return "Permission{" + - "id=" + id + - ", type='" + type + '\'' + - '}'; + return "Permission{" + "id=" + id + ", type='" + type + '\'' + '}'; } } diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java index 875a2e7160..422962ce45 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java @@ -2,6 +2,7 @@ package com.baeldung.countrows.repository; import com.baeldung.countrows.entity.Account; import com.baeldung.countrows.entity.Permission; + import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java index f8f8d5905e..e4e716b4ce 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java @@ -11,8 +11,10 @@ import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.criteria.*; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; + import com.baeldung.countrows.entity.Account; import com.baeldung.countrows.entity.Permission; import com.baeldung.countrows.repository.AccountRepository; @@ -29,19 +31,18 @@ public class AccountStatsLogic { @Autowired private PermissionRepository permissionRepository; - public long getAccountCount(){ + public long getAccountCount() { return accountRepository.count(); } - public long getAccountCountByUsername(String username){ + public long getAccountCountByUsername(String username) { return accountRepository.countByUsername(username); } - public long getAccountCountByPermission(Permission permission){ + public long getAccountCountByPermission(Permission permission) { return accountRepository.countByPermission(permission); } - public long getAccountCountByPermissionAndCreatedOn(Permission permission, Date date) throws ParseException { return accountRepository.countByPermissionAndCreatedOnGreaterThan(permission, new Timestamp(date.getTime())); } @@ -53,11 +54,11 @@ public class AccountStatsLogic { Root accountRoot = criteriaQuery.from(Account.class); // select query - criteriaQuery - .select(builder.count(accountRoot)); + criteriaQuery.select(builder.count(accountRoot)); // execute and get the result - return entityManager.createQuery(criteriaQuery).getSingleResult(); + return entityManager.createQuery(criteriaQuery) + .getSingleResult(); } public long getAccountsByPermissionUsingCQ(Permission permission) throws ParseException { @@ -68,11 +69,11 @@ public class AccountStatsLogic { List predicateList = new ArrayList<>(); // list of predicates that will go in where clause predicateList.add(builder.equal(accountRoot.get("permission"), permission)); - criteriaQuery - .select(builder.count(accountRoot)) + criteriaQuery.select(builder.count(accountRoot)) .where(builder.and(predicateList.toArray(new Predicate[0]))); - return entityManager.createQuery(criteriaQuery).getSingleResult(); + return entityManager.createQuery(criteriaQuery) + .getSingleResult(); } public long getAccountsByPermissionAndCreateOnUsingCQ(Permission permission, Date date) throws ParseException { @@ -87,12 +88,12 @@ public class AccountStatsLogic { predicateList.add(builder.greaterThan(accountRoot.get("createdOn"), new Timestamp(date.getTime()))); // select query - criteriaQuery - .select(builder.count(accountRoot)) + criteriaQuery.select(builder.count(accountRoot)) .where(builder.and(predicateList.toArray(new Predicate[0]))); // execute and get the result - return entityManager.createQuery(criteriaQuery).getSingleResult(); + return entityManager.createQuery(criteriaQuery) + .getSingleResult(); } public long getAccountsUsingJPQL() throws ParseException { @@ -112,12 +113,4 @@ public class AccountStatsLogic { query.setParameter(2, new Timestamp(date.getTime())); return (long) query.getSingleResult(); } - - private static Date getDate() throws ParseException { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date parsedDate = dateFormat.parse("2023-04-29"); - - System.out.println("parseDate: "+parsedDate); - return parsedDate; - } } \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java index 98269547c3..af825601aa 100644 --- a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java @@ -35,15 +35,15 @@ class AccountStatsUnitTest { private AccountStatsLogic accountStatsLogic; @AfterEach - public void afterEach(){ + public void afterEach() { accountRepository.deleteAll(); permissionRepository.deleteAll(); } @Test - public void givenAccountInTable_whenPerformCount_returnsAppropriateCount(){ + public void givenAccountInTable_whenPerformCount_returnsAppropriateCount() { savePermissions(); - Account account = saveAccount(); + saveAccount(); assertThat(accountStatsLogic.getAccountCount()).isEqualTo(1); } @@ -66,7 +66,7 @@ class AccountStatsUnitTest { @Test public void givenAccountInTable_whenPerformCountUsingCQ_returnsAppropriateCount() throws ParseException { savePermissions(); - Account account = saveAccount(); + saveAccount(); long count = accountStatsLogic.getAccountsUsingCQ(); assertThat(count).isEqualTo(1); } @@ -90,10 +90,11 @@ class AccountStatsUnitTest { @Test public void givenAccountInTable_whenPerformCountUsingJPQL_returnsAppropriateCount() throws ParseException { savePermissions(); - Account account = saveAccount(); + saveAccount(); long count = accountStatsLogic.getAccountsUsingJPQL(); assertThat(count).isEqualTo(1); } + @Test public void givenAccountInTable_whenPerformCountByPermissionUsingJPQL_returnsAppropriateCount() throws ParseException { savePermissions(); @@ -101,6 +102,7 @@ class AccountStatsUnitTest { long count = accountStatsLogic.getAccountsByPermissionUsingJPQL(account.getPermission()); assertThat(count).isEqualTo(1); } + @Test public void givenAccountInTable_whenPerformCountByPermissionAndCreatedOnUsingJPQL_returnsAppropriateCount() throws ParseException { savePermissions(); @@ -109,11 +111,11 @@ class AccountStatsUnitTest { assertThat(count).isEqualTo(1); } - private Account saveAccount(){ + private Account saveAccount() { return accountRepository.save(getAccount()); } - private void savePermissions(){ + private void savePermissions() { Permission editor = new Permission(); editor.setType("editor"); permissionRepository.save(editor); @@ -123,18 +125,13 @@ class AccountStatsUnitTest { permissionRepository.save(admin); } - private static Date getDate() throws ParseException { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date parsedDate = dateFormat.parse("2023-04-29"); - return parsedDate; - } - private Account getAccount() { Permission permission = permissionRepository.findByType("admin"); Account account = new Account(); - String seed = UUID.randomUUID().toString(); - account.setUsername("username_"+seed); - account.setEmail("username_"+seed+"@gmail.com"); + String seed = UUID.randomUUID() + .toString(); + account.setUsername("username_" + seed); + account.setEmail("username_" + seed + "@gmail.com"); account.setPermission(permission); account.setPassword("password_q1234"); account.setCreatedOn(Timestamp.from(Instant.now())); From 0238c2b94878c2ead6bc1bb74d30e523c85e3963 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Sun, 28 May 2023 11:06:59 +0200 Subject: [PATCH 92/98] BAEL-6465: How to handle NoSuchElementException when reading a file through a Scanner ? (#13999) --- .../ScannerNoSuchElementException.java | 58 +++++++++++++++++++ ...ScannerNoSuchElementExceptionUnitTest.java | 43 ++++++++++++++ .../src/test/resources/emptyFile.txt | 0 3 files changed, 101 insertions(+) create mode 100644 core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/scanner/ScannerNoSuchElementException.java create mode 100644 core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerNoSuchElementExceptionUnitTest.java create mode 100644 core-java-modules/core-java-io-apis-2/src/test/resources/emptyFile.txt diff --git a/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/scanner/ScannerNoSuchElementException.java b/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/scanner/ScannerNoSuchElementException.java new file mode 100644 index 0000000000..e868381dc2 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/scanner/ScannerNoSuchElementException.java @@ -0,0 +1,58 @@ +package com.baeldung.scanner; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.NoSuchElementException; +import java.util.Scanner; + +public class ScannerNoSuchElementException { + + public static String readFileV1(String pathname) throws IOException { + Path pathFile = Paths.get(pathname); + if (Files.notExists(pathFile)) { + return ""; + } + + try (Scanner scanner = new Scanner(pathFile)) { + return scanner.nextLine(); + } + } + + public static String readFileV2(String pathname) throws IOException { + Path pathFile = Paths.get(pathname); + if (Files.notExists(pathFile)) { + return ""; + } + + try (Scanner scanner = new Scanner(pathFile)) { + return scanner.hasNextLine() ? scanner.nextLine() : ""; + } + } + + public static String readFileV3(String pathname) throws IOException { + Path pathFile = Paths.get(pathname); + if (Files.notExists(pathFile) || Files.size(pathFile) == 0) { + return ""; + } + + try (Scanner scanner = new Scanner(pathFile)) { + return scanner.nextLine(); + } + } + + public static String readFileV4(String pathname) throws IOException { + Path pathFile = Paths.get(pathname); + if (Files.notExists(pathFile)) { + return ""; + } + + try (Scanner scanner = new Scanner(pathFile)) { + return scanner.nextLine(); + } catch (NoSuchElementException exception) { + return ""; + } + } + +} diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerNoSuchElementExceptionUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerNoSuchElementExceptionUnitTest.java new file mode 100644 index 0000000000..6aa7d8f9d6 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerNoSuchElementExceptionUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.scanner; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.util.NoSuchElementException; + +import org.junit.jupiter.api.Test; + +class ScannerNoSuchElementExceptionUnitTest { + + @Test + void givenEmptyFile_whenUsingReadFileV1_thenThrowException() { + Exception exception = assertThrows(NoSuchElementException.class, () -> { + ScannerNoSuchElementException.readFileV1("src/test/resources/emptyFile.txt"); + }); + + assertEquals("No line found", exception.getMessage()); + } + + @Test + void givenEmptyFile_whenUsingReadFileV2_thenSuccess() throws IOException { + String emptyLine = ScannerNoSuchElementException.readFileV2("src/test/resources/emptyFile.txt"); + + assertEquals("", emptyLine); + } + + @Test + void givenEmptyFile_whenUsingReadFileV3_thenSuccess() throws IOException { + String emptyLine = ScannerNoSuchElementException.readFileV3("src/test/resources/emptyFile.txt"); + + assertEquals("", emptyLine); + } + + @Test + void givenEmptyFile_whenUsingReadFileV4_thenSuccess() throws IOException { + String emptyLine = ScannerNoSuchElementException.readFileV4("src/test/resources/emptyFile.txt"); + + assertEquals("", emptyLine); + } + +} diff --git a/core-java-modules/core-java-io-apis-2/src/test/resources/emptyFile.txt b/core-java-modules/core-java-io-apis-2/src/test/resources/emptyFile.txt new file mode 100644 index 0000000000..e69de29bb2 From 3fc44b44eef4c416d675e5cf4b001460fa5959fa Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 29 May 2023 12:54:11 +0530 Subject: [PATCH 93/98] Update README.md --- persistence-modules/spring-data-jpa-repo/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index fc0288793c..6ffb402477 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -10,7 +10,6 @@ This module contains articles about repositories in Spring Data JPA - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) - [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) - [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) -- [SAML with Spring Boot and Spring Security](https://www.baeldung.com/spring-security-saml) - [TRUNCATE TABLE in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-truncate-table) - More articles: [[--> next]](../spring-data-jpa-repo-2) From ee4923a29d8701075084702b78531a5c9b0ca5ca Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Mon, 29 May 2023 16:50:55 +0200 Subject: [PATCH 94/98] [list-with-default] Set Default Value for Elements in List (#14125) * [list-with-default] Set Default Value for Elements in List * [list-with-default] remove the ncopies and stream methods. * [list-with-default] remove irrelevant codes --- .../ListWithDefaultValuesUnitTest.java | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/listwithdefault/ListWithDefaultValuesUnitTest.java diff --git a/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/listwithdefault/ListWithDefaultValuesUnitTest.java b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/listwithdefault/ListWithDefaultValuesUnitTest.java new file mode 100644 index 0000000000..e23fa838be --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/listwithdefault/ListWithDefaultValuesUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.java.listwithdefault; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.function.Supplier; + +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +public class ListWithDefaultValuesUnitTest { + private static final List EXPECTED_LIST = Lists.newArrayList("new", "new", "new", "new", "new"); + private static final Date DATE_EPOCH = Date.from(Instant.EPOCH); + private static final Date DATE_NOW = new Date(); + + static List newListWithDefault(T value, int size) { + List list = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + list.add(value); + } + return list; + } + + static List newListWithDefault2(Supplier supplier, int size) { + List list = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + list.add(supplier.get()); + } + return list; + } + + @Test + void whenUsingArraysFill_thenGetExpectedList() { + String[] strings = new String[5]; + Arrays.fill(strings, "new"); + List result = Arrays.asList(strings); + assertEquals(EXPECTED_LIST, result); + + //result is a fixed size list + assertThrows(UnsupportedOperationException.class, () -> result.add("a new string")); + assertThrows(UnsupportedOperationException.class, () -> result.remove(0)); + + //result's element can be "set" + result.set(2, "a new value"); + assertEquals("a new value", result.get(2)); + + Date[] dates = new Date[2]; + Arrays.fill(dates, Date.from(Instant.EPOCH)); + List dateList = Arrays.asList(dates); + assertEquals(Lists.newArrayList(DATE_EPOCH, DATE_EPOCH), dateList); + dateList.get(0) + .setTime(DATE_NOW.getTime()); + assertEquals(Lists.newArrayList(DATE_NOW, DATE_NOW), dateList); + + } + + @Test + void whenUsingNewListWithDefault_thenGetExpectedList() { + List result = newListWithDefault("new", 5); + assertEquals(EXPECTED_LIST, result); + + List intList = newListWithDefault(42, 3); + assertEquals(Lists.newArrayList(42, 42, 42), intList); + + List dateList = newListWithDefault(Date.from(Instant.EPOCH), 2); + assertEquals(Lists.newArrayList(DATE_EPOCH, DATE_EPOCH), dateList); + dateList.get(0) + .setTime(DATE_NOW.getTime()); + assertEquals(Lists.newArrayList(DATE_NOW, DATE_NOW), dateList); + } + + @Test + void whenUsingNewListWithDefault2_thenGetExpectedList() { + List result = newListWithDefault2(() -> "new", 5); + assertEquals(EXPECTED_LIST, result); + + List intList = newListWithDefault2(() -> 42, 3); + assertEquals(Lists.newArrayList(42, 42, 42), intList); + + List dateList = newListWithDefault2(() -> Date.from(Instant.EPOCH), 2); + assertEquals(Lists.newArrayList(DATE_EPOCH, DATE_EPOCH), dateList); + dateList.get(0) + .setTime(DATE_NOW.getTime()); + assertEquals(Lists.newArrayList(DATE_NOW, DATE_EPOCH), dateList); + } +} \ No newline at end of file From 3d15ed00203f57d24a5c3a0d0ccab3af6b400c2f Mon Sep 17 00:00:00 2001 From: sachin <56427366+sachin071287@users.noreply.github.com> Date: Wed, 31 May 2023 06:54:52 +0530 Subject: [PATCH 95/98] bael-5728 added code (#14010) * bael-5728 added code * bael-5728 added code * bael-5728 added code * bael-5728 code fix * bael-5728 code fix --------- Co-authored-by: Sachin kumar --- .../readresolvevsreadobject/Singleton.java | 21 +++++++ .../readresolvevsreadobject/User.java | 59 +++++++++++++++++++ .../SingletonUnitTest.java | 47 +++++++++++++++ .../readresolvevsreadobject/UserUnitTest.java | 52 ++++++++++++++++ 4 files changed, 179 insertions(+) create mode 100644 core-java-modules/core-java-serialization/src/main/java/com/baeldung/readresolvevsreadobject/Singleton.java create mode 100644 core-java-modules/core-java-serialization/src/main/java/com/baeldung/readresolvevsreadobject/User.java create mode 100644 core-java-modules/core-java-serialization/src/test/java/com/baeldung/readresolvevsreadobject/SingletonUnitTest.java create mode 100644 core-java-modules/core-java-serialization/src/test/java/com/baeldung/readresolvevsreadobject/UserUnitTest.java diff --git a/core-java-modules/core-java-serialization/src/main/java/com/baeldung/readresolvevsreadobject/Singleton.java b/core-java-modules/core-java-serialization/src/main/java/com/baeldung/readresolvevsreadobject/Singleton.java new file mode 100644 index 0000000000..91ee10dd6d --- /dev/null +++ b/core-java-modules/core-java-serialization/src/main/java/com/baeldung/readresolvevsreadobject/Singleton.java @@ -0,0 +1,21 @@ +package com.baeldung.readresolvevsreadobject; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +public class Singleton implements Serializable { + + private static final long serialVersionUID = 1L; + private static Singleton INSTANCE = new Singleton(); + + private Singleton() { + } + + public static Singleton getInstance() { + return INSTANCE; + } + + private Object readResolve() throws ObjectStreamException { + return INSTANCE; + } +} diff --git a/core-java-modules/core-java-serialization/src/main/java/com/baeldung/readresolvevsreadobject/User.java b/core-java-modules/core-java-serialization/src/main/java/com/baeldung/readresolvevsreadobject/User.java new file mode 100644 index 0000000000..95aac0301e --- /dev/null +++ b/core-java-modules/core-java-serialization/src/main/java/com/baeldung/readresolvevsreadobject/User.java @@ -0,0 +1,59 @@ +package com.baeldung.readresolvevsreadobject; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +public class User implements Serializable { + + private static final long serialVersionUID = 3659932210257138726L; + private String userName; + private String password; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return "User [userName=" + userName + ", password=" + password + "]"; + } + + public User() { + } + + public User(String userName, String password) { + super(); + this.userName = userName; + this.password = password; + } + + private void writeObject(ObjectOutputStream oos) throws IOException { + this.password = "xyz" + password; + oos.defaultWriteObject(); + } + + private void readObject(ObjectInputStream aInputStream) + throws ClassNotFoundException, IOException { + aInputStream.defaultReadObject(); + this.password = password.substring(3); + } + + private Object readResolve() { + return this; + } + +} diff --git a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/readresolvevsreadobject/SingletonUnitTest.java b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/readresolvevsreadobject/SingletonUnitTest.java new file mode 100644 index 0000000000..d5133ae976 --- /dev/null +++ b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/readresolvevsreadobject/SingletonUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.readresolvevsreadobject; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class SingletonUnitTest { + + @Test + public void testSingletonObj_withNoReadResolve() throws ClassNotFoundException, IOException { + // Serialization + FileOutputStream fos = new FileOutputStream("singleton.ser"); + ObjectOutputStream oos = new ObjectOutputStream(fos); + Singleton actualSingletonObject = Singleton.getInstance(); + oos.writeObject(actualSingletonObject); + + // Deserialization + Singleton deserializedSingletonObject = null; + FileInputStream fis = new FileInputStream("singleton.ser"); + ObjectInputStream ois = new ObjectInputStream(fis); + deserializedSingletonObject = (Singleton) ois.readObject(); + // remove readResolve() from Singleton class and uncomment this to test. + //assertNotEquals(actualSingletonObject.hashCode(), deserializedSingletonObject.hashCode()); + } + + @Test + public void testSingletonObj_withCustomReadResolve() + throws ClassNotFoundException, IOException { + // Serialization + FileOutputStream fos = new FileOutputStream("singleton.ser"); + ObjectOutputStream oos = new ObjectOutputStream(fos); + Singleton actualSingletonObject = Singleton.getInstance(); + oos.writeObject(actualSingletonObject); + + // Deserialization + Singleton deserializedSingletonObject = null; + FileInputStream fis = new FileInputStream("singleton.ser"); + ObjectInputStream ois = new ObjectInputStream(fis); + deserializedSingletonObject = (Singleton) ois.readObject(); + assertEquals(actualSingletonObject.hashCode(), deserializedSingletonObject.hashCode()); + } +} diff --git a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/readresolvevsreadobject/UserUnitTest.java b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/readresolvevsreadobject/UserUnitTest.java new file mode 100644 index 0000000000..ffd56d67e9 --- /dev/null +++ b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/readresolvevsreadobject/UserUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.readresolvevsreadobject; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class UserUnitTest { + + @Test + public void testDeserializeObj_withOverriddenReadObject() + throws ClassNotFoundException, IOException { + // Serialization + FileOutputStream fos = new FileOutputStream("user.ser"); + ObjectOutputStream oos = new ObjectOutputStream(fos); + User acutalObject = new User("Sachin", "Kumar"); + oos.writeObject(acutalObject); + + // Deserialization + User deserializedUser = null; + FileInputStream fis = new FileInputStream("user.ser"); + ObjectInputStream ois = new ObjectInputStream(fis); + deserializedUser = (User) ois.readObject(); + assertNotEquals(deserializedUser.hashCode(), acutalObject.hashCode()); + assertEquals(deserializedUser.getUserName(), "Sachin"); + assertEquals(deserializedUser.getPassword(), "Kumar"); + } + + @Test + public void testDeserializeObj_withDefaultReadObject() + throws ClassNotFoundException, IOException { + // Serialization + FileOutputStream fos = new FileOutputStream("user.ser"); + ObjectOutputStream oos = new ObjectOutputStream(fos); + User acutalObject = new User("Sachin", "Kumar"); + oos.writeObject(acutalObject); + + // Deserialization + User deserializedUser = null; + FileInputStream fis = new FileInputStream("user.ser"); + ObjectInputStream ois = new ObjectInputStream(fis); + deserializedUser = (User) ois.readObject(); + assertNotEquals(deserializedUser.hashCode(), acutalObject.hashCode()); + assertEquals(deserializedUser.getUserName(), "Sachin"); + // remove readObject() from User class and uncomment this to test. + //assertEquals(deserializedUser.getPassword(), "xyzKumar"); + } +} From 9834fe1d212c5aeb745e1691527acca8f37bef93 Mon Sep 17 00:00:00 2001 From: Avin Buricha Date: Wed, 31 May 2023 08:45:00 +0530 Subject: [PATCH 96/98] BAEL-6409 | Article code (#14135) * BAEL-6409 | Article code * Compilation fix --- .../kafka/message/MessageWithKey.java | 106 ++++++++++++++ .../kafka/message/MessageWithKeyLiveTest.java | 130 ++++++++++++++++++ 2 files changed, 236 insertions(+) create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/message/MessageWithKey.java create mode 100644 apache-kafka-2/src/test/java/com/baeldung/kafka/message/MessageWithKeyLiveTest.java diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/message/MessageWithKey.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/MessageWithKey.java new file mode 100644 index 0000000000..b03c1e1adc --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/message/MessageWithKey.java @@ -0,0 +1,106 @@ +package com.baeldung.kafka.message; + +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import org.apache.kafka.clients.admin.Admin; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.NewTopic; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +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.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MessageWithKey { + + private static Logger logger = LoggerFactory.getLogger(MessageWithKey.class); + + private static String TOPIC = "baeldung"; + private static int PARTITIONS = 5; + private static short REPLICATION_FACTOR = 1; + + private static String MESSAGE_KEY = "message-key"; + + private static Admin admin; + private static KafkaProducer producer; + private static KafkaConsumer consumer; + + public static void main(String[] args) throws ExecutionException, InterruptedException { + setup(); + + publishMessagesWithoutKey(); + + consumeMessages(); + + publishMessagesWithKey(); + + consumeMessages(); + } + + private static void consumeMessages() { + consumer.subscribe(Arrays.asList(TOPIC)); + + ConsumerRecords records = consumer.poll(Duration.ofSeconds(5)); + for (ConsumerRecord record : records) { + logger.info("Key : {}, Value : {}", record.key(), record.value()); + } + } + + private static void publishMessagesWithKey() throws ExecutionException, InterruptedException { + for (int i = 1; i <= 10; i++) { + ProducerRecord record = new ProducerRecord<>(TOPIC, MESSAGE_KEY, String.valueOf(i)); + Future future = producer.send(record); + RecordMetadata metadata = future.get(); + + logger.info(String.valueOf(metadata.partition())); + } + } + + private static void publishMessagesWithoutKey() throws ExecutionException, InterruptedException { + for (int i = 1; i <= 10; i++) { + ProducerRecord record = new ProducerRecord<>(TOPIC, String.valueOf(i)); + Future future = producer.send(record); + RecordMetadata metadata = future.get(); + + logger.info(String.valueOf(metadata.partition())); + } + } + + private static void setup() { + Properties adminProperties = new Properties(); + adminProperties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + + Properties producerProperties = new Properties(); + producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + + Properties consumerProperties = new Properties(); + consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID() + .toString()); + + admin = Admin.create(adminProperties); + producer = new KafkaProducer<>(producerProperties); + consumer = new KafkaConsumer<>(consumerProperties); + + admin.createTopics(Collections.singleton(new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR))); + } + +} \ No newline at end of file diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/message/MessageWithKeyLiveTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/MessageWithKeyLiveTest.java new file mode 100644 index 0000000000..093dc629cb --- /dev/null +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/message/MessageWithKeyLiveTest.java @@ -0,0 +1,130 @@ +package com.baeldung.kafka.message; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import org.apache.kafka.clients.admin.Admin; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.NewTopic; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +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.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; +import org.testcontainers.containers.KafkaContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; + +// This live test needs a Docker Daemon running so that a kafka container can be created + +@Testcontainers +public class MessageWithKeyLiveTest { + + private static String TOPIC = "baeldung"; + private static int PARTITIONS = 5; + private static short REPLICATION_FACTOR = 1; + + private static String MESSAGE_KEY = "message-key"; + private static String MESSAGE_VALUE = "Hello World"; + + private static Admin admin; + private static KafkaProducer producer; + private static KafkaConsumer consumer; + + @Container + private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + + @BeforeAll + static void setup() { + 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, StringSerializer.class.getName()); + producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.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.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID() + .toString()); + + admin = Admin.create(adminProperties); + producer = new KafkaProducer<>(producerProperties); + consumer = new KafkaConsumer<>(consumerProperties); + + admin.createTopics(Collections.singleton(new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR))); + } + + @AfterAll + static void destroy() { + KAFKA_CONTAINER.stop(); + } + + @Test + void givenAMessageWithKey_whenPublishedToKafkaAndConsumed_thenCheckForKey() throws ExecutionException, InterruptedException { + + ProducerRecord producerRecord = new ProducerRecord<>(TOPIC, MESSAGE_KEY, MESSAGE_VALUE); + Future future = producer.send(producerRecord); + + RecordMetadata metadata = future.get(); + + assertNotNull(metadata); + + consumer.subscribe(Arrays.asList(TOPIC)); + + ConsumerRecords records = consumer.poll(Duration.ofSeconds(5)); + for (ConsumerRecord consumerRecord : records) { + assertEquals(MESSAGE_KEY, consumerRecord.key()); + assertEquals(MESSAGE_VALUE, consumerRecord.value()); + } + } + + @Test + void givenAListOfMessageWithKeys_whenPublishedToKafka_thenCheckedIfPublishedToSamePartition() throws ExecutionException, InterruptedException { + + boolean isSamePartition = true; + int partition = 0; + + for (int i = 1; i <= 10; i++) { + ProducerRecord producerRecord = new ProducerRecord<>(TOPIC, MESSAGE_KEY, MESSAGE_VALUE); + Future future = producer.send(producerRecord); + + RecordMetadata metadata = future.get(); + + assertNotNull(metadata); + if (i == 1) { + partition = metadata.partition(); + } else { + if (partition != metadata.partition()) { + isSamePartition = false; + } + } + } + + assertTrue(isSamePartition); + } +} From 23917a110b4972ae4ce71d4c4418604b23ff28c5 Mon Sep 17 00:00:00 2001 From: Avin Buricha Date: Wed, 31 May 2023 08:53:46 +0530 Subject: [PATCH 97/98] BAEL-6416 | Article code (#14065) --- .../kafka/consumer/ConsumeFromBeginning.java | 81 +++++++++++++ .../ConsumeFromBeginningLiveTest.java | 109 ++++++++++++++++++ 2 files changed, 190 insertions(+) create mode 100644 apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/ConsumeFromBeginning.java create mode 100644 apache-kafka-2/src/test/java/com/baeldung/kafka/consumer/ConsumeFromBeginningLiveTest.java diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/ConsumeFromBeginning.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/ConsumeFromBeginning.java new file mode 100644 index 0000000000..569c5aa9e9 --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/ConsumeFromBeginning.java @@ -0,0 +1,81 @@ +package com.baeldung.kafka.consumer; + +import java.time.Duration; +import java.util.Arrays; +import java.util.Properties; +import java.util.UUID; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +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.common.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ConsumeFromBeginning { + + private static Logger logger = LoggerFactory.getLogger(ConsumeFromBeginning.class); + + private static String TOPIC = "baeldung"; + private static int messagesInTopic = 10; + + private static KafkaProducer producer; + private static KafkaConsumer consumer; + + public static void main(String[] args) { + setup(); + + publishMessages(); + + consumeFromBeginning(); + } + + private static void consumeFromBeginning() { + consumer.subscribe(Arrays.asList(TOPIC)); + + ConsumerRecords records = consumer.poll(Duration.ofSeconds(10)); + + for (ConsumerRecord record : records) { + logger.info(record.value()); + } + + consumer.seekToBeginning(consumer.assignment()); + + records = consumer.poll(Duration.ofSeconds(10)); + + for (ConsumerRecord record : records) { + logger.info(record.value()); + } + } + + private static void publishMessages() { + for (int i = 1; i <= messagesInTopic; i++) { + ProducerRecord record = new ProducerRecord<>(TOPIC, String.valueOf(i)); + producer.send(record); + } + } + + private static void setup() { + Properties producerProperties = new Properties(); + producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + + Properties consumerProperties = new Properties(); + consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID() + .toString()); + + producer = new KafkaProducer<>(producerProperties); + consumer = new KafkaConsumer<>(consumerProperties); + } + +} diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/consumer/ConsumeFromBeginningLiveTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/consumer/ConsumeFromBeginningLiveTest.java new file mode 100644 index 0000000000..6bfba1eca9 --- /dev/null +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/consumer/ConsumeFromBeginningLiveTest.java @@ -0,0 +1,109 @@ +package com.baeldung.kafka.consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; +import java.util.Arrays; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.ExecutionException; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +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.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; +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; +import org.testcontainers.utility.DockerImageName; + +// This live test needs a Docker Daemon running so that a kafka container can be created + +@Testcontainers +public class ConsumeFromBeginningLiveTest { + + private static Logger logger = LoggerFactory.getLogger(ConsumeFromBeginningLiveTest.class); + + private static String TOPIC = "baeldung"; + private static int messagesInTopic = 10; + + private static KafkaProducer producer; + private static KafkaConsumer consumer; + + @Container + private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + + @BeforeAll + static void setup() { + KAFKA_CONTAINER.addExposedPort(9092); + + 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.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.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.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID() + .toString()); + + producer = new KafkaProducer<>(producerProperties); + consumer = new KafkaConsumer<>(consumerProperties); + } + + private static void publishMessages() throws ExecutionException, InterruptedException { + for (int i = 1; i <= messagesInTopic; i++) { + ProducerRecord record = new ProducerRecord<>(TOPIC, String.valueOf(i)); + producer.send(record) + .get(); + } + } + + @AfterAll + static void destroy() { + KAFKA_CONTAINER.stop(); + } + + @Test + void givenMessages_whenConsumedFromBeginning_thenCheckIfConsumedFromBeginning() throws ExecutionException, InterruptedException { + + publishMessages(); + + consumer.subscribe(Arrays.asList(TOPIC)); + + ConsumerRecords records = consumer.poll(Duration.ofSeconds(10)); + + int messageCount = 0; + for (ConsumerRecord record : records) { + logger.info(record.value()); + messageCount++; + } + + assertEquals(messagesInTopic, messageCount); + + consumer.seekToBeginning(consumer.assignment()); + + records = consumer.poll(Duration.ofSeconds(10)); + + messageCount = 0; + for (ConsumerRecord record : records) { + logger.info(record.value()); + messageCount++; + } + + assertEquals(messagesInTopic, messageCount); + } +} From 920214f38dd07af14eea79682e16572a41118054 Mon Sep 17 00:00:00 2001 From: Kasra Madadipouya Date: Wed, 31 May 2023 13:40:49 +0200 Subject: [PATCH 98/98] JAVA-17164 update config and discovery services to use Spring Boot 2.7.X (#13967) --- .../book-service.properties | 2 + .../application-config/gateway.properties | 18 +---- .../rating-service.properties | 2 + .../spring-cloud-bootstrap/config/pom.xml | 8 +-- .../bootstrap/config/ConfigApplication.java | 4 +- .../bootstrap/config/SecurityConfig.java | 42 +++++++---- .../spring-cloud-bootstrap/discovery/pom.xml | 14 ++-- .../bootstrap/discovery/SecurityConfig.java | 2 +- .../spring-cloud-bootstrap/gateway/pom.xml | 24 ++++--- .../bootstrap/gateway/ErrorPageConfig.java | 6 +- .../bootstrap/gateway/GatewayApplication.java | 67 +----------------- .../bootstrap/gateway/SecurityConfig.java | 70 ++++++++++++------- .../bootstrap/gateway/SessionConfig.java | 9 ++- .../gateway/client/book/BooksClient.java | 5 +- .../gateway/client/rating/RatingsClient.java | 9 ++- .../filter/SessionSavingPreFilter.java | 25 +++++++ .../filter/SessionSavingZuulPreFilter.java | 47 ------------- .../src/main/resources/bootstrap.properties | 2 + .../spring-cloud-bootstrap/pom.xml | 1 - .../spring-cloud-bootstrap/svc-book/pom.xml | 20 ++++-- .../svcbook/BookServiceApplication.java | 43 +----------- .../cloud/bootstrap/svcbook/CookieConfig.java | 16 +++++ .../bootstrap/svcbook/SecurityConfig.java | 35 +++++----- .../bootstrap/svcbook/book/BookService.java | 10 +-- .../src/main/resources/bootstrap.properties | 2 + .../spring-cloud-bootstrap/svc-rating/pom.xml | 28 +++++--- .../bootstrap/svcrating/CookieConfig.java | 16 +++++ .../svcrating/RatingServiceApplication.java | 57 +-------------- .../bootstrap/svcrating/SecurityConfig.java | 50 ++++++------- .../bootstrap/svcrating/SessionConfig.java | 20 +++--- .../rating/RatingCacheRepository.java | 6 +- .../svcrating/rating/RatingService.java | 22 +++--- .../src/main/resources/bootstrap.properties | 2 + .../spring-cloud-bootstrap/zipkin/README.md | 19 +++++ .../zipkin/docker-compose.yml | 6 ++ .../spring-cloud-bootstrap/zipkin/pom.xml | 53 -------------- .../bootstrap/zipkin/ZipkinApplication.java | 15 ---- .../src/main/resources/bootstrap.properties | 7 -- .../zipkin/src/main/resources/logback.xml | 13 ---- .../java/com/baeldung/SpringContextTest.java | 17 ----- 40 files changed, 329 insertions(+), 485 deletions(-) create mode 100644 spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingPreFilter.java delete mode 100644 spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java create mode 100644 spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/CookieConfig.java create mode 100644 spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/CookieConfig.java create mode 100644 spring-cloud-modules/spring-cloud-bootstrap/zipkin/README.md create mode 100644 spring-cloud-modules/spring-cloud-bootstrap/zipkin/docker-compose.yml delete mode 100644 spring-cloud-modules/spring-cloud-bootstrap/zipkin/pom.xml delete mode 100644 spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/java/com/baeldung/spring/cloud/bootstrap/zipkin/ZipkinApplication.java delete mode 100644 spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/resources/bootstrap.properties delete mode 100644 spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/resources/logback.xml delete mode 100644 spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-cloud-modules/spring-cloud-bootstrap/application-config/book-service.properties b/spring-cloud-modules/spring-cloud-bootstrap/application-config/book-service.properties index 49f7d1ed91..2ea30b9ab7 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/application-config/book-service.properties +++ b/spring-cloud-modules/spring-cloud-bootstrap/application-config/book-service.properties @@ -18,3 +18,5 @@ spring.redis.port=6379 spring.sleuth.sampler.percentage=1.0 spring.sleuth.web.skipPattern=(^cleanup.*) + +spring.zipkin.baseUrl=http://localhost:9411 diff --git a/spring-cloud-modules/spring-cloud-bootstrap/application-config/gateway.properties b/spring-cloud-modules/spring-cloud-bootstrap/application-config/gateway.properties index e9e593284c..42e114450d 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/application-config/gateway.properties +++ b/spring-cloud-modules/spring-cloud-bootstrap/application-config/gateway.properties @@ -6,25 +6,13 @@ eureka.client.registryFetchIntervalSeconds = 5 management.security.sessions=always -zuul.routes.book-service.path=/book-service/** -zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization -hystrix.command.book-service.execution.isolation.thread.timeoutInMilliseconds=600000 - -zuul.routes.rating-service.path=/rating-service/** -zuul.routes.rating-service.sensitive-headers=Set-Cookie,Authorization -hystrix.command.rating-service.execution.isolation.thread.timeoutInMilliseconds=600000 - -zuul.routes.discovery.path=/discovery/** -zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization -zuul.routes.discovery.url=http://localhost:8082 -hystrix.command.discovery.execution.isolation.thread.timeoutInMilliseconds=600000 - logging.level.org.springframework.web.=debug logging.level.org.springframework.security=debug -logging.level.org.springframework.cloud.netflix.zuul=debug spring.redis.host=localhost spring.redis.port=6379 spring.sleuth.sampler.percentage=1.0 -spring.sleuth.web.skipPattern=(^cleanup.*|.+favicon.*) \ No newline at end of file +spring.sleuth.web.skipPattern=(^cleanup.*|.+favicon.*) + +spring.zipkin.baseUrl=http://localhost:9411 diff --git a/spring-cloud-modules/spring-cloud-bootstrap/application-config/rating-service.properties b/spring-cloud-modules/spring-cloud-bootstrap/application-config/rating-service.properties index b7cbb6fbd6..059b87e4e7 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/application-config/rating-service.properties +++ b/spring-cloud-modules/spring-cloud-bootstrap/application-config/rating-service.properties @@ -18,3 +18,5 @@ spring.redis.port=6379 spring.sleuth.sampler.percentage=1.0 spring.sleuth.web.skipPattern=(^cleanup.*) + +spring.zipkin.baseUrl=http://localhost:9411 diff --git a/spring-cloud-modules/spring-cloud-bootstrap/config/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/config/pom.xml index 6c9c3c5374..c1be447822 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/config/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/config/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 @@ -33,7 +33,7 @@ org.springframework.cloud - spring-cloud-starter-eureka + spring-cloud-starter-netflix-eureka-client org.springframework.boot @@ -42,7 +42,7 @@ - Brixton.SR7 + 2021.0.7 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java b/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java index 847c86f881..c3e04c4b54 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java @@ -2,12 +2,12 @@ package com.baeldung.spring.cloud.bootstrap.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.config.server.EnableConfigServer; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableConfigServer -@EnableEurekaClient +@EnableDiscoveryClient public class ConfigApplication { public static void main(String[] args) { SpringApplication.run(ConfigApplication.class, args); diff --git a/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java index ef1d7b0b78..d563052baa 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java @@ -1,23 +1,41 @@ package com.baeldung.spring.cloud.bootstrap.config; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; -@Configuration @EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("configUser").password("configPassword").roles("SYSTEM"); + @Bean + public InMemoryUserDetailsManager userDetailsService(BCryptPasswordEncoder bCryptPasswordEncoder) { + InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); + manager.createUser(User.withUsername("configUser") + .password(bCryptPasswordEncoder.encode("configPassword")) + .roles("SYSTEM") + .build()); + return manager; } - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().hasRole("SYSTEM").and().httpBasic().and().csrf().disable(); + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.authorizeRequests() + .anyRequest() + .hasRole("SYSTEM") + .and() + .httpBasic() + .and() + .csrf() + .disable(); + return http.build(); + } + + @Bean + public BCryptPasswordEncoder encoder() { + return new BCryptPasswordEncoder(); } } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/discovery/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/discovery/pom.xml index fb06c6052b..28c1a741a6 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/discovery/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/discovery/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 @@ -33,7 +33,11 @@ org.springframework.cloud - spring-cloud-starter-eureka-server + spring-cloud-starter-bootstrap + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server org.springframework.boot @@ -41,7 +45,7 @@ org.springframework.session - spring-session + spring-session-data-redis org.springframework.boot @@ -50,7 +54,7 @@ - Edgware.SR5 + 2021.0.7 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java index a89faba962..fa389ec6a3 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java @@ -17,7 +17,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("discUser").password("discPassword").roles("SYSTEM"); + auth.inMemoryAuthentication().withUser("discUser").password("{noop}discPassword").roles("SYSTEM"); } @Override diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml index e1041516c4..fa6735199f 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 @@ -33,11 +33,15 @@ org.springframework.cloud - spring-cloud-starter-eureka + spring-cloud-starter-bootstrap org.springframework.cloud - spring-cloud-starter-zuul + spring-cloud-starter-netflix-eureka-client + + + org.springframework.cloud + spring-cloud-starter-gateway org.springframework.boot @@ -45,7 +49,7 @@ org.springframework.session - spring-session + spring-session-data-redis org.springframework.boot @@ -53,11 +57,15 @@ org.springframework.cloud - spring-cloud-starter-zipkin + spring-cloud-starter-sleuth org.springframework.cloud - spring-cloud-starter-feign + spring-cloud-sleuth-zipkin + + + org.springframework.cloud + spring-cloud-starter-openfeign @@ -97,7 +105,7 @@
- Dalston.RELEASE + 2021.0.7 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/ErrorPageConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/ErrorPageConfig.java index 67d172d3cd..b1fa7ce0bb 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/ErrorPageConfig.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/ErrorPageConfig.java @@ -1,8 +1,8 @@ package com.baeldung.spring.cloud.bootstrap.gateway; -import org.springframework.boot.web.servlet.ErrorPage; -import org.springframework.boot.web.servlet.ErrorPageRegistrar; -import org.springframework.boot.web.servlet.ErrorPageRegistry; +import org.springframework.boot.web.server.ErrorPage; +import org.springframework.boot.web.server.ErrorPageRegistrar; +import org.springframework.boot.web.server.ErrorPageRegistry; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java index 8fc75e1ff6..6adda92c25 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java @@ -1,76 +1,15 @@ package com.baeldung.spring.cloud.bootstrap.gateway; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.cloud.netflix.ribbon.RibbonClientSpecification; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.cloud.sleuth.metric.SpanMetricReporter; -import org.springframework.cloud.sleuth.zipkin.HttpZipkinSpanReporter; -import org.springframework.cloud.sleuth.zipkin.ZipkinProperties; -import org.springframework.cloud.sleuth.zipkin.ZipkinSpanReporter; -import org.springframework.context.annotation.Bean; -import org.springframework.web.client.RestTemplate; -import zipkin.Span; - -import java.util.ArrayList; -import java.util.List; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication -@EnableZuulProxy -@EnableEurekaClient @EnableFeignClients +@EnableDiscoveryClient public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } - - @Autowired(required = false) - private List configurations = new ArrayList<>(); - @Autowired - private EurekaClient eurekaClient; - @Autowired - private SpanMetricReporter spanMetricReporter; - @Autowired - private ZipkinProperties zipkinProperties; - @Value("${spring.sleuth.web.skipPattern}") - private String skipPattern; - - @Bean - @LoadBalanced - RestTemplate restTemplate() { - return new RestTemplate(); - } - - @Bean - public SpringClientFactory springClientFactory() { - SpringClientFactory factory = new SpringClientFactory(); - factory.setConfigurations(this.configurations); - return factory; - } - - @Bean - public ZipkinSpanReporter makeZipkinSpanReporter() { - return new ZipkinSpanReporter() { - private HttpZipkinSpanReporter delegate; - private String baseUrl; - - @Override - public void report(Span span) { - InstanceInfo instance = eurekaClient.getNextServerFromEureka("zipkin", false); - if (baseUrl == null || !instance.getHomePageUrl().equals(baseUrl)) { - baseUrl = instance.getHomePageUrl(); - } - delegate = new HttpZipkinSpanReporter(new RestTemplate(), baseUrl, zipkinProperties.getFlushInterval(), spanMetricReporter); - if (!span.name.matches(skipPattern)) delegate.report(span); - } - }; - } } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java index d56be699e6..088fdd01f7 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java @@ -1,37 +1,59 @@ package com.baeldung.spring.cloud.bootstrap.gateway; -import org.springframework.beans.factory.annotation.Autowired; +import static org.springframework.security.config.Customizer.withDefaults; + +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler; -@EnableWebSecurity +@EnableWebFluxSecurity @Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .withUser("user").password("password").roles("USER") - .and() - .withUser("admin").password("admin").roles("ADMIN"); + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User.withUsername("user") + .password(passwordEncoder().encode("password")) + .roles("USER") + .build(); + UserDetails adminUser = User.withUsername("admin") + .password(passwordEncoder().encode("admin")) + .roles("ADMIN") + .build(); + return new MapReactiveUserDetailsService(user, adminUser); } - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .formLogin() - .defaultSuccessUrl("/home/index.html", true) + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http.formLogin() + .authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/home/index.html")) .and() - .authorizeRequests() - .antMatchers("/book-service/**", "/rating-service/**", "/login*", "/").permitAll() - .antMatchers("/eureka/**").hasRole("ADMIN") - .anyRequest().authenticated() + .authorizeExchange() + .pathMatchers("/book-service/**", "/rating-service/**", "/login*", "/") + .permitAll() + .pathMatchers("/eureka/**") + .hasRole("ADMIN") + .anyExchange() + .authenticated() .and() - .logout() + .logout() .and() - .csrf().disable(); + .csrf() + .disable() + .httpBasic(withDefaults()); + return http.build(); } } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SessionConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SessionConfig.java index 14f7deb770..498c780f65 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SessionConfig.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SessionConfig.java @@ -1,11 +1,10 @@ package com.baeldung.spring.cloud.bootstrap.gateway; import org.springframework.context.annotation.Configuration; -import org.springframework.session.data.redis.RedisFlushMode; -import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; -import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; +import org.springframework.session.data.redis.config.annotation.web.server.EnableRedisWebSession; @Configuration -@EnableRedisHttpSession(redisFlushMode = RedisFlushMode.IMMEDIATE) -public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +@EnableRedisWebSession +public class SessionConfig { + } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/client/book/BooksClient.java b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/client/book/BooksClient.java index f60f65d23c..8fd235b3dc 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/client/book/BooksClient.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/client/book/BooksClient.java @@ -1,7 +1,6 @@ package com.baeldung.spring.cloud.bootstrap.gateway.client.book; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -9,6 +8,6 @@ import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(value = "book-service") public interface BooksClient { - @RequestMapping(value = "/books/{bookId}", method = {RequestMethod.GET}) + @RequestMapping(value = "/books/{bookId}", method = { RequestMethod.GET }) Book getBookById(@PathVariable("bookId") Long bookId); } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/client/rating/RatingsClient.java b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/client/rating/RatingsClient.java index 9728111c5e..d04ba85082 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/client/rating/RatingsClient.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/client/rating/RatingsClient.java @@ -1,17 +1,16 @@ package com.baeldung.spring.cloud.bootstrap.gateway.client.rating; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.web.bind.annotation.GetMapping; +import java.util.List; + +import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; -import java.util.List; - @FeignClient(value = "rating-service") public interface RatingsClient { - @RequestMapping(value = "/ratings", method = {RequestMethod.GET}) + @RequestMapping(value = "/ratings", method = { RequestMethod.GET }) List getRatingsByBookId(@RequestParam("bookId") Long bookId, @RequestHeader("Cookie") String session); } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingPreFilter.java b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingPreFilter.java new file mode 100644 index 0000000000..bf10152318 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingPreFilter.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.cloud.bootstrap.gateway.filter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; + +import reactor.core.publisher.Mono; + +@Component +public class SessionSavingPreFilter implements GlobalFilter { + + private static final Logger logger = LoggerFactory.getLogger(SessionSavingPreFilter.class); + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + return exchange.getSession() + .flatMap(session -> { + logger.debug("SessionId: {}", session.getId()); + return chain.filter(exchange); + }); + } +} diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java deleted file mode 100644 index 1c90ba2e12..0000000000 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.spring.cloud.bootstrap.gateway.filter; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.session.Session; -import org.springframework.session.SessionRepository; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpSession; - -@Component -public class SessionSavingZuulPreFilter extends ZuulFilter { - - private Logger log = LoggerFactory.getLogger(this.getClass()); - - @Autowired - private SessionRepository repository; - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - RequestContext context = RequestContext.getCurrentContext(); - HttpSession httpSession = context.getRequest().getSession(); - Session session = repository.getSession(httpSession.getId()); - - context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId()); - log.info("ZuulPreFilter session proxy: {}", session.getId()); - return null; - } - - @Override - public String filterType() { - return "pre"; - } - - @Override - public int filterOrder() { - return 0; - } -} diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties index 43491ff36b..1c90ca9db0 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties @@ -3,5 +3,7 @@ spring.cloud.config.discovery.service-id=config spring.cloud.config.discovery.enabled=true spring.cloud.config.username=configUser spring.cloud.config.password=configPassword +spring.cloud.gateway.discovery.locator.enabled=true +spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/pom.xml index 1e97082db1..e7fe7e7485 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/pom.xml @@ -20,7 +20,6 @@ gateway svc-book svc-rating - zipkin customer-service order-service diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/svc-book/pom.xml index b1aa205af5..c973968a70 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/svc-book/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 @@ -34,7 +34,11 @@ org.springframework.cloud - spring-cloud-starter-eureka + spring-cloud-starter-bootstrap + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client org.springframework.boot @@ -46,7 +50,7 @@ org.springframework.session - spring-session + spring-session-data-redis org.springframework.boot @@ -63,12 +67,16 @@ org.springframework.cloud - spring-cloud-starter-zipkin + spring-cloud-starter-sleuth + + + org.springframework.cloud + spring-cloud-sleuth-zipkin - Dalston.RELEASE + 2021.0.7 \ No newline at end of file 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/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java index d787b5e407..8b1eab7885 100644 --- 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/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java @@ -1,53 +1,14 @@ package com.baeldung.spring.cloud.bootstrap.svcbook; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.cloud.sleuth.metric.SpanMetricReporter; -import org.springframework.cloud.sleuth.zipkin.HttpZipkinSpanReporter; -import org.springframework.cloud.sleuth.zipkin.ZipkinProperties; -import org.springframework.cloud.sleuth.zipkin.ZipkinSpanReporter; -import org.springframework.context.annotation.Bean; -import org.springframework.web.client.RestTemplate; - -import zipkin.Span; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication -@EnableEurekaClient +@EnableDiscoveryClient public class BookServiceApplication { - @Autowired - private EurekaClient eurekaClient; - @Autowired - private SpanMetricReporter spanMetricReporter; - @Autowired - private ZipkinProperties zipkinProperties; - @Value("${spring.sleuth.web.skipPattern}") - private String skipPattern; - public static void main(String[] args) { SpringApplication.run(BookServiceApplication.class, args); } - - @Bean - public ZipkinSpanReporter makeZipkinSpanReporter() { - return new ZipkinSpanReporter() { - private HttpZipkinSpanReporter delegate; - private String baseUrl; - - @Override - public void report(Span span) { - InstanceInfo instance = eurekaClient.getNextServerFromEureka("zipkin", false); - if (baseUrl == null || !instance.getHomePageUrl().equals(baseUrl)) { - baseUrl = instance.getHomePageUrl(); - } - delegate = new HttpZipkinSpanReporter(new RestTemplate(), baseUrl, zipkinProperties.getFlushInterval(), spanMetricReporter); - if (!span.name.matches(skipPattern)) delegate.report(span); - } - }; - } } 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/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/CookieConfig.java new file mode 100644 index 0000000000..99696836c1 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/CookieConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.session.web.http.DefaultCookieSerializer; + +@Configuration +public class CookieConfig { + + @Bean + public DefaultCookieSerializer cookieSerializer() { + DefaultCookieSerializer serializer = new DefaultCookieSerializer(); + serializer.setUseBase64Encoding(false); + return serializer; + } +} \ No newline at end of file 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/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java index 6aa996c575..0b9520c976 100644 --- 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/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java @@ -1,36 +1,37 @@ package com.baeldung.spring.cloud.bootstrap.svcbook; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; @EnableWebSecurity @Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { @Autowired - public void configureGlobal1(AuthenticationManagerBuilder auth) throws Exception { - //try in memory auth with no users to support the case that this will allow for users that are logged in to go anywhere + public void registerAuthProvider(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication(); } - @Override - protected void configure(HttpSecurity http) throws Exception { - http.httpBasic() + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + return http.authorizeHttpRequests((auth) -> auth.antMatchers(HttpMethod.GET, "/books") + .permitAll() + .antMatchers(HttpMethod.GET, "/books/*") + .permitAll() + .antMatchers(HttpMethod.POST, "/books") + .hasRole("ADMIN") + .antMatchers(HttpMethod.PATCH, "/books/*") + .hasRole("ADMIN") + .antMatchers(HttpMethod.DELETE, "/books/*") + .hasRole("ADMIN")) + .csrf() .disable() - .authorizeRequests() - .antMatchers(HttpMethod.GET, "/books").permitAll() - .antMatchers(HttpMethod.GET, "/books/*").permitAll() - .antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN") - .antMatchers(HttpMethod.PATCH, "/books/*").hasRole("ADMIN") - .antMatchers(HttpMethod.DELETE, "/books/*").hasRole("ADMIN") - .anyRequest().authenticated() - .and() - .csrf() - .disable(); + .build(); } } 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/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java index 106fdad5d9..4ee3112049 100644 --- 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/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java @@ -2,7 +2,6 @@ package com.baeldung.spring.cloud.bootstrap.svcbook.book; import java.util.List; import java.util.Map; -import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -23,8 +22,8 @@ public class BookService { } public Book findBookById(Long bookId) { - return Optional.ofNullable(bookRepository.findOne(bookId)) - .orElseThrow(() -> new BookNotFoundException("Book not found. ID: " + bookId)); + return bookRepository.findById(bookId) + .orElseThrow(() -> new BookNotFoundException(String.format("Book not found. ID: %s", bookId))); } @Transactional(propagation = Propagation.REQUIRED) @@ -37,7 +36,7 @@ public class BookService { @Transactional(propagation = Propagation.REQUIRED) public void deleteBook(Long bookId) { - bookRepository.delete(bookId); + bookRepository.deleteById(bookId); } @Transactional(propagation = Propagation.REQUIRED) @@ -60,7 +59,8 @@ public class BookService { public Book updateBook(Book book, Long bookId) { Preconditions.checkNotNull(book); Preconditions.checkState(book.getId() == bookId); - Preconditions.checkNotNull(bookRepository.findOne(bookId)); + Preconditions.checkArgument(bookRepository.findById(bookId) + .isPresent()); return bookRepository.save(book); } } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/resources/bootstrap.properties b/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/resources/bootstrap.properties index 481cdc182c..a50048c671 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/resources/bootstrap.properties +++ b/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/resources/bootstrap.properties @@ -3,5 +3,7 @@ spring.cloud.config.discovery.service-id=config spring.cloud.config.discovery.enabled=true spring.cloud.config.username=configUser spring.cloud.config.password=configPassword +spring.cloud.gateway.discovery.locator.enabled=true +spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/pom.xml index 336c1ff2c6..29ebb4c4bc 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 @@ -34,7 +34,11 @@ org.springframework.cloud - spring-cloud-starter-eureka + spring-cloud-starter-bootstrap + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client org.springframework.boot @@ -46,7 +50,7 @@ org.springframework.session - spring-session + spring-session-data-redis org.springframework.boot @@ -58,25 +62,29 @@ org.springframework.cloud - spring-cloud-starter-hystrix + spring-cloud-starter-circuitbreaker-resilience4j org.springframework.boot spring-boot-starter-actuator + + org.springframework.cloud + spring-cloud-starter-sleuth + + + org.springframework.cloud + spring-cloud-sleuth-zipkin + com.h2database h2 runtime - - org.springframework.cloud - spring-cloud-starter-zipkin - - Dalston.RELEASE + 2021.0.7 \ No newline at end of file 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/CookieConfig.java new file mode 100644 index 0000000000..9774c18568 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/CookieConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.session.web.http.DefaultCookieSerializer; + +@Configuration +public class CookieConfig { + + @Bean + public DefaultCookieSerializer cookieSerializer() { + DefaultCookieSerializer serializer = new DefaultCookieSerializer(); + serializer.setUseBase64Encoding(false); + return serializer; + } +} \ No newline at end of file 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java index 5a94f19472..1774407d26 100644 --- 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java @@ -1,69 +1,18 @@ package com.baeldung.spring.cloud.bootstrap.svcrating; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.cloud.netflix.hystrix.EnableHystrix; -import org.springframework.cloud.sleuth.metric.SpanMetricReporter; -import org.springframework.cloud.sleuth.zipkin.HttpZipkinSpanReporter; -import org.springframework.cloud.sleuth.zipkin.ZipkinProperties; -import org.springframework.cloud.sleuth.zipkin.ZipkinSpanReporter; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.AdviceMode; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.web.client.RestTemplate; - -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; -import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect; - -import zipkin.Span; @SpringBootApplication -@EnableEurekaClient -@EnableHystrix -@EnableTransactionManagement(order=Ordered.LOWEST_PRECEDENCE, mode=AdviceMode.ASPECTJ) +@EnableDiscoveryClient +@EnableTransactionManagement(order = Ordered.LOWEST_PRECEDENCE, mode = AdviceMode.ASPECTJ) public class RatingServiceApplication { - @Autowired - private EurekaClient eurekaClient; - @Autowired - private SpanMetricReporter spanMetricReporter; - @Autowired - private ZipkinProperties zipkinProperties; - @Value("${spring.sleuth.web.skipPattern}") - private String skipPattern; public static void main(String[] args) { SpringApplication.run(RatingServiceApplication.class, args); } - - @Bean - public ZipkinSpanReporter makeZipkinSpanReporter() { - return new ZipkinSpanReporter() { - private HttpZipkinSpanReporter delegate; - private String baseUrl; - - @Override - public void report(Span span) { - InstanceInfo instance = eurekaClient.getNextServerFromEureka("zipkin", false); - if (baseUrl == null || !instance.getHomePageUrl().equals(baseUrl)) { - baseUrl = instance.getHomePageUrl(); - } - delegate = new HttpZipkinSpanReporter(new RestTemplate(), baseUrl, zipkinProperties.getFlushInterval(), spanMetricReporter); - if (!span.name.matches(skipPattern)) delegate.report(span); - } - }; - } - - @Bean - @Primary - @Order(value=Ordered.HIGHEST_PRECEDENCE) - public HystrixCommandAspect hystrixAspect() { - return new HystrixCommandAspect(); - } } \ No newline at end of file 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java index 9b6afc8059..f470946e1d 100644 --- 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java @@ -1,39 +1,41 @@ package com.baeldung.spring.cloud.bootstrap.svcrating; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; @EnableWebSecurity @Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { - @Autowired - public void configureGlobal1(AuthenticationManagerBuilder auth) throws Exception { - //try in memory auth with no users to support the case that this will allow for users that are logged in to go anywhere - auth.inMemoryAuthentication(); + @Bean + public UserDetailsService users() { + return new InMemoryUserDetailsManager(); } - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .regexMatchers("^/ratings\\?bookId.*$").authenticated() - .antMatchers(HttpMethod.POST,"/ratings").authenticated() - .antMatchers(HttpMethod.PATCH,"/ratings/*").hasRole("ADMIN") - .antMatchers(HttpMethod.DELETE,"/ratings/*").hasRole("ADMIN") - .antMatchers(HttpMethod.GET,"/ratings").hasRole("ADMIN") - .antMatchers(HttpMethod.GET,"/hystrix").authenticated() - .anyRequest().authenticated() + @Bean + public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { + return httpSecurity.authorizeHttpRequests((auth) -> auth.regexMatchers("^/ratings\\?bookId.*$") + .authenticated() + .antMatchers(HttpMethod.POST, "/ratings") + .authenticated() + .antMatchers(HttpMethod.PATCH, "/ratings/*") + .hasRole("ADMIN") + .antMatchers(HttpMethod.DELETE, "/ratings/*") + .hasRole("ADMIN") + .antMatchers(HttpMethod.GET, "/ratings") + .hasRole("ADMIN") + .anyRequest() + .authenticated()) + .httpBasic() .and() - .httpBasic().and() - .csrf() - .disable(); - - + .csrf() + .disable() + .build(); } } 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java index 6e8fcd10d4..c0e067026d 100644 --- 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java @@ -5,24 +5,24 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; -import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; @Configuration @EnableRedisHttpSession public class SessionConfig extends AbstractHttpSessionApplicationInitializer { + @Autowired - Environment properties; - + private Environment properties; + @Bean @Primary - public JedisConnectionFactory connectionFactory() { - JedisConnectionFactory factory = new JedisConnectionFactory(); - factory.setHostName(properties.getProperty("spring.redis.host","localhost")); - factory.setPort(properties.getProperty("spring.redis.port", Integer.TYPE,6379)); - factory.afterPropertiesSet(); - factory.setUsePool(true); - return factory; + public LettuceConnectionFactory redisConnectionFactory() { + RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration(); + redisConfiguration.setHostName(properties.getProperty("spring.redis.host", "localhost")); + redisConfiguration.setPort(properties.getProperty("spring.redis.port", Integer.TYPE, 6379)); + return new LettuceConnectionFactory(redisConfiguration); } } 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingCacheRepository.java index d9f3a3584e..1263093b80 100644 --- 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingCacheRepository.java @@ -6,21 +6,21 @@ import java.util.stream.Collectors; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Repository; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.stereotype.Repository; @Repository public class RatingCacheRepository implements InitializingBean { @Autowired - private JedisConnectionFactory cacheConnectionFactory; + private LettuceConnectionFactory cacheConnectionFactory; private StringRedisTemplate redisTemplate; private ValueOperations valueOps; 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java index 395ff50bd7..e02803bff3 100644 --- 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/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java @@ -2,7 +2,6 @@ package com.baeldung.spring.cloud.bootstrap.svcrating.rating; import java.util.List; import java.util.Map; -import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -10,7 +9,8 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.google.common.base.Preconditions; -import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; + +import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker; @Service @Transactional(readOnly = true) @@ -22,31 +22,31 @@ public class RatingService { @Autowired private RatingCacheRepository cacheRepository; - @HystrixCommand(commandKey = "ratingsByBookIdFromDB", fallbackMethod = "findCachedRatingsByBookId") + @CircuitBreaker(name = "ratingsByBookIdFromDB", fallbackMethod = "findCachedRatingsByBookId") public List findRatingsByBookId(Long bookId) { return ratingRepository.findRatingsByBookId(bookId); } - public List findCachedRatingsByBookId(Long bookId) { + public List findCachedRatingsByBookId(Long bookId, Exception exception) { return cacheRepository.findCachedRatingsByBookId(bookId); } - @HystrixCommand(commandKey = "ratingsFromDB", fallbackMethod = "findAllCachedRatings") + @CircuitBreaker(name = "ratingsFromDB", fallbackMethod = "findAllCachedRatings") public List findAllRatings() { return ratingRepository.findAll(); } - public List findAllCachedRatings() { + public List findAllCachedRatings(Exception exception) { return cacheRepository.findAllCachedRatings(); } - @HystrixCommand(commandKey = "ratingsByIdFromDB", fallbackMethod = "findCachedRatingById", ignoreExceptions = { RatingNotFoundException.class }) + @CircuitBreaker(name = "ratingsByIdFromDB", fallbackMethod = "findCachedRatingById") public Rating findRatingById(Long ratingId) { - return Optional.ofNullable(ratingRepository.findOne(ratingId)) + return ratingRepository.findById(ratingId) .orElseThrow(() -> new RatingNotFoundException("Rating not found. ID: " + ratingId)); } - public Rating findCachedRatingById(Long ratingId) { + public Rating findCachedRatingById(Long ratingId, Exception exception) { return cacheRepository.findCachedRatingById(ratingId); } @@ -62,7 +62,7 @@ public class RatingService { @Transactional(propagation = Propagation.REQUIRED) public void deleteRating(Long ratingId) { - ratingRepository.delete(ratingId); + ratingRepository.deleteById(ratingId); cacheRepository.deleteRating(ratingId); } @@ -86,7 +86,7 @@ public class RatingService { public Rating updateRating(Rating rating, Long ratingId) { Preconditions.checkNotNull(rating); Preconditions.checkState(rating.getId() == ratingId); - Preconditions.checkNotNull(ratingRepository.findOne(ratingId)); + Preconditions.checkNotNull(ratingRepository.findById(ratingId)); return ratingRepository.save(rating); } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties b/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties index be5cf7f1e1..846bc4c7aa 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties +++ b/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties @@ -3,5 +3,7 @@ spring.cloud.config.discovery.service-id=config spring.cloud.config.discovery.enabled=true spring.cloud.config.username=configUser spring.cloud.config.password=configPassword +spring.cloud.gateway.discovery.locator.enabled=true +spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/README.md b/spring-cloud-modules/spring-cloud-bootstrap/zipkin/README.md new file mode 100644 index 0000000000..66f150ede0 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin/README.md @@ -0,0 +1,19 @@ +# Zipkin server + +Zipkin project [deprecated custom server](https://github.com/openzipkin/zipkin/tree/master/zipkin-server). +It's no longer possible to run a custom Zipkin server compatible with Spring Cloud or even Spring Boot. + +The best approach to run a Zipkin server is to use docker. We provided a docker-compose file that you can run: + +```bash +$ docker compose up -d +``` + +After that Zipkin is accessible via [http://localhost:9411](http://localhost:9411) + +Alternatively, you can run the Zipkin Jar file, + +```bash +$ curl -sSL https://zipkin.io/quickstart.sh | bash -s +$ java -jar zipkin.jar +``` \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/docker-compose.yml b/spring-cloud-modules/spring-cloud-bootstrap/zipkin/docker-compose.yml new file mode 100644 index 0000000000..20528dca8f --- /dev/null +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin/docker-compose.yml @@ -0,0 +1,6 @@ +version: "3.9" +services: + zipkin: + image: openzipkin/zipkin + ports: + - 9411:9411 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/zipkin/pom.xml deleted file mode 100644 index b515661a00..0000000000 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - zipkin - 1.0.0-SNAPSHOT - zipkin - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../../parent-boot-1 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud-dependencies.version} - pom - import - - - - - - - org.springframework.cloud - spring-cloud-starter-config - - - org.springframework.cloud - spring-cloud-starter-eureka - - - io.zipkin.java - zipkin-server - - - io.zipkin.java - zipkin-autoconfigure-ui - runtime - - - - - Brixton.SR7 - - - \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/java/com/baeldung/spring/cloud/bootstrap/zipkin/ZipkinApplication.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/java/com/baeldung/spring/cloud/bootstrap/zipkin/ZipkinApplication.java deleted file mode 100644 index d757567156..0000000000 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/java/com/baeldung/spring/cloud/bootstrap/zipkin/ZipkinApplication.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.spring.cloud.bootstrap.zipkin; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import zipkin.server.EnableZipkinServer; - -@SpringBootApplication -@EnableEurekaClient -@EnableZipkinServer -public class ZipkinApplication { - public static void main(String[] args) { - SpringApplication.run(ZipkinApplication.class, args); - } -} diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/resources/bootstrap.properties b/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/resources/bootstrap.properties deleted file mode 100644 index 9569179a4f..0000000000 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,7 +0,0 @@ -spring.cloud.config.name=zipkin -spring.cloud.config.discovery.service-id=config -spring.cloud.config.discovery.enabled=true -spring.cloud.config.username=configUser -spring.cloud.config.password=configPassword - -eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/resources/logback.xml b/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/test/java/com/baeldung/SpringContextTest.java deleted file mode 100644 index 71e67df191..0000000000 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin/src/test/java/com/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.spring.cloud.bootstrap.zipkin.ZipkinApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ZipkinApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -}