From 005c68e0a65aa3f0d27f5d4305a76a00901e841d Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Fri, 28 Apr 2023 20:24:19 +0530 Subject: [PATCH 01/46] JAVA-13721 Format, Fix Package, Upgrade version of all the articles --- testing-modules/mockito-simple/pom.xml | 7 +- .../java/com/baeldung/app/api/MessageDTO.java | 31 ----- .../baeldung/app/rest/FlowerController.java | 27 ---- .../baeldung/app/rest/MessageController.java | 34 ----- .../com/baeldung/domain/model/Message.java | 53 ------- .../junit5/mockito/repository/MailClient.java | 9 -- .../junit5/mockito/service/UserService.java | 9 -- .../mockito/argumentcaptor/Credentials.java | 29 ++-- .../argumentmatchers}/Flower.java | 2 +- .../mockito/argumentmatchers/Message.java | 53 +++++++ .../mockito/argumentmatchers/MessageDTO.java | 32 +++++ .../controller/FlowerController.java | 28 ++++ .../controller/MessageController.java | 35 +++++ .../service/FlowerService.java | 2 +- .../service/MessageService.java | 5 +- .../mockito => mockito/junit5}/User.java | 2 +- .../mockito/junit5/repository/MailClient.java | 9 ++ .../junit5}/repository/SettingRepository.java | 2 +- .../junit5}/repository/UserRepository.java | 4 +- .../junit5}/service/DefaultUserService.java | 10 +- .../junit5}/service/Errors.java | 2 +- .../mockito/junit5/service/UserService.java | 9 ++ .../mockito/mockedstatic/StaticUtils.java | 21 ++- .../app/rest/MessageControllerUnitTest.java | 56 -------- .../java/com/baeldung/mockito/FinalList.java | 8 +- .../baeldung/mockito/MockFinalsUnitTest.java | 32 ----- .../mockito/MockitoAnnotationUnitTest.java | 127 ----------------- ...ckitoAnnotationsUninitializedUnitTest.java | 23 ---- .../mockito/MockitoExceptionUnitTest.java | 71 ---------- .../baeldung/mockito/MockitoMockUnitTest.java | 67 --------- .../MockitoVerifyExamplesUnitTest.java | 130 ------------------ .../MockitoWhenThenExamplesUnitTest.java | 108 --------------- .../com/baeldung/mockito/MyDictionary.java | 28 ++-- .../java/com/baeldung/mockito/MyList.java | 30 ++-- .../MockitoAnnotationUnitTest.java | 130 ++++++++++++++++++ ...tionsInitWithMockitoJUnitRuleUnitTest.java | 22 ++- ...ckitoAnnotationsInjectIntoSpyUnitTest.java | 38 ++--- ...ckitoAnnotationsUninitializedUnitTest.java | 22 +++ .../argumentcaptor/EmailServiceUnitTest.java | 118 ++++++++-------- .../FlowerControllerUnitTest.java | 38 ++--- .../MessageControllerUnitTest.java | 54 ++++++++ .../argumentmatchers}/MessageMatcher.java | 3 +- .../MockitoWhenThenExamplesUnitTest.java | 105 ++++++++++++++ .../exceptions/MockitoExceptionUnitTest.java | 57 ++++++++ .../junit5}/UserServiceUnitTest.java | 23 ++-- .../mockedstatic/MockedStaticUnitTest.java | 39 ------ .../mockito/mockfinal/MockFinalsUnitTest.java | 31 +++++ .../MockitoMockMethodsUnitTest.java | 73 ++++++++++ .../mockstatic/MockStaticUnitTest.java | 41 ++++++ .../mockito/spy/MockitoSpyUnitTest.java | 87 ++++++------ .../verify/MockitoVerifyExamplesUnitTest.java | 126 +++++++++++++++++ .../MockitoVoidMethodsUnitTest.java | 104 +++++++------- 52 files changed, 1103 insertions(+), 1103 deletions(-) delete mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/app/api/MessageDTO.java delete mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/app/rest/FlowerController.java delete mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/app/rest/MessageController.java delete mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/domain/model/Message.java delete mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java delete mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/UserService.java rename testing-modules/mockito-simple/src/main/java/com/baeldung/{app/api => mockito/argumentmatchers}/Flower.java (90%) create mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java create mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java create mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java create mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java rename testing-modules/mockito-simple/src/main/java/com/baeldung/{domain => mockito/argumentmatchers}/service/FlowerService.java (91%) rename testing-modules/mockito-simple/src/main/java/com/baeldung/{domain => mockito/argumentmatchers}/service/MessageService.java (61%) rename testing-modules/mockito-simple/src/main/java/com/baeldung/{junit5/mockito => mockito/junit5}/User.java (95%) create mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java rename testing-modules/mockito-simple/src/main/java/com/baeldung/{junit5/mockito => mockito/junit5}/repository/SettingRepository.java (68%) rename testing-modules/mockito-simple/src/main/java/com/baeldung/{junit5/mockito => mockito/junit5}/repository/UserRepository.java (58%) rename testing-modules/mockito-simple/src/main/java/com/baeldung/{junit5/mockito => mockito/junit5}/service/DefaultUserService.java (82%) rename testing-modules/mockito-simple/src/main/java/com/baeldung/{junit5/mockito => mockito/junit5}/service/Errors.java (87%) create mode 100644 testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java delete mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java delete mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockFinalsUnitTest.java delete mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java delete mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java delete mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoExceptionUnitTest.java delete mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java delete mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java delete mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoWhenThenExamplesUnitTest.java create mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java rename testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/{ => annotations}/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java (51%) rename testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/{ => annotations}/MockitoAnnotationsInjectIntoSpyUnitTest.java (52%) create mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java rename testing-modules/mockito-simple/src/test/java/com/baeldung/{app/rest => mockito/argumentmatchers}/FlowerControllerUnitTest.java (65%) create mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java rename testing-modules/mockito-simple/src/test/java/com/baeldung/{domain/util => mockito/argumentmatchers}/MessageMatcher.java (86%) create mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java create mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java rename testing-modules/mockito-simple/src/test/java/com/baeldung/{junit5/mockito => mockito/junit5}/UserServiceUnitTest.java (87%) delete mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java create mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java create mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java create mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java create mode 100644 testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java diff --git a/testing-modules/mockito-simple/pom.xml b/testing-modules/mockito-simple/pom.xml index 3bfca2db2a..f96cb98d46 100644 --- a/testing-modules/mockito-simple/pom.xml +++ b/testing-modules/mockito-simple/pom.xml @@ -29,12 +29,14 @@ spring-context ${spring-framework.version} + org.apache.commons commons-lang3 ${commons-lang3.version} + org.mockito @@ -55,9 +57,8 @@ - 5.3.20 - - 4.6.1 + 6.0.8 + 5.3.1 \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/app/api/MessageDTO.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/app/api/MessageDTO.java deleted file mode 100644 index 1d9da244b0..0000000000 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/app/api/MessageDTO.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.app.api; - -public class MessageDTO { - private String from; - private String to; - private String text; - - public String getFrom() { - return from; - } - - public void setFrom(String from) { - this.from = from; - } - - public String getTo() { - return to; - } - - public void setTo(String to) { - this.to = to; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } -} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/app/rest/FlowerController.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/app/rest/FlowerController.java deleted file mode 100644 index 10f602088c..0000000000 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/app/rest/FlowerController.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.app.rest; - -import com.baeldung.app.api.Flower; -import com.baeldung.domain.service.FlowerService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping("/flowers") -public class FlowerController { - - @Autowired - private FlowerService flowerService; - - @PostMapping("/isAFlower") - public String isAFlower (@RequestBody String flower) { - return flowerService.analyze(flower); - } - - @PostMapping("/isABigFlower") - public Boolean isABigFlower (@RequestBody Flower flower) { - return flowerService.isABigFlower(flower.getName(), flower.getPetals()); - } -} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/app/rest/MessageController.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/app/rest/MessageController.java deleted file mode 100644 index 6911197197..0000000000 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/app/rest/MessageController.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.app.rest; - -import com.baeldung.app.api.MessageDTO; -import com.baeldung.domain.model.Message; -import com.baeldung.domain.service.MessageService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; - -import java.time.Instant; -import java.util.Date; -import java.util.UUID; - -@Controller -@RequestMapping("/message") -public class MessageController { - - @Autowired - private MessageService messageService; - - @PostMapping - public Message createMessage (@RequestBody MessageDTO messageDTO) { - Message message = new Message(); - message.setText(messageDTO.getText()); - message.setFrom(messageDTO.getFrom()); - message.setTo(messageDTO.getTo()); - message.setDate(Date.from(Instant.now())); - message.setId(UUID.randomUUID()); - - return messageService.deliverMessage(message); - } -} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/domain/model/Message.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/domain/model/Message.java deleted file mode 100644 index a516d5619b..0000000000 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/domain/model/Message.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.domain.model; - -import java.util.Date; -import java.util.UUID; - -public class Message { - - private String from; - private String to; - private String text; - private Date date; - private UUID id; - - public String getFrom() { - return from; - } - - public void setFrom(String from) { - this.from = from; - } - - public String getTo() { - return to; - } - - public void setTo(String to) { - this.to = to; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } -} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java deleted file mode 100644 index d10169ef7a..0000000000 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.junit5.mockito.repository; - -import com.baeldung.junit5.mockito.User; - -public interface MailClient { - - void sendUserRegistrationMail(User user); - -} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/UserService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/UserService.java deleted file mode 100644 index 326d019b4a..0000000000 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/UserService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.junit5.mockito.service; - -import com.baeldung.junit5.mockito.User; - -public interface UserService { - - User register(User user); - -} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java index d5d60bb6fc..3ec86b4499 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java @@ -1,14 +1,25 @@ package com.baeldung.mockito.argumentcaptor; public class Credentials { - private final String name; - private final String password; - private final String key; + private final String name; + private final String password; + private final String key; - public Credentials(String name, String password, String key) { - this.name = name; - this.password = password; - this.key = key; - } + public Credentials(String name, String password, String key) { + this.name = name; + this.password = password; + this.key = key; + } + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String getKey() { + return key; + } } - diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/app/api/Flower.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Flower.java similarity index 90% rename from testing-modules/mockito-simple/src/main/java/com/baeldung/app/api/Flower.java rename to testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Flower.java index dc1c36e3ff..8bfd0d1b02 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/app/api/Flower.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Flower.java @@ -1,4 +1,4 @@ -package com.baeldung.app.api; +package com.baeldung.mockito.argumentmatchers; public class Flower { diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java new file mode 100644 index 0000000000..13d285de8d --- /dev/null +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java @@ -0,0 +1,53 @@ +package com.baeldung.mockito.argumentmatchers; + +import java.util.Date; +import java.util.UUID; + +public class Message { + + private String from; + private String to; + private String text; + private Date date; + private UUID id; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } +} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java new file mode 100644 index 0000000000..76989e758c --- /dev/null +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java @@ -0,0 +1,32 @@ +package com.baeldung.mockito.argumentmatchers; + +public class MessageDTO { + + private String from; + private String to; + private String text; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java new file mode 100644 index 0000000000..29c8dbb15d --- /dev/null +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java @@ -0,0 +1,28 @@ +package com.baeldung.mockito.argumentmatchers.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +import com.baeldung.mockito.argumentmatchers.Flower; +import com.baeldung.mockito.argumentmatchers.service.FlowerService; + +@Controller +@RequestMapping("/flowers") +public class FlowerController { + + @Autowired + private FlowerService flowerService; + + @PostMapping("/isAFlower") + public String isAFlower(@RequestBody String flower) { + return flowerService.analyze(flower); + } + + @PostMapping("/isABigFlower") + public Boolean isABigFlower(@RequestBody Flower flower) { + return flowerService.isABigFlower(flower.getName(), flower.getPetals()); + } +} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java new file mode 100644 index 0000000000..16eb041044 --- /dev/null +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java @@ -0,0 +1,35 @@ +package com.baeldung.mockito.argumentmatchers.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +import com.baeldung.mockito.argumentmatchers.Message; +import com.baeldung.mockito.argumentmatchers.MessageDTO; +import com.baeldung.mockito.argumentmatchers.service.MessageService; + +import java.time.Instant; +import java.util.Date; +import java.util.UUID; + +@Controller +@RequestMapping("/message") +public class MessageController { + + @Autowired + private MessageService messageService; + + @PostMapping + public Message createMessage(@RequestBody MessageDTO messageDTO) { + Message message = new Message(); + message.setText(messageDTO.getText()); + message.setFrom(messageDTO.getFrom()); + message.setTo(messageDTO.getTo()); + message.setDate(Date.from(Instant.now())); + message.setId(UUID.randomUUID()); + + return messageService.deliverMessage(message); + } +} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/domain/service/FlowerService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/FlowerService.java similarity index 91% rename from testing-modules/mockito-simple/src/main/java/com/baeldung/domain/service/FlowerService.java rename to testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/FlowerService.java index 74a9308890..364f2b57d7 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/domain/service/FlowerService.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/FlowerService.java @@ -1,4 +1,4 @@ -package com.baeldung.domain.service; +package com.baeldung.mockito.argumentmatchers.service; import org.springframework.stereotype.Service; diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/domain/service/MessageService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java similarity index 61% rename from testing-modules/mockito-simple/src/main/java/com/baeldung/domain/service/MessageService.java rename to testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java index d156c59571..beeccf763a 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/domain/service/MessageService.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java @@ -1,8 +1,9 @@ -package com.baeldung.domain.service; +package com.baeldung.mockito.argumentmatchers.service; -import com.baeldung.domain.model.Message; import org.springframework.stereotype.Service; +import com.baeldung.mockito.argumentmatchers.Message; + @Service public class MessageService { diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/User.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/User.java similarity index 95% rename from testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/User.java rename to testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/User.java index 4276fd62b9..0f0b93e30b 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/User.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/User.java @@ -1,4 +1,4 @@ -package com.baeldung.junit5.mockito; +package com.baeldung.mockito.junit5; public class User { diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java new file mode 100644 index 0000000000..722c4fff71 --- /dev/null +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java @@ -0,0 +1,9 @@ +package com.baeldung.mockito.junit5.repository; + +import com.baeldung.mockito.junit5.User; + +public interface MailClient { + + void sendUserRegistrationMail(User user); + +} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/SettingRepository.java similarity index 68% rename from testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java rename to testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/SettingRepository.java index 23ae8fa35c..78249c9fd9 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/SettingRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.junit5.mockito.repository; +package com.baeldung.mockito.junit5.repository; public interface SettingRepository { diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/UserRepository.java similarity index 58% rename from testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java rename to testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/UserRepository.java index e1b84c774b..5ce624b73b 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/UserRepository.java @@ -1,6 +1,6 @@ -package com.baeldung.junit5.mockito.repository; +package com.baeldung.mockito.junit5.repository; -import com.baeldung.junit5.mockito.User; +import com.baeldung.mockito.junit5.User; public interface UserRepository { diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/DefaultUserService.java similarity index 82% rename from testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java rename to testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/DefaultUserService.java index 888edbd710..c239bba2b3 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/DefaultUserService.java @@ -1,9 +1,9 @@ -package com.baeldung.junit5.mockito.service; +package com.baeldung.mockito.junit5.service; -import com.baeldung.junit5.mockito.User; -import com.baeldung.junit5.mockito.repository.MailClient; -import com.baeldung.junit5.mockito.repository.SettingRepository; -import com.baeldung.junit5.mockito.repository.UserRepository; +import com.baeldung.mockito.junit5.User; +import com.baeldung.mockito.junit5.repository.MailClient; +import com.baeldung.mockito.junit5.repository.SettingRepository; +import com.baeldung.mockito.junit5.repository.UserRepository; public class DefaultUserService implements UserService { diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/Errors.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/Errors.java similarity index 87% rename from testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/Errors.java rename to testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/Errors.java index 28283754a3..c46688f484 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/junit5/mockito/service/Errors.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/Errors.java @@ -1,4 +1,4 @@ -package com.baeldung.junit5.mockito.service; +package com.baeldung.mockito.junit5.service; public class Errors { diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java new file mode 100644 index 0000000000..b781747a45 --- /dev/null +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java @@ -0,0 +1,9 @@ +package com.baeldung.mockito.junit5.service; + +import com.baeldung.mockito.junit5.User; + +public interface UserService { + + User register(User user); + +} diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java index 2e2f5ead33..e7ee3a0aa6 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java @@ -6,17 +6,16 @@ import java.util.stream.IntStream; public class StaticUtils { - private StaticUtils() { - } + private StaticUtils() { + } - public static List range(int start, int end) { - return IntStream.range(start, end) - .boxed() - .collect(Collectors.toList()); - } - - public static String name() { - return "Baeldung"; - } + public static List range(int start, int end) { + return IntStream.range(start, end) + .boxed() + .collect(Collectors.toList()); + } + public static String name() { + return "Baeldung"; + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java deleted file mode 100644 index 84b5bf241e..0000000000 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.app.rest; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import com.baeldung.app.api.MessageDTO; -import com.baeldung.domain.model.Message; -import com.baeldung.domain.service.MessageService; -import com.baeldung.domain.util.MessageMatcher; - -@ExtendWith(MockitoExtension.class) -class MessageControllerUnitTest { - - @InjectMocks - private MessageController messageController; - - @Mock - private MessageService messageService; - - @Test - void givenMsg_whenVerifyUsingAnyMatcher_thenOk() { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setFrom("me"); - messageDTO.setTo("you"); - messageDTO.setText("Hello, you!"); - - messageController.createMessage(messageDTO); - - verify(messageService, times(1)).deliverMessage(any(Message.class)); - } - - @Test - void givenMsg_whenVerifyUsingMessageMatcher_thenOk() { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setFrom("me"); - messageDTO.setTo("you"); - messageDTO.setText("Hello, you!"); - - messageController.createMessage(messageDTO); - - Message message = new Message(); - message.setFrom("me"); - message.setTo("you"); - message.setText("Hello, you!"); - - verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message))); - } -} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java index 27b7534978..87e8b5de77 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java @@ -2,9 +2,9 @@ package com.baeldung.mockito; public final class FinalList extends MyList { - @Override - public int size() { - return 1; - } + @Override + public int size() { + return 1; + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockFinalsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockFinalsUnitTest.java deleted file mode 100644 index a4b2bd03b4..0000000000 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockFinalsUnitTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.mockito; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.jupiter.api.Test; - -class MockFinalsUnitTest { - - @Test - void whenMockFinalMethodMockWorks() { - - MyList myList = new MyList(); - - MyList mock = mock(MyList.class); - when(mock.finalMethod()).thenReturn(1); - - assertThat(mock.finalMethod()).isNotEqualTo(myList.finalMethod()); - } - - @Test - public void whenMockFinalClassMockWorks() { - - FinalList finalList = new FinalList(); - - FinalList mock = mock(FinalList.class); - when(mock.size()).thenReturn(2); - - assertThat(mock.size()).isNotEqualTo(finalList.size()); - } -} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java deleted file mode 100644 index acfd87e047..0000000000 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.baeldung.mockito; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class MockitoAnnotationUnitTest { - - @Mock - private List mockedList; - - @Spy - private List spiedList = new ArrayList<>(); - - // Use either @RunWith(MockitoJUnitRunner.class) or manually openMocks in the @Before method - /* - @Before - public void init() { - MockitoAnnotations.openMocks(this); - } - */ - - // tests - - @Test - void whenNotUseMockAnnotation_thenCorrect() { - final List mockList = mock(List.class); - mockList.add("one"); - verify(mockList).add("one"); - assertEquals(0, mockList.size()); - - when(mockList.size()).thenReturn(100); - assertEquals(100, mockList.size()); - } - - @Test - void whenUseMockAnnotation_thenMockIsInjected() { - mockedList.add("one"); - verify(mockedList).add("one"); - assertEquals(0, mockedList.size()); - - when(mockedList.size()).thenReturn(100); - assertEquals(100, mockedList.size()); - } - - @Test - void whenNotUseSpyAnnotation_thenCorrect() { - final List spyList = spy(new ArrayList()); - spyList.add("one"); - spyList.add("two"); - - verify(spyList).add("one"); - verify(spyList).add("two"); - - assertEquals(2, spyList.size()); - - doReturn(100).when(spyList).size(); - assertEquals(100, spyList.size()); - } - - @Test - void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() { - spiedList.add("one"); - spiedList.add("two"); - - verify(spiedList).add("one"); - verify(spiedList).add("two"); - - assertEquals(2, spiedList.size()); - - doReturn(100).when(spiedList).size(); - assertEquals(100, spiedList.size()); - } - - @Test - void whenNotUseCaptorAnnotation_thenCorrect() { - final List mockList = mock(List.class); - final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class); - mockList.add("one"); - verify(mockList).add(arg.capture()); - - assertEquals("one", arg.getValue()); - } - - @Captor - private - ArgumentCaptor argCaptor; - - @Test - void whenUseCaptorAnnotation_thenTheSame() { - mockedList.add("one"); - verify(mockedList).add(argCaptor.capture()); - - assertEquals("one", argCaptor.getValue()); - } - - @Mock - private Map wordMap; - - @InjectMocks - private MyDictionary dic = new MyDictionary(); - - @Test - void whenUseInjectMocksAnnotation_thenCorrect() { - when(wordMap.get("aWord")).thenReturn("aMeaning"); - - assertEquals("aMeaning", dic.getMeaning("aWord")); - } - -} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java deleted file mode 100644 index 10b0aa6626..0000000000 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.mockito; - - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.when; - -import org.junit.jupiter.api.Test; -import org.mockito.Mock; - -import java.util.List; - -class MockitoAnnotationsUninitializedUnitTest { - - @Mock - List mockedList; - - @Test - void whenMockitoAnnotationsUninitialized_thenNPEThrown() { - assertThrows(NullPointerException.class, () -> { - when(mockedList.size()).thenReturn(1); - }); - } -} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoExceptionUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoExceptionUnitTest.java deleted file mode 100644 index 843edd8d0a..0000000000 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoExceptionUnitTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.mockito; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class MockitoExceptionUnitTest { - - @Test - void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { - MyDictionary dictMock = mock(MyDictionary.class); - when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class); - assertThrows(NullPointerException.class, () -> { - dictMock.getMeaning("word"); - }); - - } - - @Test - void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() { - MyDictionary dictMock = mock(MyDictionary.class); - doThrow(IllegalStateException.class).when(dictMock) - .add(anyString(), anyString()); - assertThrows(IllegalStateException.class, () -> { - dictMock.add("word", "meaning"); - }); - - } - - @Test - void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { - MyDictionary dictMock = mock(MyDictionary.class); - when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred")); - assertThrows(NullPointerException.class, () -> { - dictMock.getMeaning("word"); - }); - - } - - @Test - void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { - MyDictionary dictMock = mock(MyDictionary.class); - doThrow(new IllegalStateException("Error occurred")).when(dictMock) - .add(anyString(), anyString()); - assertThrows(IllegalStateException.class, () -> { - dictMock.add("word", "meaning"); - }); - - } - - // ===== - - @Test - void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { - MyDictionary dict = new MyDictionary(); - MyDictionary spy = Mockito.spy(dict); - when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class); - assertThrows(NullPointerException.class, () -> { - spy.getMeaning("word"); - }); - } -} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java deleted file mode 100644 index 6e9167f0d0..0000000000 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.mockito; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; - -import org.junit.jupiter.api.Test; -import org.mockito.MockSettings; -import org.mockito.exceptions.verification.TooFewActualInvocations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -class MockitoMockUnitTest { - - @Test - void whenUsingSimpleMock_thenCorrect() { - MyList listMock = mock(MyList.class); - when(listMock.add(anyString())).thenReturn(false); - boolean added = listMock.add(randomAlphabetic(6)); - - verify(listMock).add(anyString()); - assertThat(added).isFalse(); - } - - @Test - void whenUsingMockWithName_thenCorrect() { - MyList listMock = mock(MyList.class, "myMock"); - when(listMock.add(anyString())).thenReturn(false); - listMock.add(randomAlphabetic(6)); - - assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString())) - .isInstanceOf(TooFewActualInvocations.class) - .hasMessageContaining("myMock.add"); - } - - private static class CustomAnswer implements Answer { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return false; - } - } - - @Test - void whenUsingMockWithAnswer_thenCorrect() { - MyList listMock = mock(MyList.class, new CustomAnswer()); - boolean added = listMock.add(randomAlphabetic(6)); - - verify(listMock).add(anyString()); - assertThat(added).isFalse(); - } - - @Test - void whenUsingMockWithSettings_thenCorrect() { - MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer()); - MyList listMock = mock(MyList.class, customSettings); - boolean added = listMock.add(randomAlphabetic(6)); - - verify(listMock).add(anyString()); - assertThat(added).isFalse(); - } -} \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java deleted file mode 100644 index a236fc7cfc..0000000000 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.baeldung.mockito; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.atMost; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.InOrder; -import org.mockito.exceptions.verification.NoInteractionsWanted; - -import com.google.common.collect.Lists; - -class MockitoVerifyExamplesUnitTest { - - // tests - - @Test - final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); - verify(mockedList).size(); - } - - @Test - final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); - verify(mockedList, times(1)).size(); - } - - @Test - final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - verifyNoInteractions(mockedList); - } - - @Test - final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - verify(mockedList, times(0)).size(); - } - - @Test - final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() { - final List mockedList = mock(MyList.class); - mockedList.size(); - mockedList.clear(); - - verify(mockedList).size(); - assertThrows(NoInteractionsWanted.class, () -> { - verifyNoMoreInteractions(mockedList); - }); - - } - - @Test - final void whenVerifyingOrderOfInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); - mockedList.add("a parameter"); - mockedList.clear(); - - final InOrder inOrder = inOrder(mockedList); - inOrder.verify(mockedList).size(); - inOrder.verify(mockedList).add("a parameter"); - inOrder.verify(mockedList).clear(); - } - - @Test - final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); - - verify(mockedList, never()).clear(); - } - - @Test - final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.clear(); - mockedList.clear(); - mockedList.clear(); - - verify(mockedList, atLeast(1)).clear(); - verify(mockedList, atMost(10)).clear(); - } - - // with arguments - - @Test - final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.add("test"); - - verify(mockedList).add("test"); - } - - @Test - final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.add("test"); - - verify(mockedList).add(anyString()); - } - - @Test - final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.addAll(Lists.newArrayList("someElement")); - - final ArgumentCaptor> argumentCaptor = ArgumentCaptor.forClass(List.class); - verify(mockedList).addAll(argumentCaptor.capture()); - - final List capturedArgument = argumentCaptor.getValue(); - assertThat(capturedArgument).contains("someElement"); - } - -} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoWhenThenExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoWhenThenExamplesUnitTest.java deleted file mode 100644 index c570629ccd..0000000000 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoWhenThenExamplesUnitTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.baeldung.mockito; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import org.junit.jupiter.api.Test; - - -class MockitoWhenThenExamplesUnitTest { - - @Test - final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() { - final MyList listMock = mock(MyList.class); - when(listMock.add(anyString())).thenReturn(false); - - final boolean added = listMock.add(randomAlphabetic(6)); - assertThat(added).isFalse(); - } - - @Test - final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() { - final MyList listMock = mock(MyList.class); - doReturn(false).when(listMock).add(anyString()); - - final boolean added = listMock.add(randomAlphabetic(6)); - assertThat(added).isFalse(); - } - - @Test - final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() { - final MyList listMock = mock(MyList.class); - when(listMock.add(anyString())).thenThrow(IllegalStateException.class); - - assertThrows(IllegalStateException.class, () -> { - listMock.add(randomAlphabetic(6)); - }); - - } - - @Test - final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() { - final MyList listMock = mock(MyList.class); - when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class); - - listMock.add(randomAlphabetic(6)); - } - - @Test - final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() { - final MyList listMock = mock(MyList.class); - doThrow(NullPointerException.class).when(listMock).clear(); - - assertThrows(NullPointerException.class, () -> { - listMock.clear(); - }); - - } - - @Test - final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() { - final MyList listMock = mock(MyList.class); - when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class); - - assertThrows(IllegalStateException.class, () -> { - listMock.add(randomAlphabetic(6)); - listMock.add(randomAlphabetic(6)); - }); - - } - - @Test - final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() { - final MyList instance = new MyList(); - final MyList spy = spy(instance); - - doThrow(NullPointerException.class).when(spy).size(); - assertThrows(NullPointerException.class, () -> { - spy.size(); - }); - - } - - @Test - final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() { - final MyList listMock = mock(MyList.class); - when(listMock.size()).thenCallRealMethod(); - - assertThat(listMock).hasSize(1); - } - - @Test - final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() { - final MyList listMock = mock(MyList.class); - doAnswer(invocation -> "Always the same").when(listMock).get(anyInt()); - - final String element = listMock.get(1); - assertThat(element).isEqualTo("Always the same"); - } -} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java index 92a4498696..6877d7fb6a 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java @@ -3,23 +3,23 @@ package com.baeldung.mockito; import java.util.HashMap; import java.util.Map; -class MyDictionary { +public class MyDictionary { - private Map wordMap; + private Map wordMap; - MyDictionary() { - wordMap = new HashMap<>(); - } + public MyDictionary() { + wordMap = new HashMap<>(); + } - MyDictionary(Map wordMap) { - this.wordMap = wordMap; - } + public MyDictionary(Map wordMap) { + this.wordMap = wordMap; + } - public void add(final String word, final String meaning) { - wordMap.put(word, meaning); - } + public void add(final String word, final String meaning) { + wordMap.put(word, meaning); + } - String getMeaning(final String word) { - return wordMap.get(word); - } + public String getMeaning(final String word) { + return wordMap.get(word); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java index ac3a76e04a..8324af8ae8 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java @@ -4,22 +4,22 @@ import java.util.AbstractList; public class MyList extends AbstractList { - @Override - public String get(final int index) { - return null; - } + @Override + public String get(final int index) { + return null; + } - @Override - public int size() { - return 1; - } + @Override + public int size() { + return 1; + } - @Override - public void add(int index, String element) { - // no-op - } + @Override + public void add(int index, String element) { + // no-op + } - final public int finalMethod() { - return 0; - } + final public int finalMethod() { + return 0; + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java new file mode 100644 index 0000000000..5e12b5c34a --- /dev/null +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java @@ -0,0 +1,130 @@ +package com.baeldung.mockito.annotations; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.baeldung.mockito.MyDictionary; + +@ExtendWith(MockitoExtension.class) +class MockitoAnnotationUnitTest { + + @Mock + private List mockedList; + + @Spy + private List spiedList = new ArrayList<>(); + + // Use either @ExtendWith(MockitoExtension.class) or manually openMocks in the @BeforeEach method + /* + @BeforeEach + public void init() { + MockitoAnnotations.openMocks(this); + } + */ + + // tests + + @Test + void whenNotUseMockAnnotation_thenCorrect() { + final List mockList = mock(ArrayList.class); + + mockList.add("one"); + verify(mockList).add("one"); + assertEquals(0, mockList.size()); + + when(mockList.size()).thenReturn(100); + assertEquals(100, mockList.size()); + } + + @Test + void whenUseMockAnnotation_thenMockIsInjected() { + mockedList.add("one"); + verify(mockedList).add("one"); + assertEquals(0, mockedList.size()); + + when(mockedList.size()).thenReturn(100); + assertEquals(100, mockedList.size()); + } + + @Test + void whenNotUseSpyAnnotation_thenCorrect() { + final List spyList = spy(new ArrayList()); + + spyList.add("one"); + spyList.add("two"); + + verify(spyList).add("one"); + verify(spyList).add("two"); + + assertEquals(2, spyList.size()); + + doReturn(100).when(spyList).size(); + assertEquals(100, spyList.size()); + } + + @Test + void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() { + spiedList.add("one"); + spiedList.add("two"); + + verify(spiedList).add("one"); + verify(spiedList).add("two"); + + assertEquals(2, spiedList.size()); + + doReturn(100).when(spiedList).size(); + assertEquals(100, spiedList.size()); + } + + @Test + void whenNotUseCaptorAnnotation_thenCorrect() { + final List mockList = mock(List.class); + final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class); + + mockList.add("one"); + verify(mockList).add(arg.capture()); + + assertEquals("one", arg.getValue()); + } + + @Captor + private ArgumentCaptor argCaptor; + + @Test + void whenUseCaptorAnnotation_thenTheSame() { + mockedList.add("one"); + verify(mockedList).add(argCaptor.capture()); + + assertEquals("one", argCaptor.getValue()); + } + + @Mock + private Map wordMap; + + @InjectMocks + private MyDictionary dic = new MyDictionary(); + + @Test + void whenUseInjectMocksAnnotation_thenCorrect() { + when(wordMap.get("aWord")).thenReturn("aMeaning"); + + assertEquals("aMeaning", dic.getMeaning("aWord")); + } +} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java similarity index 51% rename from testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java rename to testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java index 512f538a58..437462fcb4 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.mockito; +package com.baeldung.mockito.annotations; import org.junit.Rule; import org.junit.Test; @@ -6,25 +6,23 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; - import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; - public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest { - @Rule - public MockitoRule initRule = MockitoJUnit.rule(); + @Rule + public MockitoRule initRule = MockitoJUnit.rule(); - @Mock - private List mockedList; + @Mock + private List mockedList; - @Test - public void whenUsingMockitoJUnitRule_thenMocksInitialized() { - when(mockedList.size()).thenReturn(41); + @Test + public void whenUsingMockitoJUnitRule_thenMocksInitialized() { + when(mockedList.size()).thenReturn(41); - assertThat(mockedList).hasSize(41); - } + assertThat(mockedList).hasSize(41); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInjectIntoSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java similarity index 52% rename from testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInjectIntoSpyUnitTest.java rename to testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java index 89a253c855..44b8d5ec8f 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInjectIntoSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java @@ -1,11 +1,12 @@ -package com.baeldung.mockito; - +package com.baeldung.mockito.annotations; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.openMocks; +import java.util.Map; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -13,30 +14,29 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.Map; - +import com.baeldung.mockito.MyDictionary; @ExtendWith(MockitoExtension.class) class MockitoAnnotationsInjectIntoSpyUnitTest { - @BeforeEach - public void init() { - openMocks(this); - spyDic = spy(new MyDictionary(wordMap)); - } + @BeforeEach + public void init() { + openMocks(this); + spyDic = spy(new MyDictionary(wordMap)); + } - @Mock - private Map wordMap; + @Mock + private Map wordMap; - @InjectMocks - private MyDictionary dic = new MyDictionary(); + @InjectMocks + private MyDictionary dic = new MyDictionary(); - private MyDictionary spyDic; + private MyDictionary spyDic; - @Test - void whenUseInjectMocksAnnotation_thenCorrect() { - when(wordMap.get("aWord")).thenReturn("aMeaning"); + @Test + void whenUseInjectMocksAnnotation_thenCorrect() { + when(wordMap.get("aWord")).thenReturn("aMeaning"); - assertEquals("aMeaning", spyDic.getMeaning("aWord")); - } + assertEquals("aMeaning", spyDic.getMeaning("aWord")); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java new file mode 100644 index 0000000000..1b7db32c37 --- /dev/null +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.mockito.annotations; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.mockito.Mock; + +class MockitoAnnotationsUninitializedUnitTest { + + @Mock + List mockedList; + + @Test + void whenMockitoAnnotationsUninitialized_thenNPEThrown() { + assertThrows(NullPointerException.class, () -> { + when(mockedList.size()).thenReturn(1); + }); + } +} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java index 36c26659a6..a0d542e152 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java @@ -18,84 +18,84 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class EmailServiceUnitTest { - @Mock - DeliveryPlatform platform; + @Mock + DeliveryPlatform platform; - @InjectMocks - EmailService emailService; + @InjectMocks + EmailService emailService; - @Captor - ArgumentCaptor emailCaptor; + @Captor + ArgumentCaptor emailCaptor; - @Captor - ArgumentCaptor credentialsCaptor; + @Captor + ArgumentCaptor credentialsCaptor; - @Test - void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() { - String to = "info@baeldung.com"; - String subject = "Using ArgumentCaptor"; - String body = "Hey, let'use ArgumentCaptor"; + @Test + void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() { + String to = "info@baeldung.com"; + String subject = "Using ArgumentCaptor"; + String body = "Hey, let'use ArgumentCaptor"; - emailService.send(to, subject, body, false); + emailService.send(to, subject, body, false); - verify(platform).deliver(emailCaptor.capture()); - Email emailCaptorValue = emailCaptor.getValue(); - assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY); - } + verify(platform).deliver(emailCaptor.capture()); + Email emailCaptorValue = emailCaptor.getValue(); + assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY); + } - @Test - void whenDoesSupportHtml_expectHTMLEmailFormat() { - String to = "info@baeldung.com"; - String subject = "Using ArgumentCaptor"; - String body = "Hey, let'use ArgumentCaptor"; + @Test + void whenDoesSupportHtml_expectHTMLEmailFormat() { + String to = "info@baeldung.com"; + String subject = "Using ArgumentCaptor"; + String body = "Hey, let'use ArgumentCaptor"; - emailService.send(to, subject, body, true); + emailService.send(to, subject, body, true); - verify(platform).deliver(emailCaptor.capture()); - Email value = emailCaptor.getValue(); - assertThat(value.getFormat()).isEqualTo(Format.HTML); - } + verify(platform).deliver(emailCaptor.capture()); + Email value = emailCaptor.getValue(); + assertThat(value.getFormat()).isEqualTo(Format.HTML); + } - @Test - void whenServiceRunning_expectUpResponse() { - when(platform.getServiceStatus()).thenReturn("OK"); + @Test + void whenServiceRunning_expectUpResponse() { + when(platform.getServiceStatus()).thenReturn("OK"); - ServiceStatus serviceStatus = emailService.checkServiceStatus(); + ServiceStatus serviceStatus = emailService.checkServiceStatus(); - assertThat(serviceStatus).isEqualTo(ServiceStatus.UP); - } + assertThat(serviceStatus).isEqualTo(ServiceStatus.UP); + } - @Test - void whenServiceNotRunning_expectDownResponse() { - when(platform.getServiceStatus()).thenReturn("Error"); + @Test + void whenServiceNotRunning_expectDownResponse() { + when(platform.getServiceStatus()).thenReturn("Error"); - ServiceStatus serviceStatus = emailService.checkServiceStatus(); + ServiceStatus serviceStatus = emailService.checkServiceStatus(); - assertThat(serviceStatus).isEqualTo(ServiceStatus.DOWN); - } + assertThat(serviceStatus).isEqualTo(ServiceStatus.DOWN); + } - @Test - void whenUsingArgumentMatcherForValidCredentials_expectTrue() { - Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); - when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); + @Test + void whenUsingArgumentMatcherForValidCredentials_expectTrue() { + Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); + when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); - assertTrue(emailService.authenticatedSuccessfully(credentials)); - } + assertTrue(emailService.authenticatedSuccessfully(credentials)); + } - @Test - void whenUsingArgumentCaptorForValidCredentials_expectTrue() { - Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); - when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); + @Test + void whenUsingArgumentCaptorForValidCredentials_expectTrue() { + Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); + when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); - assertTrue(emailService.authenticatedSuccessfully(credentials)); - assertThat(credentialsCaptor.getValue()).isEqualTo(credentials); - } + assertTrue(emailService.authenticatedSuccessfully(credentials)); + assertThat(credentialsCaptor.getValue()).isEqualTo(credentials); + } - @Test - void whenNotAuthenticated_expectFalse() { - Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key"); - when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); + @Test + void whenNotAuthenticated_expectFalse() { + Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key"); + when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); - assertFalse(emailService.authenticatedSuccessfully(credentials)); - } + assertFalse(emailService.authenticatedSuccessfully(credentials)); + } } \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java similarity index 65% rename from testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java rename to testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java index d611cd9e45..5db7f2e112 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.app.rest; +package com.baeldung.mockito.argumentmatchers; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -18,8 +18,8 @@ import org.mockito.Mock; import org.mockito.exceptions.misusing.InvalidUseOfMatchersException; import org.mockito.junit.jupiter.MockitoExtension; -import com.baeldung.app.api.Flower; -import com.baeldung.domain.service.FlowerService; +import com.baeldung.mockito.argumentmatchers.controller.FlowerController; +import com.baeldung.mockito.argumentmatchers.service.FlowerService; @ExtendWith(MockitoExtension.class) class FlowerControllerUnitTest { @@ -39,7 +39,7 @@ class FlowerControllerUnitTest { } @Test - void givenAnyString_whenUsingArgumentMatcher_thenCorrect() { + void givenAnyFlower_whenUsingArgumentMatcher_thenCorrect() { when(flowerService.analyze(anyString())).thenReturn("Flower"); String response = flowerController.isAFlower("violetta"); @@ -47,19 +47,13 @@ class FlowerControllerUnitTest { } @Test - void whenIncorrectMatchers_thenThrowsError() { - assertThrows(InvalidUseOfMatchersException.class, () -> { - when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true); - }); - - Flower flower = new Flower("poppy", 15); - - Boolean response = flowerController.isABigFlower(flower); - assertThat(response).isFalse(); + void givenIncorrectMatchers_whenUsingArgumentMatchers_thenThrowsError() { + assertThrows(InvalidUseOfMatchersException.class, + () -> when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true)); } @Test - void whenCorrectMatchers_thenCorrect() { + void givenCorrectMatchers_whenUsingArgumentMatchers_thenCorrect() { when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true); Flower flower = new Flower("poppy", 15); @@ -69,26 +63,18 @@ class FlowerControllerUnitTest { } @Test - void whenUsingMatchersAsReturnValue_thenThrowsError() { + void givenMatchersOutsideofStubbing_whenUsingMatchersAsReturnValue_thenThrowsError() { flowerController.isAFlower("poppy"); String orMatcher = or(eq("poppy"), endsWith("y")); - assertThrows(InvalidUseOfMatchersException.class, () -> { - verify(flowerService).analyze(orMatcher); - }); + assertThrows(InvalidUseOfMatchersException.class, + () -> verify(flowerService).analyze(orMatcher)); } @Test - void whenUsingMatchersAsOngoingStubbing_thenCorrect1() { + void givenMatchersAsOngoingStubbing_whenUsingMatchers_thenCorrect() { flowerController.isAFlower("poppy"); verify(flowerService).analyze(or(eq("poppy"), endsWith("y"))); } - - @Test - void whenUsingMatchersAsOngoingStubbing_thenCorrect2() { - flowerController.isAFlower("lily"); - - verify(flowerService).analyze(or(eq("poppy"), endsWith("y"))); - } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java new file mode 100644 index 0000000000..5a64f37696 --- /dev/null +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.mockito.argumentmatchers; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.baeldung.mockito.argumentmatchers.controller.MessageController; +import com.baeldung.mockito.argumentmatchers.service.MessageService; + +@ExtendWith(MockitoExtension.class) +class MessageControllerUnitTest { + + @InjectMocks + private MessageController messageController; + + @Mock + private MessageService messageService; + + @Test + void givenMsg_whenVerifyUsingAnyMatcher_thenOk() { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setFrom("me"); + messageDTO.setTo("you"); + messageDTO.setText("Hello, you!"); + + messageController.createMessage(messageDTO); + + verify(messageService, times(1)).deliverMessage(any(Message.class)); + } + + @Test + void givenMsg_whenVerifyUsingMessageMatcher_thenOk() { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setFrom("me"); + messageDTO.setTo("you"); + messageDTO.setText("Hello, you!"); + + messageController.createMessage(messageDTO); + + Message message = new Message(); + message.setFrom("me"); + message.setTo("you"); + message.setText("Hello, you!"); + + verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message))); + } +} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/domain/util/MessageMatcher.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java similarity index 86% rename from testing-modules/mockito-simple/src/test/java/com/baeldung/domain/util/MessageMatcher.java rename to testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java index 51db07fde7..e50c8ac9d7 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/domain/util/MessageMatcher.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java @@ -1,6 +1,5 @@ -package com.baeldung.domain.util; +package com.baeldung.mockito.argumentmatchers; -import com.baeldung.domain.model.Message; import org.mockito.ArgumentMatcher; public class MessageMatcher implements ArgumentMatcher { diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java new file mode 100644 index 0000000000..4fd70007ab --- /dev/null +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung.mockito.behaviour; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; + +import com.baeldung.mockito.MyList; + +class MockitoWhenThenExamplesUnitTest { + + @Test + final void whenSimpleReturnBehaviourConfigured_thenCorrect() { + final MyList listMock = mock(MyList.class); + when(listMock.add(anyString())).thenReturn(false); + + final boolean added = listMock.add(randomAlphabetic(6)); + assertThat(added).isFalse(); + } + + @Test + final void whenSimpleReturnBehaviourConfiguredAlternatively_thenCorrect() { + final MyList listMock = mock(MyList.class); + doReturn(false).when(listMock).add(anyString()); + + final boolean added = listMock.add(randomAlphabetic(6)); + assertThat(added).isFalse(); + } + + @Test + final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() { + final MyList listMock = mock(MyList.class); + when(listMock.add(anyString())).thenThrow(IllegalStateException.class); + + assertThrows(IllegalStateException.class, () -> listMock.add(randomAlphabetic(6))); + } + + @Test + final void givenMethodHasNoReturnType_whenCallingMethod_thenExceptionIsThrown() { + final MyList listMock = mock(MyList.class); + doThrow(NullPointerException.class).when(listMock).clear(); + + assertThrows(NullPointerException.class, () -> listMock.clear()); + } + + @Test + final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() { + final MyList listMock = mock(MyList.class); + when(listMock.add(anyString())) + .thenReturn(false) + .thenThrow(IllegalStateException.class); + + assertThrows(IllegalStateException.class, () -> { + listMock.add(randomAlphabetic(6)); + listMock.add(randomAlphabetic(6)); + }); + } + + @Test + final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() { + final MyList listMock = mock(MyList.class); + when(listMock.add(anyString())) + .thenReturn(false) + .thenThrow(IllegalStateException.class); + + assertThatNoException().isThrownBy(() -> listMock.add(randomAlphabetic(6))); + } + + @Test + final void whenSpyBehaviourConfigured_thenCorrect() { + final MyList instance = new MyList(); + final MyList spy = spy(instance); + + doThrow(NullPointerException.class).when(spy).size(); + + assertThrows(NullPointerException.class, () -> spy.size()); + } + + @Test + final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() { + final MyList listMock = mock(MyList.class); + when(listMock.size()).thenCallRealMethod(); + + assertThat(listMock).hasSize(1); + } + + @Test + final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenCustomerAnswerIsCalled() { + final MyList listMock = mock(MyList.class); + doAnswer(invocation -> "Always the same").when(listMock).get(anyInt()); + + final String element = listMock.get(1); + assertThat(element).isEqualTo("Always the same"); + } +} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java new file mode 100644 index 0000000000..b612749328 --- /dev/null +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.mockito.exceptions; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import com.baeldung.mockito.MyDictionary; + +class MockitoExceptionUnitTest { + + @Test + void givenNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class); + + assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word")); + } + + @Test + void givenVoidReturnType_whenUsingDoThrow_thenExceptionIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + doThrow(IllegalStateException.class).when(dictMock).add(anyString(), anyString()); + + assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning")); + } + + @Test + void givenNonVoidReturnType_whenUsingWhenThenAndExeceptionAsNewObject_thenExceptionIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred")); + + assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word")); + } + + @Test + void givenNonVoidReturnType_whenUsingDoThrowAndExeceptionAsNewObject_thenExceptionIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + doThrow(new IllegalStateException("Error occurred")).when(dictMock).add(anyString(), anyString()); + + assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning")); + + } + + @Test + void givenSpyAndNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() { + MyDictionary dict = new MyDictionary(); + MyDictionary spy = Mockito.spy(dict); + when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class); + + assertThrows(NullPointerException.class, () -> spy.getMeaning("word")); + } +} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java similarity index 87% rename from testing-modules/mockito-simple/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java rename to testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java index cc38d617b7..461e377a39 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.junit5.mockito; +package com.baeldung.mockito.junit5; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -18,12 +18,12 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; -import com.baeldung.junit5.mockito.repository.MailClient; -import com.baeldung.junit5.mockito.repository.SettingRepository; -import com.baeldung.junit5.mockito.repository.UserRepository; -import com.baeldung.junit5.mockito.service.DefaultUserService; -import com.baeldung.junit5.mockito.service.Errors; -import com.baeldung.junit5.mockito.service.UserService; +import com.baeldung.mockito.junit5.repository.MailClient; +import com.baeldung.mockito.junit5.repository.SettingRepository; +import com.baeldung.mockito.junit5.repository.UserRepository; +import com.baeldung.mockito.junit5.service.DefaultUserService; +import com.baeldung.mockito.junit5.service.Errors; +import com.baeldung.mockito.junit5.service.UserService; @ExtendWith(MockitoExtension.class) class UserServiceUnitTest { @@ -43,11 +43,14 @@ class UserServiceUnitTest { @BeforeEach void init(@Mock SettingRepository settingRepository) { userService = new DefaultUserService(userRepository, settingRepository, mailClient); - lenient().when(settingRepository.getUserMinAge()) - .thenReturn(10); + + lenient().when(settingRepository.getUserMinAge()).thenReturn(10); + when(settingRepository.getUserNameMinLength()).thenReturn(4); + lenient().when(userRepository.isUsernameAlreadyExists(any(String.class))) .thenReturn(false); + this.settingRepository = settingRepository; } @@ -77,6 +80,8 @@ class UserServiceUnitTest { verify(mailClient).sendUserRegistrationMail(insertedUser); } + //additional tests + @Test void givenShortName_whenSaveUser_thenGiveShortUsernameError() { // Given diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java deleted file mode 100644 index 309f066a87..0000000000 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.mockito.mockedstatic; - -import org.junit.jupiter.api.Test; -import org.mockito.MockedStatic; - -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Mockito.mockStatic; - -import java.util.Arrays; - -class MockedStaticUnitTest { - - @Test - void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() { - assertThat(StaticUtils.name()).isEqualTo("Baeldung"); - - try (MockedStatic utilities = mockStatic(StaticUtils.class)) { - utilities.when(StaticUtils::name).thenReturn("Eugen"); - assertThat(StaticUtils.name()).isEqualTo("Eugen"); - } - - assertThat(StaticUtils.name()).isEqualTo("Baeldung"); - } - - @Test - void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() { - assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); - - try (MockedStatic utilities = mockStatic(StaticUtils.class)) { - utilities.when(() -> StaticUtils.range(2, 6)) - .thenReturn(Arrays.asList(10, 11, 12)); - - assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12); - } - - assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); - } - -} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java new file mode 100644 index 0000000000..10fd480015 --- /dev/null +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.mockito.mockfinal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; + +import com.baeldung.mockito.FinalList; +import com.baeldung.mockito.MyList; + +class MockFinalsUnitTest { + + @Test + void whenMockFinalMethod_thenMockWorks() { + + MyList mock = mock(MyList.class); + when(mock.finalMethod()).thenReturn(1); + + assertThat(mock.finalMethod()).isNotZero(); + } + + @Test + void whenMockFinalClass_thenMockWorks() { + + FinalList mock = mock(FinalList.class); + when(mock.size()).thenReturn(2); + + assertThat(mock.size()).isNotEqualTo(1); + } +} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java new file mode 100644 index 0000000000..0a113ed143 --- /dev/null +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.mockito.mockmethods; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +import org.junit.jupiter.api.Test; +import org.mockito.MockSettings; +import org.mockito.exceptions.verification.TooFewActualInvocations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.baeldung.mockito.MyList; + +class MockitoMockMethodsUnitTest { + + @Test + void whenUsingSimpleMock_thenCorrect() { + MyList listMock = mock(MyList.class); + when(listMock.add(anyString())).thenReturn(false); + + boolean added = listMock.add(randomAlphabetic(6)); + + assertThat(added).isFalse(); + verify(listMock).add(anyString()); + } + + @Test + void givenFewActualInvocationThanConfigured_whenUsingMockWithName_thenExceptionIsThrown() { + MyList listMock = mock(MyList.class, "myMock"); + + when(listMock.add(anyString())).thenReturn(false); + listMock.add(randomAlphabetic(6)); + + assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString())) + .isInstanceOf(TooFewActualInvocations.class) + .hasMessageContaining("myMock.add"); + } + + private static class CustomAnswer implements Answer { + + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + return false; + } + } + + @Test + void whenUsingMockWithAnswer_thenCorrect() { + MyList listMock = mock(MyList.class, new CustomAnswer()); + boolean added = listMock.add(randomAlphabetic(6)); + + verify(listMock).add(anyString()); + assertThat(added).isFalse(); + } + + @Test + void whenUsingMockWithSettings_thenCorrect() { + MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer()); + MyList listMock = mock(MyList.class, customSettings); + + boolean added = listMock.add(randomAlphabetic(6)); + + verify(listMock).add(anyString()); + assertThat(added).isFalse(); + } +} \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java new file mode 100644 index 0000000000..0d653940a4 --- /dev/null +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.mockito.mockstatic; + +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import com.baeldung.mockito.mockedstatic.StaticUtils; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.mockStatic; + +import java.util.Arrays; + +class MockStaticUnitTest { + + @Test + void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() { + assertThat(StaticUtils.name()).isEqualTo("Baeldung"); + + try (MockedStatic utilities = mockStatic(StaticUtils.class)) { + utilities.when(StaticUtils::name).thenReturn("Eugen"); + assertThat(StaticUtils.name()).isEqualTo("Eugen"); + } + + assertThat(StaticUtils.name()).isEqualTo("Baeldung"); + } + + @Test + void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() { + assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); + + try (MockedStatic utilities = mockStatic(StaticUtils.class)) { + utilities.when(() -> StaticUtils.range(2, 6)) + .thenReturn(Arrays.asList(10, 11, 12)); + + assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12); + } + + assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); + } + +} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java index caef0c3b4b..d154044191 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java @@ -16,65 +16,66 @@ import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class MockitoSpyUnitTest { +class MockitoSpyUnitTest { - @Test - void whenSpyingOnList_thenCorrect() { - final List list = new ArrayList(); - final List spyList = spy(list); + @Test + void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() { + final List list = new ArrayList(); + final List spyList = spy(list); - spyList.add("one"); - spyList.add("two"); + spyList.add("one"); + spyList.add("two"); - verify(spyList).add("one"); - verify(spyList).add("two"); + verify(spyList).add("one"); + verify(spyList).add("two"); - assertThat(spyList).hasSize(2); - } + assertThat(spyList).hasSize(2); + } - @Spy - private List aSpyList = new ArrayList(); + @Spy + private List aSpyList = new ArrayList(); - @Test - void whenUsingTheSpyAnnotation_thenObjectIsSpied() { - aSpyList.add("one"); - aSpyList.add("two"); + @Test + void givenUsingSpyAnnotation_whenSpyingOnList_thenCorrect() { + aSpyList.add("one"); + aSpyList.add("two"); - verify(aSpyList).add("one"); - verify(aSpyList).add("two"); + verify(aSpyList).add("one"); + verify(aSpyList).add("two"); - assertThat(aSpyList).hasSize(2); - } + assertThat(aSpyList).hasSize(2); + } - @Test - void whenStubASpy_thenStubbed() { - final List list = new ArrayList(); - final List spyList = spy(list); + @Test + void givenASpy_whenStubbingTheBehaviour_thenCorrect() { + final List list = new ArrayList(); + final List spyList = spy(list); - assertEquals(0, spyList.size()); + assertEquals(0, spyList.size()); - doReturn(100).when(spyList).size(); - assertThat(spyList).hasSize(100); - } + doReturn(100).when(spyList).size(); + + assertThat(spyList).hasSize(100); + } - @Test - void whenCreateMock_thenCreated() { - final List mockedList = mock(ArrayList.class); + @Test + void whenCreateMock_thenCreated() { + final List mockedList = mock(ArrayList.class); - mockedList.add("one"); - verify(mockedList).add("one"); + mockedList.add("one"); + verify(mockedList).add("one"); - assertThat(mockedList).hasSize(0); - } + assertThat(mockedList).hasSize(0); + } - @Test - void whenCreateSpy_thenCreate() { - final List spyList = spy(new ArrayList<>()); + @Test + void whenCreateSpy_thenCreate() { + final List spyList = spy(new ArrayList<>()); - spyList.add("one"); - verify(spyList).add("one"); + spyList.add("one"); + verify(spyList).add("one"); - assertThat(spyList).hasSize(1); - } + assertThat(spyList).hasSize(1); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java new file mode 100644 index 0000000000..383231b458 --- /dev/null +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java @@ -0,0 +1,126 @@ +package com.baeldung.mockito.verify; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.atMost; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.exceptions.verification.NoInteractionsWanted; + +import com.baeldung.mockito.MyList; +import com.google.common.collect.Lists; + +class MockitoVerifyExamplesUnitTest { + + @Test + final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); + verify(mockedList).size(); + } + + @Test + final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); + verify(mockedList, times(1)).size(); + } + + @Test + final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + verifyNoInteractions(mockedList); + } + + @Test + final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + verify(mockedList, times(0)).size(); + } + + @Test + final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() { + final List mockedList = mock(MyList.class); + mockedList.size(); + mockedList.clear(); + + verify(mockedList).size(); + + assertThrows(NoInteractionsWanted.class, () -> verifyNoMoreInteractions(mockedList)); + } + + @Test + final void givenInteractionsInOrder_whenVerifyingOrderOfInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); + mockedList.add("a parameter"); + mockedList.clear(); + + final InOrder inOrder = inOrder(mockedList); + inOrder.verify(mockedList).size(); + inOrder.verify(mockedList).add("a parameter"); + inOrder.verify(mockedList).clear(); + } + + @Test + final void givenNoInteraction_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); + + verify(mockedList, never()).clear(); + } + + @Test + final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.clear(); + mockedList.clear(); + mockedList.clear(); + + verify(mockedList, atLeast(1)).clear(); + verify(mockedList, atMost(10)).clear(); + } + + // with arguments + + @Test + final void givenInteractionWithExactArgument_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.add("test"); + + verify(mockedList).add("test"); + } + + @Test + final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.add("test"); + + verify(mockedList).add(anyString()); + } + + @Test + final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.addAll(Lists. newArrayList("someElement")); + + final ArgumentCaptor> argumentCaptor = ArgumentCaptor.forClass(List.class); + verify(mockedList).addAll(argumentCaptor.capture()); + + final List capturedArgument = argumentCaptor.getValue(); + assertThat(capturedArgument).contains("someElement"); + } +} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java index 9b8a713a15..ef4f91139d 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.mockito.voidmethods; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; @@ -15,64 +14,75 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.junit.jupiter.MockitoExtension; import com.baeldung.mockito.MyList; -@ExtendWith(MockitoExtension.class) class MockitoVoidMethodsUnitTest { - @Test - void whenAddCalledVerified() { - MyList myList = mock(MyList.class); - myList.add(0, ""); + @Test + void whenAddCalled_thenVerified() { + MyList myList = mock(MyList.class); + doNothing().when(myList).add(isA(Integer.class), isA(String.class)); + myList.add(0, ""); + + verify(myList, times(1)).add(0, ""); + } + + @Test + void whenAddCalled_thenVerified2() { + MyList myList = mock(MyList.class); + myList.add(0, ""); - verify(myList, times(1)).add(0, ""); - } + verify(myList, times(1)).add(0, ""); + } - @Test - void givenNull_addThrows() { - MyList myList = mock(MyList.class); - assertThrows(Exception.class, () -> { - doThrow().when(myList).add(isA(Integer.class), isNull()); - }); + @Test + void givenNull_whenAddCalled_thenThrowsException() { + MyList myList = mock(MyList.class); + + assertThrows(Exception.class, () -> { + doThrow().when(myList).add(isA(Integer.class), isNull()); + }); - myList.add(0, null); - } + myList.add(0, null); + } - @Test - void whenAddCalledValueCaptured() { - MyList myList = mock(MyList.class); - ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); - doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); - myList.add(0, "captured"); + @Test + void givenArgumentCaptor_whenAddCalled_thenValueCaptured() { + MyList myList = mock(MyList.class); + + ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); + doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); + + myList.add(0, "captured"); - assertEquals("captured", valueCapture.getValue()); - } + assertEquals("captured", valueCapture.getValue()); + } - @Test - void whenAddCalledAnswered() { - MyList myList = mock(MyList.class); - doAnswer(invocation -> { - Object arg0 = invocation.getArgument(0); - Object arg1 = invocation.getArgument(1); + @Test + void givenDoAnswer_whenAddCalled_thenAnswered() { + MyList myList = mock(MyList.class); - //do something with the arguments here - assertEquals(3, arg0); - assertEquals("answer me", arg1); - return null; - }).when(myList).add(any(Integer.class), any(String.class)); - myList.add(3, "answer me"); - } + doAnswer(invocation -> { + Object arg0 = invocation.getArgument(0); + Object arg1 = invocation.getArgument(1); - @Test - void whenAddCalledRealMethodCalled() { - MyList myList = mock(MyList.class); - doCallRealMethod().when(myList).add(any(Integer.class), any(String.class)); - myList.add(1, "real"); - - verify(myList, times(1)).add(1, "real"); - } + assertEquals(3, arg0); + assertEquals("answer me", arg1); + return null; + }).when(myList).add(any(Integer.class), any(String.class)); + + myList.add(3, "answer me"); + } + + @Test + void givenDoCallRealMethod_whenAddCalled_thenRealMethodCalled() { + MyList myList = mock(MyList.class); + + doCallRealMethod().when(myList).add(any(Integer.class), any(String.class)); + myList.add(1, "real"); + + verify(myList, times(1)).add(1, "real"); + } } From e5985b37397e1f44242ce97491e502b0a04e0ddb Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Fri, 28 Apr 2023 22:03:51 +0530 Subject: [PATCH 02/46] JAVA-13721 Moved mockito-simple to JDK9+ profiles --- pom.xml | 2 ++ testing-modules/pom.xml | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f55a665c33..605542e6dc 100644 --- a/pom.xml +++ b/pom.xml @@ -813,6 +813,7 @@ spring-reactive-modules spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions + testing-modules/mockito-simple persistence-modules/fauna persistence-modules/spring-data-rest @@ -1065,6 +1066,7 @@ spring-reactive-modules spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions + testing-modules/mockito-simple persistence-modules/fauna persistence-modules/spring-data-rest diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 80e0c3bc29..ade9db7661 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -31,7 +31,7 @@ junit5-migration load-testing-comparison mockito - mockito-simple + mocks mocks-2 mockserver From 7be37254804e30e284206b5788c9f4777cd53d1d Mon Sep 17 00:00:00 2001 From: "emanuel.trandafir" Date: Thu, 4 May 2023 18:04:15 +0200 Subject: [PATCH 03/46] BAEL-6320: added code support for the @NaturalId article --- .../data/jpa/naturalid/Application.java | 14 ++++ .../data/jpa/naturalid/HotelRoomsService.java | 35 +++++++++ .../jpa/naturalid/NaturalIdRepoConfig.java | 10 +++ .../jpa/naturalid/entity/ConferenceRoom.java | 56 ++++++++++++++ .../data/jpa/naturalid/entity/GuestRoom.java | 73 +++++++++++++++++++ .../repository/ConferenceRoomJpaRepo.java | 9 +++ .../repository/ConferenceRoomRepository.java | 8 ++ .../repository/GuestRoomJpaRepo.java | 9 +++ .../repository/NaturalIdRepository.java | 11 +++ .../repository/NaturalIdRepositoryImpl.java | 28 +++++++ .../src/main/resources/application.properties | 3 +- .../naturalid/NaturalIdIntegrationTest.java | 61 ++++++++++++++++ 12 files changed, 316 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepoConfig.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomJpaRepo.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepo.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java create mode 100644 persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java new file mode 100644 index 0000000000..aec711d0d1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.data.jpa.naturalid; + +import com.baeldung.spring.data.jpa.naturalid.repository.NaturalIdRepositoryImpl; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(SpringBootApplication.class, args); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java new file mode 100644 index 0000000000..c4c9b4c2b6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java @@ -0,0 +1,35 @@ +package com.baeldung.spring.data.jpa.naturalid; + +import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; +import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import org.hibernate.Session; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +@Service +public class HotelRoomsService { + + private final EntityManager entityManager; + + public HotelRoomsService(EntityManagerFactory entityManagerFactory) { + this.entityManager = entityManagerFactory.createEntityManager(); + } + + public Optional conferenceRoom(String name) { + Session session = entityManager.unwrap(Session.class); + return session.bySimpleNaturalId(ConferenceRoom.class) + .loadOptional(name); + } + + public Optional guestRoom(int roomNumber, int floor) { + Session session = entityManager.unwrap(Session.class); + return session.byNaturalId(GuestRoom.class) + .using("roomNumber", roomNumber) + .using("floor", floor) + .loadOptional(); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepoConfig.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepoConfig.java new file mode 100644 index 0000000000..1461d01a46 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepoConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.data.jpa.naturalid; + +import com.baeldung.spring.data.jpa.naturalid.repository.NaturalIdRepositoryImpl; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@Configuration +@EnableJpaRepositories(repositoryBaseClass = NaturalIdRepositoryImpl.class) +public class NaturalIdRepoConfig { +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java new file mode 100644 index 0000000000..5f72993aa1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.data.jpa.naturalid.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import org.hibernate.annotations.NaturalId; + +@Entity +public class ConferenceRoom { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NaturalId(mutable = true) + private String name; + + private int capacity; + + public ConferenceRoom(String name, int capacity) { + this.name = name; + this.capacity = capacity; + } + + protected ConferenceRoom() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public int getCapacity() { + return capacity; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + } + + @Override + public String toString() { + return "HotelRoom{" + + "id=" + id + + ", name='" + name + '\'' + + ", capacity=" + capacity + + '}'; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java new file mode 100644 index 0000000000..e6ec6bb3dc --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java @@ -0,0 +1,73 @@ +package com.baeldung.spring.data.jpa.naturalid.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import org.hibernate.annotations.NaturalId; + +@Entity +public class GuestRoom { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NaturalId + private Integer roomNumber; + + @NaturalId + private Integer floor; + + private String name; + private int capacity; + + + public GuestRoom(int roomNumber, int floor, String name, int capacity) { + this.roomNumber = roomNumber; + this.floor = floor; + this.name = name; + this.capacity = capacity; + } + + protected GuestRoom() { + } + + public Long getId() { + return id; + } + + public Integer getRoomNumber() { + return roomNumber; + } + + public Integer getFloor() { + return floor; + } + + public int getCapacity() { + return capacity; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "GuestRoom{" + + "id=" + id + + ", roomNumber=" + roomNumber + + ", floor=" + floor + + ", name=" + name + + ", capacity=" + capacity + + '}'; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomJpaRepo.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomJpaRepo.java new file mode 100644 index 0000000000..0f6d2a4b18 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomJpaRepo.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.data.jpa.naturalid.repository; + +import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ConferenceRoomJpaRepo extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java new file mode 100644 index 0000000000..5d98ca930a --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.data.jpa.naturalid.repository; + +import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; +import org.springframework.stereotype.Repository; + +@Repository +public interface ConferenceRoomRepository extends NaturalIdRepository { +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepo.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepo.java new file mode 100644 index 0000000000..4caf327d76 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepo.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.data.jpa.naturalid.repository; + +import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface GuestRoomJpaRepo extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java new file mode 100644 index 0000000000..36a71f4ffa --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.data.jpa.naturalid.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.NoRepositoryBean; + +import java.util.Optional; + +@NoRepositoryBean +public interface NaturalIdRepository extends JpaRepository { + Optional naturalId(ID naturalId); +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java new file mode 100644 index 0000000000..8442237ab1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.data.jpa.naturalid.repository; + +import jakarta.persistence.EntityManager; +import org.hibernate.Session; +import org.springframework.data.jpa.repository.support.JpaEntityInformation; +import org.springframework.data.jpa.repository.support.SimpleJpaRepository; +import org.springframework.data.repository.NoRepositoryBean; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.Optional; + +public class NaturalIdRepositoryImpl extends SimpleJpaRepository implements NaturalIdRepository { + private final EntityManager entityManager; + + public NaturalIdRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { + super(entityInformation, entityManager); + this.entityManager = entityManager; + } + + @Override + public Optional naturalId(ID naturalId) { + return entityManager.unwrap(Session.class) + .bySimpleNaturalId(this.getDomainClass()) + .loadOptional(naturalId); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties index 8b13789179..5a1841e2ad 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties @@ -1 +1,2 @@ - +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java new file mode 100644 index 0000000000..d9f0c68a51 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java @@ -0,0 +1,61 @@ +package com.baeldung.spring.data.jpa.naturalid; + +import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; +import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; +import com.baeldung.spring.data.jpa.naturalid.repository.ConferenceRoomJpaRepo; +import com.baeldung.spring.data.jpa.naturalid.repository.ConferenceRoomRepository; +import com.baeldung.spring.data.jpa.naturalid.repository.GuestRoomJpaRepo; +import jakarta.transaction.Transactional; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.Rollback; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class NaturalIdIntegrationTest { + + @Autowired + private HotelRoomsService service; + + @Autowired + private GuestRoomJpaRepo guestRoomJpaRepo; + @Autowired + private ConferenceRoomJpaRepo conferenceRoomJpaRepo; + + @Autowired + private ConferenceRoomRepository conferenceRoomRepository; + + @Test + void whenWeFindByNaturalKey_thenEntityIsReturnedCorrectly() { + guestRoomJpaRepo.save(new GuestRoom(23, 3, "B-423", 4)); + + Optional result = service.guestRoom(23, 3); + + assertThat(result).isPresent() + .hasValueSatisfying(room -> "B-423".equals(room.getName())); + } + + @Test + void whenWeFindBySimpleNaturalKey_thenEntityIsReturnedCorrectly() { + conferenceRoomJpaRepo.save(new ConferenceRoom("Colorado", 100)); + + Optional result = service.conferenceRoom("Colorado"); + + assertThat(result).isPresent() + .hasValueSatisfying(room -> "Colorado".equals(room.getName())); + } + + @Test + void givenNaturalIdRepo_whenWeFindBySimpleNaturalKey_thenEntityIsReturnedCorrectly() { + conferenceRoomJpaRepo.save(new ConferenceRoom("Nevada", 200)); + + Optional result = conferenceRoomRepository.naturalId("Nevada"); + + assertThat(result).isPresent() + .hasValueSatisfying(room -> "Nevada".equals(room.getName())); + } +} \ No newline at end of file From 000149dd337140dd12e6ae81ce3df685b1ecc488 Mon Sep 17 00:00:00 2001 From: Anastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com> Date: Fri, 12 May 2023 16:07:21 +0300 Subject: [PATCH 04/46] JAVA-20610 Upgraded parent-boot-2 to 2.7.11 (#13944) --- parent-boot-2/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index a1f16c4a64..3f6ad8ef8a 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -94,7 +94,7 @@ 3.3.0 1.0.22.RELEASE - 2.7.8 + 2.7.11 1.9.1 8.0.31 From e7d1d56c47c10868d90a98255928f620b696b4c0 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Fri, 12 May 2023 16:36:06 +0300 Subject: [PATCH 05/46] JAVA-20163 Upgrade hibernate specific modules to JDK 11 (#13817) * JAVA-20163 Migration hibernate-annotations * JAVA-20163 Migrate hibernate-queries * JAVA-20163 Migrating hibernate-mapping * JAVA-20163 rename reserved keywords, update inheritance example * JAVA-20163 Migrate hibernate-ogm module to the jdk 8 because hibernate-ogm doesn't support jakarta API * JAVA-20163 Migrate hibernate-enterprise module * JAVA-20163 Add update to HibernateExceptionUnitTest#whenQueryExecutedWithUnmappedEntity_thenMappingException * JAVA-20163 Set explicit version for hibernate 6.1.7.Final in the hibernate-queries module * JAVA-20163 Fix failed test with port that already exists (giving another port 8088) * JAVA-20163 Fix other location after changing the port * JAVA-20163 Remove duplicate Unit Test --------- Co-authored-by: n Co-authored-by: Loredana Crusoveanu --- .../hibernate-annotations/pom.xml | 11 +- .../creationupdatetimestamp/model/Book.java | 6 +- .../hibernate/customtypes/AddressType.java | 142 ++++++++---------- .../LocalDateStringJavaDescriptor.java | 18 +-- .../customtypes/LocalDateStringType.java | 16 +- .../hibernate/customtypes/OfficeEmployee.java | 54 ++++--- .../hibernate/customtypes/PhoneNumber.java | 8 +- .../customtypes/PhoneNumberType.java | 49 +++--- .../hibernate/customtypes/SalaryType.java | 112 ++++++-------- .../hibernate/immutable/entities/Event.java | 2 +- .../immutable/entities/EventGeneratedId.java | 2 +- .../baeldung/hibernate/joincolumn/Email.java | 14 +- .../baeldung/hibernate/joincolumn/Office.java | 16 +- .../hibernate/joincolumn/OfficeAddress.java | 10 +- .../joincolumn/OfficialEmployee.java | 12 +- .../lazycollection/model/Branch.java | 12 +- .../lazycollection/model/Employee.java | 11 +- .../config/HibernateAnnotationUtil.java | 4 +- .../hibernate/oneToMany/model/Cart.java | 14 +- .../hibernate/oneToMany/model/CartOIO.java | 14 +- .../hibernate/oneToMany/model/Item.java | 16 +- .../hibernate/oneToMany/model/ItemOIO.java | 14 +- .../com/baeldung/hibernate/pojo/Phone.java | 8 +- .../hibernate/wherejointable/Group.java | 8 +- .../hibernate/wherejointable/User.java | 12 +- .../wherejointable/UserGroupRelation.java | 10 +- .../main/resources/META-INF/persistence.xml | 10 +- ...reationUpdateTimestampIntegrationTest.java | 14 +- .../HibernateCustomTypesIntegrationTest.java | 9 +- .../HibernateImmutableIntegrationTest.java | 2 +- .../joincolumn/JoinColumnIntegrationTest.java | 4 +- .../hibernate-enterprise/pom.xml | 7 +- .../hibernate/exception/EntityWithNoId.java | 2 +- .../baeldung/hibernate/exception/Product.java | 8 +- .../hibernate/exception/ProductEntity.java | 6 +- .../hibernate/exception/ProductNotMapped.java | 32 ++++ .../baeldung/hibernate/logging/Employee.java | 8 +- .../baeldung/hibernate/pojo/PointEntity.java | 10 +- .../hibernate/pojo/PolygonEntity.java | 8 +- .../com/baeldung/hibernate/pojo/Student.java | 8 +- .../baeldung/persistence/model/Person.java | 6 +- .../main/resources/META-INF/persistence.xml | 10 +- .../HibernateSpatialIntegrationTest.java | 22 ++- .../exception/HibernateExceptionUnitTest.java | 48 +++--- .../baeldung/hibernate/multitenancy/Car.java | 6 +- .../MultitenancyIntegrationTest.java | 4 +- ...seApproachMultitenancyIntegrationTest.java | 4 +- .../MapMultiTenantConnectionProvider.java | 7 +- .../SchemaMultiTenantConnectionProvider.java | 9 +- .../save/SaveMethodsIntegrationTest.java | 2 +- .../resources/hibernate-exception.properties | 2 - .../resources/hibernate-spatial.properties | 2 +- persistence-modules/hibernate-mapping/pom.xml | 31 ++-- .../com/baeldung/hibernate/HibernateUtil.java | 3 +- .../arraymapping/CustomIntegerArrayType.java | 57 ++++--- .../arraymapping/CustomStringArrayType.java | 57 ++++--- .../baeldung/hibernate/arraymapping/User.java | 20 +-- .../hibernate/basicannotation/Course.java | 9 +- .../hibernate/entities/Department.java | 2 +- .../hibernate/entities/DeptEmployee.java | 12 +- .../hibernate/fetchMode/Customer.java | 8 +- .../baeldung/hibernate/fetchMode/Order.java | 2 +- .../baeldung/hibernate/lob/model/User.java | 12 +- .../hibernate/persistmaps/mapkey/Item.java | 18 +-- .../hibernate/persistmaps/mapkey/Order.java | 20 +-- .../hibernate/persistmaps/mapkey/User.java | 13 +- .../persistmaps/mapkeycolumn/Order.java | 18 +-- .../persistmaps/mapkeyenumerated/Order.java | 22 +-- .../persistmaps/mapkeyjoincolumn/Item.java | 24 +-- .../persistmaps/mapkeyjoincolumn/Order.java | 20 +-- .../persistmaps/mapkeyjoincolumn/Seller.java | 10 +- .../persistmaps/mapkeytemporal/Order.java | 22 +-- .../com/baeldung/hibernate/pojo/Employee.java | 6 +- .../hibernate/pojo/EntityDescription.java | 15 +- .../com/baeldung/hibernate/pojo/Phone.java | 8 +- .../hibernate/pojo/TemporalValues.java | 11 +- .../hibernate/pojo/inheritance/Animal.java | 8 +- .../hibernate/pojo/inheritance/Bag.java | 4 +- .../hibernate/pojo/inheritance/Book.java | 4 +- .../hibernate/pojo/inheritance/Car.java | 2 +- .../hibernate/pojo/inheritance/Laptop.java | 39 +++++ .../pojo/inheritance/MyEmployee.java | 2 +- .../hibernate/pojo/inheritance/MyProduct.java | 14 +- .../hibernate/pojo/inheritance/Pen.java | 4 +- .../hibernate/pojo/inheritance/Person.java | 4 +- .../hibernate/pojo/inheritance/Pet.java | 4 +- .../hibernate/pojo/inheritance/Vehicle.java | 8 +- .../baeldung/hibernate/pojo/package-info.java | 9 -- .../DynamicMappingIntegrationTest.java | 4 +- .../InheritanceMappingIntegrationTest.java | 6 +- .../BasicAnnotationIntegrationTest.java | 2 +- .../UserAdditionalValidationUnitTest.java | 11 +- .../validation/UserValidationUnitTest.java | 10 +- persistence-modules/hibernate-queries/pom.xml | 14 +- .../hibernate/criteria/model/Employee.java | 2 +- .../criteria/view/ApplicationView.java | 8 +- .../view/EmployeeCriteriaQueries.java | 6 +- .../hibernate/criteriaquery/Student.java | 12 +- .../LocalDateStringJavaDescriptor.java | 25 +-- .../customtypes/LocalDateStringType.java | 16 +- .../hibernate/distinct/entities/Comment.java | 8 +- .../hibernate/distinct/entities/Post.java | 11 +- .../hibernate/entities/Department.java | 2 +- .../hibernate/entities/DeptEmployee.java | 12 +- .../baeldung/hibernate/findall/FindAll.java | 8 +- .../hibernate/keywords/BrokenPhoneOrder.java | 8 +- .../hibernate/keywords/PhoneOrder.java | 8 +- .../com/baeldung/hibernate/pojo/Student.java | 8 +- .../main/resources/META-INF/persistence.xml | 10 +- .../HibernateCriteriaIntegrationTest.java | 8 +- .../TypeSafeCriteriaIntegrationTest.java | 7 +- .../entities/DistinctHqlQueriesUnitTest.java | 7 +- persistence-modules/pom.xml | 11 +- pom.xml | 2 + .../client/ProductClient.java | 2 +- .../client/ProductClientUnitTest.java | 4 +- .../controller/ProductControllerUnitTest.java | 4 +- 117 files changed, 816 insertions(+), 787 deletions(-) create mode 100644 persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java create mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml index 310b409a00..6417421fed 100644 --- a/persistence-modules/hibernate-annotations/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -76,13 +76,18 @@ ${org.springframework.version} test + + io.hypersistence + hypersistence-utils-hibernate-60 + 3.3.1 + - 5.0.2.RELEASE - 1.10.6.RELEASE - 5.6.7.Final + 6.0.6 + 3.0.3 + 6.1.7.Final true 9.0.0.M26 diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java index 0677b46690..0484c31ced 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java @@ -2,9 +2,9 @@ package com.baeldung.hibernate.creationupdatetimestamp.model; import java.time.Instant; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java index c10c67df9a..f50d8fd7cc 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.customtypes; import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.type.IntegerType; -import org.hibernate.type.StringType; -import org.hibernate.type.Type; +import org.hibernate.metamodel.spi.ValueAccess; import org.hibernate.usertype.CompositeUserType; +import org.hibernate.usertype.UserType; import java.io.Serializable; import java.sql.PreparedStatement; @@ -14,74 +14,51 @@ import java.sql.SQLException; import java.sql.Types; import java.util.Objects; -public class AddressType implements CompositeUserType { +public class AddressType implements CompositeUserType
, UserType
{ @Override - public String[] getPropertyNames() { - return new String[]{"addressLine1", "addressLine2", - "city", "country", "zipcode"}; - } - - @Override - public Type[] getPropertyTypes() { - return new Type[]{StringType.INSTANCE, StringType.INSTANCE, - StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE}; - } - - @Override - public Object getPropertyValue(Object component, int property) throws HibernateException { - - Address empAdd = (Address) component; + public Object getPropertyValue(Address component, int property) throws HibernateException { switch (property) { case 0: - return empAdd.getAddressLine1(); + return component.getAddressLine1(); case 1: - return empAdd.getAddressLine2(); + return component.getAddressLine2(); case 2: - return empAdd.getCity(); + return component.getCity(); case 3: - return empAdd.getCountry(); + return component.getCountry(); case 4: - return Integer.valueOf(empAdd.getZipCode()); + return component.getZipCode(); + default: + throw new IllegalArgumentException(property + + " is an invalid property index for class type " + + component.getClass().getName()); } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); } @Override - public void setPropertyValue(Object component, int property, Object value) throws HibernateException { - - Address empAdd = (Address) component; - - switch (property) { - case 0: - empAdd.setAddressLine1((String) value); - case 1: - empAdd.setAddressLine2((String) value); - case 2: - empAdd.setCity((String) value); - case 3: - empAdd.setCountry((String) value); - case 4: - empAdd.setZipCode((Integer) value); - } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); - + public Address instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { + return null; } @Override - public Class returnedClass() { + public Class embeddable() { return Address.class; } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public int getSqlType() { + return Types.VARCHAR; + } + + @Override + public Class
returnedClass() { + return Address.class; + } + + @Override + public boolean equals(Address x, Address y) { if (x == y) return true; @@ -92,57 +69,52 @@ public class AddressType implements CompositeUserType { } @Override - public int hashCode(Object x) throws HibernateException { + public int hashCode(Address x) { return x.hashCode(); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - + public Address nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Address empAdd = new Address(); - empAdd.setAddressLine1(rs.getString(names[0])); + empAdd.setAddressLine1(rs.getString(position)); if (rs.wasNull()) return null; - empAdd.setAddressLine2(rs.getString(names[1])); - empAdd.setCity(rs.getString(names[2])); - empAdd.setCountry(rs.getString(names[3])); - empAdd.setZipCode(rs.getInt(names[4])); + empAdd.setAddressLine2(rs.getString(position)); + empAdd.setCity(rs.getString(position)); + empAdd.setCountry(rs.getString(position)); + empAdd.setZipCode(rs.getInt(position)); return empAdd; } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { - + public void nullSafeSet(PreparedStatement st, Address value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) st.setNull(index, Types.VARCHAR); else { - Address empAdd = (Address) value; - st.setString(index, empAdd.getAddressLine1()); - st.setString(index + 1, empAdd.getAddressLine2()); - st.setString(index + 2, empAdd.getCity()); - st.setString(index + 3, empAdd.getCountry()); - st.setInt(index + 4, empAdd.getZipCode()); + st.setString(index, value.getAddressLine1()); + st.setString(index + 1, value.getAddressLine2()); + st.setString(index + 2, value.getCity()); + st.setString(index + 3, value.getCountry()); + st.setInt(index + 4, value.getZipCode()); } } @Override - public Object deepCopy(Object value) throws HibernateException { - + public Address deepCopy(Address value) { if (Objects.isNull(value)) return null; - Address oldEmpAdd = (Address) value; Address newEmpAdd = new Address(); - newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1()); - newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2()); - newEmpAdd.setCity(oldEmpAdd.getCity()); - newEmpAdd.setCountry(oldEmpAdd.getCountry()); - newEmpAdd.setZipCode(oldEmpAdd.getZipCode()); + newEmpAdd.setAddressLine1(value.getAddressLine1()); + newEmpAdd.setAddressLine2(value.getAddressLine2()); + newEmpAdd.setCity(value.getCity()); + newEmpAdd.setCountry(value.getCountry()); + newEmpAdd.setZipCode(value.getZipCode()); return newEmpAdd; } @@ -153,17 +125,27 @@ public class AddressType implements CompositeUserType { } @Override - public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { + public Serializable disassemble(Address value) { return (Serializable) deepCopy(value); } @Override - public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return deepCopy(cached); + public Address assemble(Serializable cached, Object owner) { + return deepCopy((Address) cached); } @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return original; + public Address replace(Address detached, Address managed, Object owner) { + return detached; + } + + @Override + public boolean isInstance(Object object, SessionFactoryImplementor sessionFactory) { + return CompositeUserType.super.isInstance(object, sessionFactory); + } + + @Override + public boolean isSameClass(Object object, SessionFactoryImplementor sessionFactory) { + return CompositeUserType.super.isSameClass(object, sessionFactory); } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java index 56be9e693f..8f1794b979 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -1,14 +1,14 @@ package com.baeldung.hibernate.customtypes; -import org.hibernate.type.LocalDateType; import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; -import org.hibernate.type.descriptor.java.MutabilityPlan; import java.time.LocalDate; +import java.time.format.DateTimeFormatter; -public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { +import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor; + +public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor { public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); @@ -18,12 +18,12 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor implements DiscriminatorType { +public class LocalDateStringType extends AbstractSingleColumnStandardBasicType { public static final LocalDateStringType INSTANCE = new LocalDateStringType(); public LocalDateStringType() { - super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); + super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); } @Override @@ -21,14 +19,12 @@ public class LocalDateStringType extends AbstractSingleColumnStandardBasicType { -public class PhoneNumberType implements UserType { @Override - public int[] sqlTypes() { - return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER}; + public int getSqlType() { + return Types.INTEGER; } @Override @@ -24,7 +23,7 @@ public class PhoneNumberType implements UserType { } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public boolean equals(PhoneNumber x, PhoneNumber y) { if (x == y) return true; if (Objects.isNull(x) || Objects.isNull(y)) @@ -34,48 +33,42 @@ public class PhoneNumberType implements UserType { } @Override - public int hashCode(Object x) throws HibernateException { + public int hashCode(PhoneNumber x) { return x.hashCode(); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - int countryCode = rs.getInt(names[0]); + public PhoneNumber nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + int countryCode = rs.getInt(position); if (rs.wasNull()) return null; - int cityCode = rs.getInt(names[1]); - int number = rs.getInt(names[2]); - PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number); + int cityCode = rs.getInt(position); + int number = rs.getInt(position); - return employeeNumber; + return new PhoneNumber(countryCode, cityCode, number); } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { - + public void nullSafeSet(PreparedStatement st, PhoneNumber value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) { st.setNull(index, Types.INTEGER); st.setNull(index+1, Types.INTEGER); st.setNull(index+2, Types.INTEGER); } else { - PhoneNumber employeeNumber = (PhoneNumber) value; - st.setInt(index,employeeNumber.getCountryCode()); - st.setInt(index+1,employeeNumber.getCityCode()); - st.setInt(index+2,employeeNumber.getNumber()); + st.setInt(index, value.getCountryCode()); + st.setInt(index+1, value.getCityCode()); + st.setInt(index+2, value.getNumber()); } } @Override - public Object deepCopy(Object value) throws HibernateException { + public PhoneNumber deepCopy(PhoneNumber value) { if (Objects.isNull(value)) return null; - PhoneNumber empNumber = (PhoneNumber) value; - PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber()); - - return newEmpNumber; + return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber()); } @Override @@ -84,17 +77,17 @@ public class PhoneNumberType implements UserType { } @Override - public Serializable disassemble(Object value) throws HibernateException { + public Serializable disassemble(PhoneNumber value) { return (Serializable) value; } @Override - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; + public PhoneNumber assemble(Serializable cached, Object owner) { + return (PhoneNumber) cached; } @Override - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; + public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) { + return detached; } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java index 266b85140b..69e34c1363 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.customtypes; import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.type.LongType; -import org.hibernate.type.StringType; -import org.hibernate.type.Type; +import org.hibernate.metamodel.spi.ValueAccess; import org.hibernate.usertype.CompositeUserType; import org.hibernate.usertype.DynamicParameterizedType; +import org.hibernate.usertype.UserType; import java.io.Serializable; import java.sql.PreparedStatement; @@ -16,65 +16,47 @@ import java.sql.Types; import java.util.Objects; import java.util.Properties; -public class SalaryType implements CompositeUserType, DynamicParameterizedType { +public class SalaryType implements UserType, CompositeUserType, DynamicParameterizedType { private String localCurrency; @Override - public String[] getPropertyNames() { - return new String[]{"amount", "currency"}; - } - - @Override - public Type[] getPropertyTypes() { - return new Type[]{LongType.INSTANCE, StringType.INSTANCE}; - } - - @Override - public Object getPropertyValue(Object component, int property) throws HibernateException { - - Salary salary = (Salary) component; + public Object getPropertyValue(Salary component, int property) throws HibernateException { switch (property) { case 0: - return salary.getAmount(); + return component.getAmount(); case 1: - return salary.getCurrency(); + return component.getCurrency(); + default: + throw new IllegalArgumentException(property + + " is an invalid property index for class type " + + component.getClass().getName()); } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); - - } - - - @Override - public void setPropertyValue(Object component, int property, Object value) throws HibernateException { - - Salary salary = (Salary) component; - - switch (property) { - case 0: - salary.setAmount((Long) value); - case 1: - salary.setCurrency((String) value); - } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); - } @Override - public Class returnedClass() { + public Salary instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { + return null; + } + + @Override + public Class embeddable() { return Salary.class; } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public int getSqlType() { + return Types.BIGINT; + } + @Override + public Class returnedClass() { + return Salary.class; + } + + @Override + public boolean equals(Salary x, Salary y) { if (x == y) return true; @@ -82,54 +64,48 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType { return false; return x.equals(y); - } @Override - public int hashCode(Object x) throws HibernateException { + public int hashCode(Salary x) { return x.hashCode(); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - + public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Salary salary = new Salary(); - salary.setAmount(rs.getLong(names[0])); + salary.setAmount(rs.getLong(position)); if (rs.wasNull()) return null; - salary.setCurrency(rs.getString(names[1])); + salary.setCurrency(rs.getString(position)); return salary; } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { - - + public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) st.setNull(index, Types.BIGINT); else { - Salary salary = (Salary) value; - st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(), - salary.getCurrency(), localCurrency)); - st.setString(index + 1, salary.getCurrency()); + st.setLong(index, SalaryCurrencyConvertor.convert( + value.getAmount(), + value.getCurrency(), localCurrency)); + st.setString(index + 1, value.getCurrency()); } } @Override - public Object deepCopy(Object value) throws HibernateException { - + public Salary deepCopy(Salary value) { if (Objects.isNull(value)) return null; - Salary oldSal = (Salary) value; Salary newSal = new Salary(); - newSal.setAmount(oldSal.getAmount()); - newSal.setCurrency(oldSal.getCurrency()); + newSal.setAmount(value.getAmount()); + newSal.setCurrency(value.getCurrency()); return newSal; } @@ -140,18 +116,18 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType { } @Override - public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { + public Serializable disassemble(Salary value) { return (Serializable) deepCopy(value); } @Override - public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return deepCopy(cached); + public Salary assemble(Serializable cached, Object owner) { + return deepCopy((Salary) cached); } @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return original; + public Salary replace(Salary detached, Salary managed, Object owner) { + return detached; } @Override diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java index ec88d629a6..f16aa68475 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java @@ -4,7 +4,7 @@ import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.Immutable; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.Set; @Entity diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java index 33af9313ae..6bf4006550 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java @@ -3,7 +3,7 @@ package com.baeldung.hibernate.immutable.entities; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Immutable; -import javax.persistence.*; +import jakarta.persistence.*; @Entity @Immutable diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java index df07c3cf69..096faf7984 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.joincolumn; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; @Entity public class Email { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java index 9940577761..3c6e5f4642 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.joincolumn; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinColumns; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinColumns; +import jakarta.persistence.ManyToOne; @Entity public class Office { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java index cc723db6a2..d80a8be026 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java @@ -1,10 +1,10 @@ package com.baeldung.hibernate.joincolumn; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class OfficeAddress { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java index 49c63c7578..551b522700 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.joincolumn; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; @Entity public class OfficialEmployee { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java index de88647546..9957e2ce75 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java @@ -3,12 +3,12 @@ package com.baeldung.hibernate.lazycollection.model; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OrderColumn; -import javax.persistence.OneToMany; -import javax.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OrderColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Entity; import java.util.ArrayList; import java.util.List; diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java index 831518a365..edf89696f5 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java @@ -1,11 +1,10 @@ package com.baeldung.hibernate.lazycollection.model; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OrderColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Entity; @Entity public class Employee { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index ef82c1c9ad..99410e1f76 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -43,8 +43,8 @@ public class HibernateAnnotationUtil { return metadata.buildSessionFactory(); } - private static Map dbSettings() { - Map dbSettings = new HashMap<>(); + private static Map dbSettings() { + Map dbSettings = new HashMap<>(); dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many"); dbSettings.put(Environment.USER, "sa"); dbSettings.put(Environment.PASS, ""); diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java index 53878af445..f07f3d3887 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java @@ -2,13 +2,13 @@ package com.baeldung.hibernate.oneToMany.model; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; @Entity @Table(name = "CART") diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java index 27b28a6753..f279cc4ea6 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.oneToMany.model; import java.util.Set; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; @Entity @Table(name = "CARTOIO") diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java index a055682d0d..5babe9c545 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.oneToMany.model; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; @Entity @Table(name = "ITEMS") diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java index baaf57b106..78139da19e 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.oneToMany.model; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; @Entity @Table(name = "ITEMSOIO") diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java index d923bda5de..e173aa8b47 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; import java.io.Serializable; @Entity diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java index 04684eceac..2b17c9218d 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java @@ -3,10 +3,10 @@ package com.baeldung.hibernate.wherejointable; import java.util.ArrayList; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; @Entity(name = "e_group") public class Group { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java index 3029aae640..a517de3cca 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java @@ -3,12 +3,12 @@ package com.baeldung.hibernate.wherejointable; import java.util.ArrayList; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; import org.hibernate.annotations.WhereJoinTable; diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java index 00dd19699c..21a0a443c6 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java @@ -2,11 +2,11 @@ package com.baeldung.hibernate.wherejointable; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Id; @Entity(name = "r_user_group") public class UserGroupRelation implements Serializable { diff --git a/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml index 474eeb7a44..2915125295 100644 --- a/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml @@ -7,12 +7,12 @@ Hibernate EntityManager Demo true - + - - - - + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java index f309e9e22f..bab51dab72 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.hibernate.creationupdatetimestamp; +import static org.hibernate.FlushMode.MANUAL; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -71,22 +72,22 @@ class HibernateCreationUpdateTimestampIntegrationTest { } @Test - void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreNotEqual() { + void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreEqual() { session = sessionFactory.openSession(); session.beginTransaction(); Book book = new Book(); session.save(book); - session.getTransaction() - .commit(); + session.getTransaction().commit(); session.close(); - assertNotEquals(book.getCreatedOn(), book.getLastUpdatedOn()); + assertEquals(book.getCreatedOn(), book.getLastUpdatedOn()); } @Test void whenUpdatingEntity_ThenLastUpdatedOnIsUpdatedAndCreatedOnStaysTheSame() { session = sessionFactory.openSession(); + session.setHibernateFlushMode(MANUAL); session.beginTransaction(); Book book = new Book(); session.save(book); @@ -96,8 +97,9 @@ class HibernateCreationUpdateTimestampIntegrationTest { String newName = "newName"; book.setTitle(newName); - session.getTransaction() - .commit(); + session.save(book); + session.flush(); + session.getTransaction().commit(); session.close(); Instant createdOnAfterUpdate = book.getCreatedOn(); Instant lastUpdatedOnAfterUpdate = book.getLastUpdatedOn(); diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java index 460b65ee12..9da3a90034 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java @@ -6,10 +6,9 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; -import org.junit.Assert; import org.junit.Test; -import javax.persistence.TypedQuery; +import jakarta.persistence.TypedQuery; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; @@ -76,7 +75,7 @@ public class HibernateCustomTypesIntegrationTest { doInHibernate(this::sessionFactory, session -> { session.save(e); - TypedQuery query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode", OfficeEmployee.class); + TypedQuery query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipCode = :pinCode", OfficeEmployee.class); query.setParameter("pinCode",100); int size = query.getResultList().size(); @@ -100,8 +99,8 @@ public class HibernateCustomTypesIntegrationTest { return metadata.buildSessionFactory(); } - private static Map getProperties() { - Map dbSettings = new HashMap<>(); + private static Map getProperties() { + Map dbSettings = new HashMap<>(); dbSettings.put(Environment.URL, "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); dbSettings.put(Environment.USER, "sa"); dbSettings.put(Environment.PASS, ""); diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java index 270a235ef0..f038d2b16d 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java @@ -8,7 +8,7 @@ import org.hibernate.Session; import org.junit.*; import org.junit.rules.ExpectedException; -import javax.persistence.PersistenceException; +import jakarta.persistence.PersistenceException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java index 37125e8b15..04f0613811 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java @@ -78,8 +78,8 @@ public class JoinColumnIntegrationTest { return metadata.buildSessionFactory(); } - private static Map getProperties() { - Map dbSettings = new HashMap<>(); + private static Map getProperties() { + Map dbSettings = new HashMap<>(); dbSettings.put(Environment.URL, "jdbc:h2:mem:mydbJoinColumn;DB_CLOSE_DELAY=-1"); dbSettings.put(Environment.USER, "sa"); dbSettings.put(Environment.PASS, ""); diff --git a/persistence-modules/hibernate-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml index 833f19c673..eaa7b0e765 100644 --- a/persistence-modules/hibernate-enterprise/pom.xml +++ b/persistence-modules/hibernate-enterprise/pom.xml @@ -78,10 +78,11 @@ - 5.3.7.Final - 6.0.6 - 2.2.3 + 6.1.7.Final + 8.0.32 + 2.6.0 0.9 + 1.14.2 \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java index 989fa1281a..8ef7487804 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.exception; -import javax.persistence.Entity; +import jakarta.persistence.Entity; @Entity public class EntityWithNoId { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java index 0724ced56b..b7e80511e6 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.exception; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "PRODUCT") diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java index b9c5f5010d..a2dcec61e9 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java @@ -1,8 +1,8 @@ package com.baeldung.hibernate.exception; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "PRODUCT") diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java new file mode 100644 index 0000000000..827ad15e5b --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java @@ -0,0 +1,32 @@ +package com.baeldung.hibernate.exception; + +public class ProductNotMapped { + + private int id; + private String name; + private String description; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java index 9dcf4058a7..bc50c11d81 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.logging; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Employee { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java index 736abde866..23b9a87eef 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Point; +import org.locationtech.jts.geom.Point; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; @Entity public class PointEntity { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java index 69208c8cd4..32cb146f23 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -1,10 +1,10 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Polygon; +import org.locationtech.jts.geom.Polygon; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; @Entity public class PolygonEntity { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java index 9b26c117eb..263908a5fc 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Student { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java index 6a95a7acf5..3766639975 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java @@ -1,8 +1,8 @@ package com.baeldung.persistence.model; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; @Entity public class Person { diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml index 474eeb7a44..2915125295 100644 --- a/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml @@ -7,12 +7,12 @@ Hibernate EntityManager Demo true - + - - - - + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java index 74f752ab8c..e0f13582ab 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java @@ -9,23 +9,23 @@ import java.io.IOException; import java.net.URL; import java.util.Properties; -import javax.persistence.Query; +import jakarta.persistence.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.io.ParseException; +import org.locationtech.jts.io.WKTReader; +import org.locationtech.jts.geom.Geometry; +import org.locationtech.jts.geom.Point; +import org.locationtech.jts.geom.Polygon; +import org.locationtech.jts.util.GeometricShapeFactory; import com.baeldung.hibernate.pojo.PointEntity; import com.baeldung.hibernate.pojo.PolygonEntity; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.Point; -import com.vividsolutions.jts.geom.Polygon; -import com.vividsolutions.jts.io.ParseException; -import com.vividsolutions.jts.io.WKTReader; -import com.vividsolutions.jts.util.GeometricShapeFactory; import geodb.GeoDB; @@ -39,7 +39,7 @@ public class HibernateSpatialIntegrationTest { session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") .openSession(); transaction = session.beginTransaction(); - session.doWork(conn -> { GeoDB.InitGeoDB(conn); }); + session.doWork(GeoDB::InitGeoDB); } @After @@ -135,9 +135,7 @@ public class HibernateSpatialIntegrationTest { private Geometry wktToGeometry(String wellKnownText) throws ParseException { WKTReader fromText = new WKTReader(); - Geometry geom = null; - geom = fromText.read(wellKnownText); - return geom; + return fromText.read(wellKnownText); } private static Geometry createCircle(double x, double y, double radius) { diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java index 891352843d..37c21d1899 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java @@ -6,28 +6,25 @@ import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.util.List; -import javax.persistence.OptimisticLockException; -import javax.persistence.PersistenceException; +import jakarta.persistence.OptimisticLockException; +import jakarta.persistence.PersistenceException; -import org.hibernate.AnnotationException; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.NonUniqueObjectException; import org.hibernate.PropertyValueException; import org.hibernate.Session; import org.hibernate.SessionFactory; -import org.hibernate.StaleObjectStateException; import org.hibernate.StaleStateException; import org.hibernate.Transaction; -import org.hibernate.TransactionException; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.DataException; import org.hibernate.exception.SQLGrammarException; -import org.hibernate.hql.internal.ast.QuerySyntaxException; import org.hibernate.id.IdentifierGenerationException; import org.hibernate.query.NativeQuery; +import org.hibernate.query.sqm.UnknownEntityException; import org.hibernate.tool.schema.spi.CommandAcceptanceException; import org.hibernate.tool.schema.spi.SchemaManagementException; import org.junit.Before; @@ -63,12 +60,15 @@ public class HibernateExceptionUnitTest { @Test public void whenQueryExecutedWithUnmappedEntity_thenMappingException() { - thrown.expectCause(isA(MappingException.class)); - thrown.expectMessage("Unknown entity: java.lang.String"); + thrown.expect(isA(MappingException.class)); + thrown.expectMessage("Unable to locate persister: com.baeldung.hibernate.exception.ProductNotMapped"); + + ProductNotMapped product = new ProductNotMapped(); + product.setId(1); + product.setName("test"); Session session = sessionFactory.openSession(); - NativeQuery query = session.createNativeQuery("select name from PRODUCT", String.class); - query.getResultList(); + session.save(product); } @Test @@ -82,8 +82,8 @@ public class HibernateExceptionUnitTest { @Test public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() { - thrown.expectCause(isA(QuerySyntaxException.class)); - thrown.expectMessage("PRODUCT is not mapped [from PRODUCT]"); + thrown.expectCause(isA(UnknownEntityException.class)); + thrown.expectMessage("Could not resolve root entity 'PRODUCT"); Session session = sessionFactory.openSession(); List results = session.createQuery("from PRODUCT", Product.class) @@ -92,8 +92,8 @@ public class HibernateExceptionUnitTest { @Test public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { - thrown.expect(AnnotationException.class); - thrown.expectMessage("No identifier specified for entity"); + thrown.expect(isA(HibernateException.class)); + thrown.expectMessage("Entity 'com.baeldung.hibernate.exception.EntityWithNoId' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)"); Configuration cfg = getConfiguration(); cfg.addAnnotatedClass(EntityWithNoId.class); @@ -132,9 +132,8 @@ public class HibernateExceptionUnitTest { @Test public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { - thrown.expect(isA(PersistenceException.class)); thrown.expectCause(isA(SQLGrammarException.class)); - thrown.expectMessage("SQLGrammarException: could not prepare statement"); + thrown.expectMessage("could not prepare statement"); Configuration cfg = getConfiguration(); cfg.addAnnotatedClass(Product.class); @@ -162,9 +161,8 @@ public class HibernateExceptionUnitTest { @Test public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { - thrown.expect(isA(PersistenceException.class)); thrown.expectCause(isA(SQLGrammarException.class)); - thrown.expectMessage("SQLGrammarException: could not prepare statement"); + thrown.expectMessage("could not prepare statement"); Session session = sessionFactory.openSession(); NativeQuery query = session.createNativeQuery("select * from NON_EXISTING_TABLE", Product.class); @@ -173,9 +171,8 @@ public class HibernateExceptionUnitTest { @Test public void whenDuplicateIdSaved_thenConstraintViolationException() { - thrown.expect(isA(PersistenceException.class)); thrown.expectCause(isA(ConstraintViolationException.class)); - thrown.expectMessage("ConstraintViolationException: could not execute statement"); + thrown.expectMessage("could not execute statement"); Session session = null; Transaction transaction = null; @@ -253,7 +250,7 @@ public class HibernateExceptionUnitTest { @Test public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() { thrown.expectCause(isA(DataException.class)); - thrown.expectMessage("org.hibernate.exception.DataException: could not prepare statement"); + thrown.expectMessage("could not prepare statement"); Session session = sessionFactory.openSession(); NativeQuery query = session.createNativeQuery("select * from PRODUCT where id='wrongTypeId'", Product.class); @@ -330,9 +327,8 @@ public class HibernateExceptionUnitTest { @Test public void whenUpdatingNonExistingObject_thenStaleStateException() { - thrown.expect(isA(OptimisticLockException.class)); - thrown.expectMessage("Row was updated or deleted by another transaction"); - thrown.expectCause(isA(StaleObjectStateException.class)); + thrown.expectCause(isA(StaleStateException.class)); + thrown.expectMessage("Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed: update PRODUCT set description=?, name=? where id=?"); Session session = null; Transaction transaction = null; @@ -356,7 +352,8 @@ public class HibernateExceptionUnitTest { @Test public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() { - thrown.expect(isA(TransactionException.class)); + thrown.expect(isA(IllegalStateException.class)); + thrown.expectMessage("Transaction already active"); Session session = null; Transaction transaction = null; @@ -368,6 +365,7 @@ public class HibernateExceptionUnitTest { product1.setId(15); product1.setName("Product1"); session.save(product1); + transaction = session.beginTransaction(); transaction.setRollbackOnly(); transaction.commit(); diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java index 1b6cee7e67..3e4895e5e6 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java @@ -2,9 +2,9 @@ package com.baeldung.hibernate.multitenancy; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity(name = "Car") @Table(name = "Car") diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java index fdc3f9fa81..2dc94172b1 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java @@ -79,9 +79,9 @@ public abstract class MultitenancyIntegrationTest { private void createCarTable() { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); - session.createSQLQuery("drop table Car if exists") + session.createNativeQuery("drop table Car if exists") .executeUpdate(); - session.createSQLQuery("create table Car (brand varchar(255) primary key)") + session.createNativeQuery("create table Car (brand varchar(255) primary key)") .executeUpdate(); tx.commit(); } diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java index 92f477a646..904805f2ce 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java @@ -1,7 +1,5 @@ package com.baeldung.hibernate.multitenancy.database; -import java.io.IOException; - import org.junit.Test; import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest; @@ -14,7 +12,7 @@ public class DatabaseApproachMultitenancyIntegrationTest extends MultitenancyInt } @Test - public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() throws IOException { + public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() { whenCurrentTenantIs(TenantIdNames.MYDB1); whenAddCar("myCar"); thenCarFound("myCar"); diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java index eb1f410622..47abf6ff85 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java @@ -34,8 +34,13 @@ public class MapMultiTenantConnectionProvider extends AbstractMultiTenantConnect private void initConnectionProviderForTenant(String tenantId) throws IOException { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId))); + Map configProperties = new HashMap<>(); + for (String key : properties.stringPropertyNames()) { + String value = properties.getProperty(key); + configProperties.put(key, value); + } DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); - connectionProvider.configure(properties); + connectionProvider.configure(configProperties); this.connectionProviderMap.put(tenantId, connectionProvider); } diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java index 601eba651c..67b838fdf1 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java @@ -3,6 +3,8 @@ package com.baeldung.hibernate.multitenancy.schema; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; @@ -39,9 +41,14 @@ public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConn private ConnectionProvider initConnectionProvider() throws IOException { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties")); + Map configProperties = new HashMap<>(); + for (String key : properties.stringPropertyNames()) { + String value = properties.getProperty(key); + configProperties.put(key, value); + } DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); - connectionProvider.configure(properties); + connectionProvider.configure(configProperties); return connectionProvider; } diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java index 8c571428b4..c3d2362339 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java @@ -7,7 +7,7 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import javax.persistence.PersistenceException; +import jakarta.persistence.PersistenceException; import org.hibernate.HibernateException; import org.hibernate.Session; diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties index e08a23166d..1e086f60d4 100644 --- a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties +++ b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties @@ -12,5 +12,3 @@ hibernate.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.acquire_increment=5 hibernate.c3p0.timeout=1800 - -hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties index c16666cbf5..e156965ce7 100644 --- a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties +++ b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties @@ -4,7 +4,7 @@ hibernate.connection.username=sa hibernate.connection.autocommit=true jdbc.password= -hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect +hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true hibernate.hbm2ddl.auto=create-drop diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 506283a4fb..1e3dc8be5f 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -26,7 +26,7 @@ com.vladmihalcea - hibernate-types-52 + hibernate-types-60 ${hibernate-types.version} @@ -41,9 +41,9 @@ ${hibernate-validator.version} - org.glassfish - javax.el - ${org.glassfish.javax.el.version} + org.glassfish.expressly + expressly + 5.0.0 javax.money @@ -66,16 +66,27 @@ commons-io ${commons-io.version} + + com.fasterxml.jackson.module + jackson-module-jakarta-xmlbind-annotations + ${jackson-module-jakarta-xmlbind-annotation} + + + org.openjdk.nashorn + nashorn-core + 15.4 + - 1.4.197 - 5.4.12.Final - 2.10.4 - 6.0.16.Final + 2.1.214 + 6.1.7.Final + 2.21.1 + 8.0.0.Final 3.0.1-b11 - 1.0.3 - 1.3 + 1.1 + 1.4.2 + 2.14.2 \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java index fbd8bd487b..cbd73832a4 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -21,6 +21,7 @@ import com.baeldung.hibernate.pojo.inheritance.Animal; import com.baeldung.hibernate.pojo.inheritance.Bag; import com.baeldung.hibernate.pojo.inheritance.Book; import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.Laptop; import com.baeldung.hibernate.pojo.inheritance.MyEmployee; import com.baeldung.hibernate.pojo.inheritance.MyProduct; import com.baeldung.hibernate.pojo.inheritance.Pen; @@ -79,6 +80,7 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); metadataSources.addAnnotatedClass(Animal.class); metadataSources.addAnnotatedClass(Bag.class); + metadataSources.addAnnotatedClass(Laptop.class); metadataSources.addAnnotatedClass(Book.class); metadataSources.addAnnotatedClass(Car.class); metadataSources.addAnnotatedClass(MyEmployee.class); @@ -86,7 +88,6 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Pen.class); metadataSources.addAnnotatedClass(Pet.class); metadataSources.addAnnotatedClass(Vehicle.class); - Metadata metadata = metadataSources.getMetadataBuilder() .build(); diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java index 1155a59a57..5d3e22bf05 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java @@ -7,60 +7,57 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Arrays; -import java.util.Objects; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.usertype.UserType; -public class CustomIntegerArrayType implements UserType { +public class CustomIntegerArrayType implements UserType { @Override - public int[] sqlTypes() { - return new int[]{Types.ARRAY}; + public int getSqlType() { + return Types.ARRAY; } @Override - public Class returnedClass() { + public Class returnedClass() { return Integer[].class; } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public boolean equals(Integer[] x, Integer[] y) { if (x instanceof Integer[] && y instanceof Integer[]) { - return Arrays.deepEquals((Integer[])x, (Integer[])y); + return Arrays.deepEquals(x, y); } else { return false; } } @Override - public int hashCode(Object x) throws HibernateException { - return Arrays.hashCode((Integer[])x); + public int hashCode(Integer[] x) { + return Arrays.hashCode(x); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) - throws HibernateException, SQLException { - Array array = rs.getArray(names[0]); - return array != null ? array.getArray() : null; + public Integer[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + Array array = rs.getArray(position); + return array != null ? (Integer[]) array.getArray() : null; } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) - throws HibernateException, SQLException { - if (value != null && st != null) { - Array array = session.connection().createArrayOf("int", (Integer[])value); - st.setArray(index, array); - } else { - st.setNull(index, sqlTypes()[0]); + public void nullSafeSet(PreparedStatement st, Integer[] value, int index, SharedSessionContractImplementor session) throws SQLException { + if (st != null) { + if (value != null) { + Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("int", value); + st.setArray(index, array); + } else { + st.setNull(index, Types.ARRAY); + } } } @Override - public Object deepCopy(Object value) throws HibernateException { - Integer[] arr = (Integer[]) value; - return arr != null ? Arrays.copyOf(arr, arr.length) : null; + public Integer[] deepCopy(Integer[] value) { + return value != null ? Arrays.copyOf(value, value.length) : null; } @Override @@ -69,18 +66,18 @@ public class CustomIntegerArrayType implements UserType { } @Override - public Serializable disassemble(Object value) throws HibernateException { - return (Serializable) value; + public Serializable disassemble(Integer[] value) { + return value; } @Override - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; + public Integer[] assemble(Serializable cached, Object owner) { + return (Integer[]) cached; } @Override - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; + public Integer[] replace(Integer[] detached, Integer[] managed, Object owner) { + return detached; } } diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java index ce50196513..31a082fb05 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java @@ -7,60 +7,57 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Arrays; -import java.util.Objects; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.usertype.UserType; -public class CustomStringArrayType implements UserType { +public class CustomStringArrayType implements UserType { @Override - public int[] sqlTypes() { - return new int[]{Types.ARRAY}; + public int getSqlType() { + return Types.ARRAY; } @Override - public Class returnedClass() { + public Class returnedClass() { return String[].class; } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public boolean equals(String[] x, String[] y) { if (x instanceof String[] && y instanceof String[]) { - return Arrays.deepEquals((String[])x, (String[])y); + return Arrays.deepEquals(x, y); } else { return false; } } @Override - public int hashCode(Object x) throws HibernateException { - return Arrays.hashCode((String[])x); + public int hashCode(String[] x) { + return Arrays.hashCode(x); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) - throws HibernateException, SQLException { - Array array = rs.getArray(names[0]); - return array != null ? array.getArray() : null; + public String[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + Array array = rs.getArray(position); + return array != null ? (String[]) array.getArray() : null; } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) - throws HibernateException, SQLException { - if (value != null && st != null) { - Array array = session.connection().createArrayOf("text", (String[])value); - st.setArray(index, array); - } else { - st.setNull(index, sqlTypes()[0]); + public void nullSafeSet(PreparedStatement st, String[] value, int index, SharedSessionContractImplementor session) throws SQLException { + if (st != null) { + if (value != null) { + Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("text", value); + st.setArray(index, array); + } else { + st.setNull(index, Types.ARRAY); + } } } @Override - public Object deepCopy(Object value) throws HibernateException { - String[] arr = (String[]) value; - return arr != null ? Arrays.copyOf(arr, arr.length) : null; + public String[] deepCopy(String[] value) { + return value != null ? Arrays.copyOf(value, value.length) : null; } @Override @@ -69,18 +66,18 @@ public class CustomStringArrayType implements UserType { } @Override - public Serializable disassemble(Object value) throws HibernateException { - return (Serializable) value; + public Serializable disassemble(String[] value) { + return value; } @Override - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; + public String[] assemble(Serializable cached, Object owner) { + return (String[]) cached; } @Override - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; + public String[] replace(String[] detached, String[] managed, Object owner) { + return detached; } } diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java index 018bedc349..81f2ee89f7 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java @@ -1,21 +1,13 @@ package com.baeldung.hibernate.arraymapping; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import org.hibernate.annotations.Type; import com.vladmihalcea.hibernate.type.array.StringArrayType; -import org.hibernate.annotations.*; - -@TypeDefs({ - @TypeDef( - name = "string-array", - typeClass = StringArrayType.class - ) -}) @Entity public class User { @@ -25,14 +17,14 @@ public class User { private String name; @Column(columnDefinition = "text[]") - @Type(type = "com.baeldung.hibernate.arraymapping.CustomStringArrayType") + @Type(value = com.baeldung.hibernate.arraymapping.CustomStringArrayType.class) private String[] roles; @Column(columnDefinition = "int[]") - @Type(type = "com.baeldung.hibernate.arraymapping.CustomIntegerArrayType") + @Type(value = com.baeldung.hibernate.arraymapping.CustomIntegerArrayType.class) private Integer[] locations; - @Type(type = "string-array") + @Type(StringArrayType.class) @Column( name = "phone_numbers", columnDefinition = "text[]" diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java index e816fb0176..ca77888f9b 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java @@ -1,10 +1,9 @@ package com.baeldung.hibernate.basicannotation; -import javax.persistence.Basic; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Basic; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; @Entity public class Course { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java index ff94f4f849..39e69a2b1c 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -2,7 +2,7 @@ package com.baeldung.hibernate.entities; import java.util.List; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Department { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java index 6510e70650..3c4f542ce7 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.entities; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where employeeNumber = :designation"), @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) @org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java index 5589601da8..b8937c6692 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java @@ -3,10 +3,10 @@ package com.baeldung.hibernate.fetchMode; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; import java.util.HashSet; import java.util.Set; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java index aa9c517321..5be65bac0d 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.fetchMode; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Order { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java index 21f725b388..3c3b748990 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.lob.model; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; +import jakarta.persistence.Table; @Entity -@Table(name="user") +@Table(name="users") public class User { @Id diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java index 385ffe93ea..ff8115f5d9 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java @@ -2,15 +2,15 @@ package com.baeldung.hibernate.persistmaps.mapkey; import com.baeldung.hibernate.persistmaps.ItemType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; import java.util.Date; import java.util.Objects; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java index 8409cacd6b..e42ceda5de 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java @@ -1,15 +1,15 @@ package com.baeldung.hibernate.persistmaps.mapkey; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.MapKey; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.MapKey; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; import java.util.Map; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java index b2ee7e85fe..0a9694f43c 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java @@ -1,16 +1,15 @@ package com.baeldung.hibernate.persistmaps.mapkey; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.validation.constraints.Size; -import javax.money.MonetaryAmount; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.Size; import org.hibernate.validator.constraints.Length; -import org.hibernate.validator.constraints.CreditCardNumber; -import org.hibernate.validator.constraints.Currency; @Entity +@Table(name="users2") public class User { @Id @Column(length = 3) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java index fa092060da..3d24c743d7 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java @@ -1,14 +1,14 @@ package com.baeldung.hibernate.persistmaps.mapkeycolumn; -import javax.persistence.CollectionTable; -import javax.persistence.Column; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.MapKeyColumn; -import javax.persistence.Table; +import jakarta.persistence.CollectionTable; +import jakarta.persistence.Column; +import jakarta.persistence.ElementCollection; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.MapKeyColumn; +import jakarta.persistence.Table; import java.util.Map; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java index e1f62599b8..19622ea01d 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java @@ -3,17 +3,17 @@ package com.baeldung.hibernate.persistmaps.mapkeyenumerated; import com.baeldung.hibernate.persistmaps.ItemType; import com.baeldung.hibernate.persistmaps.mapkey.Item; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.MapKeyEnumerated; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.MapKeyEnumerated; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; import java.util.Map; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java index 97bbd5b539..9ed58305da 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java @@ -2,18 +2,18 @@ package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn; import com.baeldung.hibernate.persistmaps.ItemType; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; import java.util.Date; import java.util.Objects; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java index d680d84501..9d20237860 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java @@ -1,15 +1,15 @@ package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.MapKeyJoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.MapKeyJoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; import java.util.Map; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java index 15b08e9fe6..ca06db241e 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java @@ -1,10 +1,10 @@ package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import java.util.Objects; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java index be602c1e9f..920d693d16 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java @@ -2,17 +2,17 @@ package com.baeldung.hibernate.persistmaps.mapkeytemporal; import com.baeldung.hibernate.persistmaps.mapkey.Item; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.MapKeyTemporal; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.persistence.TemporalType; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.MapKeyTemporal; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import jakarta.persistence.TemporalType; import java.util.Date; import java.util.Map; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java index e9732b2b67..7d8a254eec 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java @@ -2,15 +2,15 @@ package com.baeldung.hibernate.pojo; import org.hibernate.annotations.*; -import javax.persistence.Entity; -import javax.persistence.*; +import jakarta.persistence.Entity; +import jakarta.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @Entity @Where(clause = "deleted = false") -@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int")) +@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = Integer.class)) @Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit") public class Employee implements Serializable { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java index 131bb73a80..29befd80f2 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java @@ -1,8 +1,11 @@ package com.baeldung.hibernate.pojo; import org.hibernate.annotations.Any; +import org.hibernate.annotations.AnyDiscriminator; +import org.hibernate.annotations.AnyDiscriminatorValue; +import org.hibernate.annotations.AnyKeyJavaClass; -import javax.persistence.*; +import jakarta.persistence.*; import java.io.Serializable; @Entity @@ -14,10 +17,12 @@ public class EntityDescription implements Serializable { private String description; - @Any( - metaDef = "EntityDescriptionMetaDef", - metaColumn = @Column(name = "entity_type") - ) + @Any + @AnyDiscriminator(DiscriminatorType.STRING) + @AnyDiscriminatorValue(discriminator = "S", entity = Employee.class) + @AnyDiscriminatorValue(discriminator = "I", entity = Phone.class) + @AnyKeyJavaClass(Integer.class) + @Column(name = "entity_type") @JoinColumn(name = "entity_id") private Serializable entity; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java index d923bda5de..e173aa8b47 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; import java.io.Serializable; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java index f3fe095cae..0c022884eb 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java @@ -1,7 +1,6 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.*; -import java.io.Serializable; +import jakarta.persistence.*; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; @@ -9,7 +8,7 @@ import java.time.*; import java.util.Calendar; @Entity -public class TemporalValues implements Serializable { +public class TemporalValues { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -48,7 +47,7 @@ public class TemporalValues implements Serializable { private java.time.LocalDate localDate; @Basic - private java.time.LocalTime localTime; + private java.time.LocalTime localTimeField; @Basic private java.time.OffsetTime offsetTime; @@ -146,11 +145,11 @@ public class TemporalValues implements Serializable { } public LocalTime getLocalTime() { - return localTime; + return localTimeField; } public void setLocalTime(LocalTime localTime) { - this.localTime = localTime; + this.localTimeField = localTime; } public OffsetTime getOffsetTime() { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java index 6fe7f915fc..c44a542b60 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.JOINED) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java index fa6e1b4bef..707e387866 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import org.hibernate.annotations.Polymorphism; import org.hibernate.annotations.PolymorphismType; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java index 36ca8dd77c..286a30cc14 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; +import jakarta.persistence.DiscriminatorValue; +import jakarta.persistence.Entity; @Entity @DiscriminatorValue("1") diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java index 49d1f7749a..987e299625 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; +import jakarta.persistence.Entity; @Entity public class Car extends Vehicle { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java new file mode 100644 index 0000000000..cced365d78 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java @@ -0,0 +1,39 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import org.hibernate.annotations.Polymorphism; +import org.hibernate.annotations.PolymorphismType; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +@Polymorphism(type = PolymorphismType.IMPLICIT) +public class Laptop implements Item { + + @Id + private Long id; + + private String type; + + public Laptop(Long id, String type) { + this.id = id; + this.type = type; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java index 9a6bce16cf..96958c6e28 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; +import jakarta.persistence.Entity; @Entity public class MyEmployee extends Person { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java index 13f04d8904..62214fc16e 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java @@ -1,13 +1,11 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; - -import org.hibernate.annotations.DiscriminatorFormula; +import jakarta.persistence.DiscriminatorColumn; +import jakarta.persistence.DiscriminatorType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java index 32b77e52af..2382cab405 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; +import jakarta.persistence.DiscriminatorValue; +import jakarta.persistence.Entity; @Entity @DiscriminatorValue("2") diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java index 99084b88af..9bf8ac254c 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Id; -import javax.persistence.MappedSuperclass; +import jakarta.persistence.Id; +import jakarta.persistence.MappedSuperclass; @MappedSuperclass public class Person { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java index 870b3cd684..b359eb3a21 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; -import javax.persistence.PrimaryKeyJoinColumn; +import jakarta.persistence.Entity; +import jakarta.persistence.PrimaryKeyJoinColumn; @Entity @PrimaryKeyJoinColumn(name = "petId") diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java index b2a920573e..9bdde8c33b 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java deleted file mode 100644 index 992cda7c1d..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int", - metaValues = { - @MetaValue(value = "Employee", targetEntity = Employee.class), - @MetaValue(value = "Phone", targetEntity = Phone.class) - }) -package com.baeldung.hibernate.pojo; - -import org.hibernate.annotations.AnyMetaDef; -import org.hibernate.annotations.MetaValue; \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java index 7a112200b5..833c5cc3ff 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java @@ -119,8 +119,8 @@ public class DynamicMappingIntegrationTest { assertThat(employees).hasSize(2); - Employee employee = session.get(Employee.class, 1); - assertThat(employee.getGrossIncome()).isEqualTo(10_000); + Employee employee = session.get(Employee.class, 2); + assertThat(employee.getGrossIncome()).isEqualTo(12_000); session.disableFilter("incomeLevelFilter"); employees = session.createQuery("from Employee").getResultList(); diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java index 0f35dbb8af..7f4cac141c 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java @@ -13,6 +13,7 @@ import org.junit.Test; import com.baeldung.hibernate.pojo.inheritance.Bag; import com.baeldung.hibernate.pojo.inheritance.Book; import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.Laptop; import com.baeldung.hibernate.pojo.inheritance.MyEmployee; import com.baeldung.hibernate.pojo.inheritance.Pen; import com.baeldung.hibernate.pojo.inheritance.Pet; @@ -81,9 +82,12 @@ public class InheritanceMappingIntegrationTest { public void givenSubclasses_whenQueryNonMappedInterface_thenOk() { Bag bag = new Bag(1, "large"); session.save(bag); + + Laptop laptop = new Laptop(1L, "Dell"); + session.save(laptop); assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Item") .getResultList() - .size()).isEqualTo(0); + .size()).isEqualTo(1); } } diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java index 930bea60c5..6a9a4f095b 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java @@ -2,7 +2,7 @@ package com.baeldung.hibernate.basicannotation; import java.io.IOException; -import javax.persistence.PersistenceException; +import jakarta.persistence.PersistenceException; import org.hibernate.Session; import org.hibernate.SessionFactory; diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java index 0f2a0403e9..17212173ec 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java @@ -7,13 +7,12 @@ import java.math.BigDecimal; import java.time.Duration; import java.util.Set; -import javax.money.CurrencyContextBuilder; import javax.money.Monetary; import javax.money.MonetaryAmount; -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; import org.hibernate.validator.constraints.CodePointLength; import org.hibernate.validator.constraints.CreditCardNumber; @@ -21,12 +20,10 @@ import org.hibernate.validator.constraints.Currency; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.LuhnCheck; import org.hibernate.validator.constraints.Range; -import org.hibernate.validator.constraints.SafeHtml; import org.hibernate.validator.constraints.ScriptAssert; import org.hibernate.validator.constraints.URL; import org.hibernate.validator.constraints.time.DurationMax; import org.hibernate.validator.constraints.time.DurationMin; -import org.javamoney.moneta.CurrencyUnitBuilder; import org.javamoney.moneta.Money; import org.junit.BeforeClass; import org.junit.Test; diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java index e39f324856..495ad657be 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java @@ -2,11 +2,11 @@ package com.baeldung.hibernate.validation; import static org.junit.Assert.assertEquals; import java.util.Set; -import javax.persistence.PersistenceException; -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; +import jakarta.persistence.PersistenceException; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.Before; diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml index 68a46b82b1..bb60c7b83a 100644 --- a/persistence-modules/hibernate-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -85,15 +85,21 @@ ${testcontainers.mysql.version} test + + io.hypersistence + hypersistence-utils-hibernate-60 + 3.3.1 + - 5.0.2.RELEASE - 1.10.6.RELEASE + 6.0.6 + 3.0.3 9.0.0.M26 - 6.0.6 - 2.2.3 + 8.0.32 + 2.6.0 2.1.214 + 6.1.7.Final 1.17.6 diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java index 8771e02e0b..9041c6727c 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.criteria.model; import java.io.Serializable; -import javax.persistence.Entity; +import jakarta.persistence.Entity; @org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "Employee_findByEmployeeId", query = "from Employee where id = :employeeId"), diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java index 248f64474a..2b782c2a1d 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -12,10 +12,10 @@ package com.baeldung.hibernate.criteria.view; import java.util.List; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.hibernate.Session; import org.hibernate.query.Query; diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java index f8c525611b..9303fd893e 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java @@ -3,9 +3,9 @@ package com.baeldung.hibernate.criteria.view; import com.baeldung.hibernate.criteria.model.Employee; import com.baeldung.hibernate.criteria.util.HibernateUtil; import java.util.List; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.hibernate.Session; import org.hibernate.query.Query; diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java index 314e7ca557..af6b561091 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.criteriaquery; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "students") diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java index 56be9e693f..58d8e8628a 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -1,14 +1,15 @@ package com.baeldung.hibernate.customtypes; -import org.hibernate.type.LocalDateType; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; -import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; -import org.hibernate.type.descriptor.java.MutabilityPlan; import java.time.LocalDate; +import java.time.format.DateTimeFormatter; -public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { +import org.hibernate.type.descriptor.WrapperOptions; +import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; + +import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor; + +public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor { public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); @@ -18,12 +19,12 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor implements DiscriminatorType { +public class LocalDateStringType extends AbstractSingleColumnStandardBasicType { public static final LocalDateStringType INSTANCE = new LocalDateStringType(); public LocalDateStringType() { - super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); + super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); } @Override @@ -21,14 +19,12 @@ public class LocalDateStringType extends AbstractSingleColumnStandardBasicTypeHibernate EntityManager Demo true - + - - - - + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index a1f88f3387..c405eb9ebd 100644 --- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -15,10 +15,10 @@ import com.baeldung.hibernate.criteria.model.Item; import com.baeldung.hibernate.criteria.util.HibernateUtil; import com.baeldung.hibernate.criteria.view.ApplicationView; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaDelete; -import javax.persistence.criteria.CriteriaUpdate; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaDelete; +import jakarta.persistence.criteria.CriteriaUpdate; +import jakarta.persistence.criteria.Root; public class HibernateCriteriaIntegrationTest { diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java index cedba412d9..bfcb4301a7 100644 --- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.hibernate.criteriaquery; -import com.baeldung.hibernate.criteriaquery.HibernateUtil; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; @@ -10,9 +9,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import java.io.IOException; import java.util.List; diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java index 799439a51b..3ce384741f 100644 --- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java @@ -8,7 +8,6 @@ import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; -import org.hibernate.annotations.QueryHints; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -45,12 +44,12 @@ public class DistinctHqlQueriesUnitTest { } @Test - public void whenExecutingSelectQuery_thereWillBeDuplicates() { + public void whenExecutingSelectQuery_thereTheInsertedPosts() { String hql = "SELECT p FROM Post p LEFT JOIN FETCH p.comments"; List posts = session.createQuery(hql, Post.class) .getResultList(); - assertThat(posts).hasSize(3); + assertThat(posts).hasSize(1); } @Test @@ -68,8 +67,8 @@ public class DistinctHqlQueriesUnitTest { @Test public void whenExecutingSelectDistinctQueryWithHint_thereShouldBeNoDuplicates() { String hql = "SELECT DISTINCT p FROM Post p LEFT JOIN FETCH p.comments"; + // From Hibernate ORM 6, distinct is always passed to the SQL query and the flag QueryHints#HINT_PASS_DISTINCT_THROUGH has been removed. List posts = session.createQuery(hql, Post.class) - .setHint(QueryHints.PASS_DISTINCT_THROUGH, false) .getResultList(); assertThat(posts).hasSize(1) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index ad757d9073..fc83233492 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -26,15 +26,14 @@ flyway-repair hbase hibernate5 - + hibernate-mapping hibernate-mapping-2 - + hibernate-annotations hibernate-exceptions hibernate-libraries hibernate-jpa - - + hibernate-queries + hibernate-enterprise influxdb java-cockroachdb @@ -116,7 +115,7 @@ 6.2.0.Final 42.5.4 - 2.3.4 + 2.7.1 1.16.3 diff --git a/pom.xml b/pom.xml index 060f3a0738..996ebdc459 100644 --- a/pom.xml +++ b/pom.xml @@ -367,6 +367,7 @@ muleesb persistence-modules/deltaspike + persistence-modules/hibernate-ogm @@ -552,6 +553,7 @@ muleesb persistence-modules/deltaspike + persistence-modules/hibernate-ogm diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java index f668e8f2c8..470dd5c929 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java @@ -8,7 +8,7 @@ import org.springframework.web.bind.annotation.RequestMethod; import com.baeldung.cloud.openfeign.customizederrorhandling.config.FeignConfig; import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; -@FeignClient(name = "product-client-2", url = "http://localhost:8081/product/", configuration = FeignConfig.class) +@FeignClient(name = "product-client-2", url = "http://localhost:8088/product/", configuration = FeignConfig.class) public interface ProductClient { @RequestMapping(value = "{id}", method = RequestMethod.GET) diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java index 5e715265aa..385ce900f5 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java @@ -31,8 +31,8 @@ public class ProductClientUnitTest { @Before public void startWireMockServer() { - wireMockServer = new WireMockServer(8081); - configureFor("localhost", 8081); + wireMockServer = new WireMockServer(8088); + configureFor("localhost", 8088); wireMockServer.start(); } diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java index d46c6fd86f..3d103d1333 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java @@ -46,8 +46,8 @@ public class ProductControllerUnitTest { @Before public void startWireMockServer() { - wireMockServer = new WireMockServer(8081); - configureFor("localhost", 8081); + wireMockServer = new WireMockServer(8088); + configureFor("localhost", 8088); wireMockServer.start(); } From bb9e5b65b4044f430aa59e23113cc8f2f2676d7b Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Fri, 12 May 2023 16:44:03 +0300 Subject: [PATCH 06/46] JAVA-20165 Upgrade spring-boot hibernate specific modules to JDK 11 (#13952) * JAVA-20165 Upgrade spring-boot hibernate specific modules to JDK 11 * JAVA-20165 Migrating spring-boot-persistence-mongodb * JAVA-20165 Migrating spring-boot-persistence-mongodb-2 * JAVA-20165 Migrating spring-boot-persistence-mongodb-3 * JAVA-20165 Adding latest version for jdbi in spring-boot-persistence-2 module --------- Co-authored-by: timis1 --- persistence-modules/pom.xml | 6 ++--- .../spring-boot-persistence-2/pom.xml | 24 +++++++++---------- .../baeldung/boot/jdbi/JdbiConfiguration.java | 4 ++-- .../baeldung/boot/jdbi/domain/CarModel.java | 2 +- .../boot/jdbi/mapper/CarModelMapper.java | 2 +- .../java/com/baeldung/db/indexing/Image.java | 8 +++---- .../spring/oracle/pooling/entity/Book.java | 8 +++---- .../application/entities/Customer.java | 10 ++++---- .../java/com/baeldung/states/UserEntity.java | 6 ++--- .../states/UserEntityWithCascade.java | 8 +++---- .../application/entities/Customer.java | 12 +++++----- .../boot/jdbi/dao/CarMakerDao/insert.sql | 2 +- .../boot/jdbi/dao/CarModelDao/insert.sql | 4 ++-- ...ingBootJdbiApplicationIntegrationTest.java | 8 +++---- .../FileSystemImageIntegrationTest.java | 15 ++++++++---- .../db/indexing/ImageIntegrationTest.java | 16 +++++++++---- .../CustomerControllerIntegrationTest.java | 3 +-- .../states/UserEntityIntegrationTest.java | 2 +- .../src/test/resources/data.sql | 16 ++++++------- .../src/test/resources/schema.sql | 4 ++-- .../spring-boot-persistence-mongodb-2/pom.xml | 1 - .../spring-boot-persistence-mongodb-3/pom.xml | 1 - .../spring-boot-persistence-mongodb/pom.xml | 1 - 23 files changed, 84 insertions(+), 79 deletions(-) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index fc83233492..b92fb45e6f 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -58,14 +58,14 @@ solr - + spring-boot-persistence-2 spring-boot-persistence-3 spring-boot-mysql spring-boot-persistence spring-boot-persistence-h2 - + spring-boot-persistence-mongodb-3 spring-data-arangodb spring-data-cassandra spring-data-cassandra-test diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 1a02b18e50..260c558875 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -17,13 +17,6 @@ - - org.junit - junit-bom - ${junit-jupiter.version} - pom - import - org.springframework.boot spring-boot-dependencies @@ -33,7 +26,7 @@ org.jdbi - jdbi3-spring4 + jdbi3-spring5 ${jdbi.version} @@ -55,7 +48,7 @@ org.jdbi - jdbi3-spring4 + jdbi3-spring5 org.jdbi @@ -103,6 +96,7 @@ mysql mysql-connector-java + ${mysql-connector-java.version} org.xerial @@ -143,10 +137,14 @@ - 3.9.1 - 2.1.8.RELEASE - 0.9.5.2 - 21.1.0.0 + 3.38.0 + 3.0.5 + 0.9.5.5 + 21.9.0.0 + + 2.0.7 + 1.4.6 + 8.0.33 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java index ddbe6cc118..d744a46f3f 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java @@ -31,11 +31,11 @@ public class JdbiConfiguration { // Register all available plugins log.info("[I27] Installing plugins... ({} found)", jdbiPlugins.size()); - jdbiPlugins.forEach(plugin -> jdbi.installPlugin(plugin)); + jdbiPlugins.forEach(jdbi::installPlugin); // Register all available rowMappers log.info("[I31] Installing rowMappers... ({} found)", rowMappers.size()); - rowMappers.forEach(mapper -> jdbi.registerRowMapper(mapper)); + rowMappers.forEach(jdbi::registerRowMapper); return jdbi; } diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java index 80b615801b..36cfd59b6d 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java @@ -8,7 +8,7 @@ import lombok.Data; public class CarModel { private Long id; private String name; - private Integer year; + private Integer yearDate; private String sku; private Long makerId; } diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java index eeceafd649..b2311ef6a9 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java @@ -18,7 +18,7 @@ public class CarModelMapper implements RowMapper{ .id(rs.getLong("id")) .name(rs.getString("name")) .sku(rs.getString("sku")) - .year(rs.getInt("year")) + .yearDate(rs.getInt("year")) .build(); } diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java index e3fcf53f81..7c7a558777 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java @@ -1,9 +1,9 @@ package com.baeldung.db.indexing; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Lob; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; @Entity class Image { diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java index fb2c3fcf6a..af4199e65b 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java @@ -1,9 +1,9 @@ package com.baeldung.spring.oracle.pooling.entity; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Book { diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java index ee2735abb8..cd4fafb60f 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java @@ -1,10 +1,10 @@ package com.baeldung.springboothsqldb.application.entities; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "customers") diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java index 90bd275240..8c3494d1e4 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java @@ -5,9 +5,9 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @Entity @AllArgsConstructor diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java index de0d62bfe2..ada6b87ae3 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java @@ -5,10 +5,10 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @Entity @AllArgsConstructor diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java index 712506eb98..02af097dc0 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java @@ -1,11 +1,11 @@ package com.baeldung.tomcatconnectionpool.application.entities; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "customers") diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql index 0e045d7274..0b1a93158b 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql @@ -1,4 +1,4 @@ -- -- Insert -- -insert into car_maker(id,name) values (:id,:name); +insert into car_maker(name) values (:name); diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql index b277213584..6bca3a0d6d 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql @@ -1,8 +1,8 @@ -- -- Insert -- -insert into car_model(maker_fk,name,sku,year) values ( +insert into car_model(maker_fk,name,sku,yearDate) values ( :makerId, :name, :sku, - :year ); + :yearDate ); diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java index ac5661afbc..948d197f14 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java @@ -76,7 +76,7 @@ public class SpringBootJdbiApplicationIntegrationTest { @Test public void givenExistingCarMaker_whenFindById_thenReturnExistingCarMaker() { - CarMaker maker = carMakerDao.findById(1l); + CarMaker maker = carMakerDao.findById(1L); assertThat(maker).isNotNull(); assertThat(maker.getId()).isEqualTo(1); @@ -85,12 +85,12 @@ public class SpringBootJdbiApplicationIntegrationTest { @Test public void givenExistingCarMaker_whenBulkInsertFails_thenRollback() { - CarMaker maker = carMakerDao.findById(1l); + CarMaker maker = carMakerDao.findById(1L); CarModel m1 = CarModel.builder() .makerId(maker.getId()) .name("Model X1") .sku("1-M1") - .year(2019) + .yearDate(2019) .build(); maker.getModels().add(m1); @@ -98,7 +98,7 @@ public class SpringBootJdbiApplicationIntegrationTest { .makerId(maker.getId()) .name("Model X1") .sku("1-M1") - .year(2019) + .yearDate(2019) .build(); maker.getModels().add(m2); diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java index 83f5bae095..809d04cc96 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java @@ -4,8 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.io.File; import java.io.InputStream; -import java.nio.file.Paths; +import java.net.URISyntaxException; +import java.net.URL; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -64,10 +66,13 @@ class FileSystemImageIntegrationTest { private FileSystemResource baeldungJpegResource() { ClassLoader classLoader = ClassLoader.getSystemClassLoader(); - String imagePath = classLoader.getResource("baeldung.jpeg") - .getFile(); - - return new FileSystemResource(Paths.get(imagePath)); + try { + final URL resource = classLoader.getResource("baeldung.jpeg"); + if (resource != null) { + return new FileSystemResource(new File(resource.toURI()).getAbsolutePath()); + } + } catch (URISyntaxException ignore) {} + return null; } } diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java index e38e0a21a9..09e13aefd4 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java @@ -7,6 +7,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.io.IOException; import java.io.InputStream; +import java.net.URISyntaxException; +import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; @@ -68,11 +70,15 @@ class ImageIntegrationTest { private Image baeldungImage() throws IOException { ClassLoader classLoader = ClassLoader.getSystemClassLoader(); - - Image mockImage = new Image(); - mockImage.setContent(Files.readAllBytes(Paths.get(classLoader.getResource("baeldung.jpeg") - .getFile()))); - return mockImage; + try { + final URL resource = classLoader.getResource("baeldung.jpeg"); + if (resource != null) { + Image mockImage = new Image(); + mockImage.setContent(Files.readAllBytes(Paths.get(resource.toURI()))); + return mockImage; + } + } catch (URISyntaxException ignore) {} + return null; } } diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java index 6956df0b13..bdd9a19b68 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java @@ -29,8 +29,7 @@ public class CustomerControllerIntegrationTest { @Before public void setUpJsonMediaType() { - MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - + MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype()); } @Test diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java index 5d0dc99ad7..0ce3ff34ce 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql b/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql index e3e1f4ae32..fb97140b48 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql +++ b/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql @@ -1,12 +1,12 @@ -insert into car_maker(id,name) values (1,'Special Motors'); -insert into car_maker(id,name) values (2,'BWM'); -insert into car_maker(id,name) values (3,'Dolores'); +insert into car_maker(id,name) values (99,'Special Motors'); +insert into car_maker(id,name) values (100,'BWM'); +insert into car_maker(id,name) values (102,'Dolores'); -insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018); -insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008); +insert into car_model(id,maker_fk,name,sku,yearDate) values(132,99,'Muze','SM001',2018); +insert into car_model(id,maker_fk,name,sku,yearDate) values(145,99,'Empada','SM002',2008); -insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008); -insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009); -insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008); +insert into car_model(id,maker_fk,name,sku,yearDate) values(43,100,'BWM-100','BWM100',2008); +insert into car_model(id,maker_fk,name,sku,yearDate) values(564,100,'BWM-200','BWM200',2009); +insert into car_model(id,maker_fk,name,sku,yearDate) values(343,100,'BWM-300','BWM300',2008); diff --git a/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql b/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql index 8d7db6c9f3..72f9e606de 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql +++ b/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql @@ -19,9 +19,9 @@ create table car_model( maker_fk int not null, name varchar(128) not null, sku varchar(128) not null, - year int not null + yearDate int not null ); create unique index ui_car_model_01 on car_model(maker_fk,sku); -create unique index ui_car_model_02 on car_model(maker_fk,name,year); +create unique index ui_car_model_02 on car_model(maker_fk,name,yearDate); diff --git a/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml b/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml index cd7198b931..121581498a 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml @@ -5,7 +5,6 @@ 4.0.0 spring-boot-persistence-mongodb-2 spring-boot-persistence-mongodb-2 - war This is simple boot application for Spring boot persistence mongodb test diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml b/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml index 484e0c0f7e..b699a33559 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml @@ -5,7 +5,6 @@ 4.0.0 spring-boot-persistence-mongodb-3 spring-boot-persistence-mongodb-3 - war This is simple boot application for Spring boot persistence mongodb diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml index 724fa38f7e..aae307f7f8 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml @@ -5,7 +5,6 @@ 4.0.0 spring-boot-persistence-mongodb spring-boot-persistence-mongodb - war This is simple boot application for Spring boot persistence mongodb test From 97bff9fd50b9db91ec5a993598cb696cb58b629a Mon Sep 17 00:00:00 2001 From: Dmytro Budym <46810751+dbudim@users.noreply.github.com> Date: Sat, 13 May 2023 03:12:38 +0200 Subject: [PATCH 07/46] [Check If a Specified Key Exists in a Given S3 Bucket using Java] added code examples (#13775) * [Check If a Specified Key Exists in a Given S3 Bucket using Java]] added code examples for change test name remove link from README.md * - used env variables for AWS credentials - used codestyle profile of baledung --- .../com/baeldung/s3/AWSS3ObjectUtils.java | 42 ++++++++++++++++++ .../s3/AWSS3ObjectIntegrationTest.java | 44 +++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 aws-modules/aws-s3/src/main/java/com/baeldung/s3/AWSS3ObjectUtils.java create mode 100644 aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectIntegrationTest.java diff --git a/aws-modules/aws-s3/src/main/java/com/baeldung/s3/AWSS3ObjectUtils.java b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/AWSS3ObjectUtils.java new file mode 100644 index 0000000000..1c31218ff9 --- /dev/null +++ b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/AWSS3ObjectUtils.java @@ -0,0 +1,42 @@ +package com.baeldung.s3; + +import org.apache.http.HttpStatus; + +import com.amazonaws.AmazonServiceException; +import com.amazonaws.services.s3.AmazonS3; + +public class AWSS3ObjectUtils { + + private AmazonS3 s3Client; + + public AWSS3ObjectUtils(AmazonS3 s3client) { + this.s3Client = s3client; + } + + public boolean doesObjectExistByDefaultMethod(String bucket, String key) { + return s3Client.doesObjectExist(bucket, key); + } + + public boolean doesObjectExistByListObjects(String bucket, String key) { + return s3Client.listObjects(bucket) + .getObjectSummaries() + .stream() + .filter(s3ObjectSummary -> s3ObjectSummary.getKey() + .equals(key)) + .findFirst() + .isPresent(); + } + + public boolean doesObjectExistByMetaData(String bucket, String key) { + try { + s3Client.getObjectMetadata(bucket, key); + return true; + } catch (AmazonServiceException e) { + if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) { + return false; + } else { + throw e; + } + } + } +} \ No newline at end of file diff --git a/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectIntegrationTest.java b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectIntegrationTest.java new file mode 100644 index 0000000000..7fe9081fe3 --- /dev/null +++ b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.s3; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.AmazonS3ClientBuilder; + +public class AWSS3ObjectIntegrationTest { + + private static final String BUCKET = "your-bucket"; + private static final String KEY_THAT_EXIST = "your-key-that-exist"; + private AWSS3ObjectUtils s3ObjectUtils; + + @Before + public void setUp() { + AmazonS3 client = AmazonS3ClientBuilder.standard() + .withRegion(Regions.DEFAULT_REGION) + .withCredentials(new EnvironmentVariableCredentialsProvider()) + .build(); + + s3ObjectUtils = new AWSS3ObjectUtils(client); + } + + @Test + public void whenVerifyIfObjectExistByDefaultMethod_thenCorrect() { + assertTrue(s3ObjectUtils.doesObjectExistByDefaultMethod(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist"); + + } + + @Test + public void whenVerifyIfObjectExistByListObjects_thenCorrect() { + assertTrue(s3ObjectUtils.doesObjectExistByListObjects(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist"); + } + + @Test + public void whenVerifyIfObjectExistByMetaData_thenCorrect() { + assertTrue(s3ObjectUtils.doesObjectExistByMetaData(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist"); + } +} From 535d967fd963417565154e20fa72513dd738b264 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sat, 13 May 2023 17:09:08 +0200 Subject: [PATCH 08/46] [os-to-is] Convert an OutputStream to an InputStream (#13992) --- ...vertOutputStreamToInputStreamUnitTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/outputstreamtoinputstream/ConvertOutputStreamToInputStreamUnitTest.java diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/outputstreamtoinputstream/ConvertOutputStreamToInputStreamUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/outputstreamtoinputstream/ConvertOutputStreamToInputStreamUnitTest.java new file mode 100644 index 0000000000..53e9da6dbb --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/outputstreamtoinputstream/ConvertOutputStreamToInputStreamUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.outputstreamtoinputstream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; + +import org.junit.jupiter.api.Test; + +public class ConvertOutputStreamToInputStreamUnitTest { + + @Test + void whenUsingByteArray_thenGetExpectedInputStream() throws IOException { + String content = "I'm an important message."; + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + out.write(content.getBytes()); + try (ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray())) { + String inContent = new String(in.readAllBytes()); + + assertEquals(content, inContent); + } + } + } + + @Test + void whenUsingPipeStream_thenGetExpectedInputStream() throws IOException { + String content = "I'm going through the pipe."; + + ByteArrayOutputStream originOut = new ByteArrayOutputStream(); + originOut.write(content.getBytes()); + + //connect the pipe + PipedInputStream in = new PipedInputStream(); + PipedOutputStream out = new PipedOutputStream(in); + + try (in) { + new Thread(() -> { + try (out) { + originOut.writeTo(out); + } catch (IOException iox) { + // handle IOExceptions + } + }).start(); + + String inContent = new String(in.readAllBytes()); + assertEquals(content, inContent); + } + } + +} \ No newline at end of file From e1272ca8fecfb7feb76571a5b09c91aec8e799e0 Mon Sep 17 00:00:00 2001 From: Vartika Nigam <63852792+vnigam2702@users.noreply.github.com> Date: Sat, 13 May 2023 21:02:14 +0530 Subject: [PATCH 09/46] =?UTF-8?q?BAEL-6264=20added=20class=20to=20show=20h?= =?UTF-8?q?ow=20to=20instantiate=20ArrayBlockingQueue=20a=E2=80=A6=20(#138?= =?UTF-8?q?51)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * BAEL-6264 added class to show how to instantiate ArrayBlockingQueue and LinkedBlockingQueue * BAEL-6264 added unit test case * modified test case * BAEL-6264 deleted BlockingQueueImplExample file not needed anymore * BAEL-6264 code review changes moved class file to different module --------- Co-authored-by: Vartika_Nigam --- .../queue/BlockingQueueUnitTest.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/BlockingQueueUnitTest.java diff --git a/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/BlockingQueueUnitTest.java b/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/BlockingQueueUnitTest.java new file mode 100644 index 0000000000..e913747f2d --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/BlockingQueueUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.concurrent.queue; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class BlockingQueueUnitTest { + + @Test + public void givenArrayBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() { + BlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(10); + arrayBlockingQueue.add("TestString1"); + arrayBlockingQueue.add("TestString2"); + assertEquals(8, arrayBlockingQueue.remainingCapacity()); + } + + @Test + public void givenLinkedBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() { + BlockingQueue linkedBlockingQueue = new LinkedBlockingQueue<>(10); + linkedBlockingQueue.add("TestString1"); + assertEquals(9, linkedBlockingQueue.remainingCapacity()); + } +} \ No newline at end of file From 0a634dfa0322527c2850357f5c01d5860a14a160 Mon Sep 17 00:00:00 2001 From: Dmytro Budym <46810751+dbudim@users.noreply.github.com> Date: Sun, 14 May 2023 04:59:37 +0200 Subject: [PATCH 10/46] Add code examples for "Opening a New Tab Using Selenium WebDriver in Java" (#14001) Add code examples for "Opening a New Tab Using Selenium WebDriver in Java" --- .../SeleniumOpenNewTabIntegrationTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabIntegrationTest.java diff --git a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabIntegrationTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabIntegrationTest.java new file mode 100644 index 0000000000..4316fedebf --- /dev/null +++ b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabIntegrationTest.java @@ -0,0 +1,53 @@ +package com.baeldung.selenium.tabs; + +import io.github.bonigarcia.wdm.WebDriverManager; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WindowType; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.time.Duration; + +public class SeleniumOpenNewTabIntegrationTest { + + private WebDriver driver; + private static final int TIMEOUT = 10; + private static final int EXPECTED_TABS_COUNT = 2; + + @BeforeMethod + public void initDriver() { + WebDriverManager.chromedriver().setup(); + driver = new ChromeDriver(); + } + + @Test + public void whenUseTabsApiOpenWindow_thenNewTabOpened() { + driver.switchTo().newWindow(WindowType.TAB); + waitTabsCount(EXPECTED_TABS_COUNT); + } + + @Test + public void whenExecuteOpenWindowJsScript_thenNewTabOpened() { + ((JavascriptExecutor) driver).executeScript("window.open()"); + waitTabsCount(EXPECTED_TABS_COUNT); + } + + + @AfterMethod + public void closeBrowser() { + driver.quit(); + } + + + private void waitTabsCount(int tabsCount) { + new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT)) + .withMessage("Tabs count should be: " + tabsCount) + .until(ExpectedConditions.numberOfWindowsToBe(tabsCount)); + } + +} From 4f8662aa01d281a98702bb916b523b2540a1eea1 Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Sun, 14 May 2023 16:52:59 +0200 Subject: [PATCH 11/46] BAEL-6320: format & code review --- .../spring-data-jpa-repo-3/pom.xml | 2 +- .../data/jpa/naturalid/Application.java | 1 + .../data/jpa/naturalid/HotelRoomsService.java | 34 +++---- ...ig.java => NaturalIdRepositoryConfig.java} | 3 +- .../jpa/naturalid/entity/ConferenceRoom.java | 65 ++++++------- .../data/jpa/naturalid/entity/GuestRoom.java | 92 +++++++++---------- .../repository/ConferenceRoomJpaRepo.java | 9 -- .../repository/ConferenceRoomRepository.java | 1 + ...aRepo.java => GuestRoomJpaRepository.java} | 3 +- .../repository/NaturalIdRepository.java | 4 +- .../repository/NaturalIdRepositoryImpl.java | 23 ++--- .../naturalid/NaturalIdIntegrationTest.java | 77 ++++++++-------- 12 files changed, 147 insertions(+), 167 deletions(-) rename persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/{NaturalIdRepoConfig.java => NaturalIdRepositoryConfig.java} (89%) delete mode 100644 persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomJpaRepo.java rename persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/{GuestRoomJpaRepo.java => GuestRoomJpaRepository.java} (75%) diff --git a/persistence-modules/spring-data-jpa-repo-3/pom.xml b/persistence-modules/spring-data-jpa-repo-3/pom.xml index 8cd8ca7f61..d406d25c05 100644 --- a/persistence-modules/spring-data-jpa-repo-3/pom.xml +++ b/persistence-modules/spring-data-jpa-repo-3/pom.xml @@ -24,6 +24,7 @@ h2 runtime + org.springframework.boot spring-boot-starter-test @@ -31,5 +32,4 @@ - diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java index aec711d0d1..94e54889f6 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java @@ -1,6 +1,7 @@ package com.baeldung.spring.data.jpa.naturalid; import com.baeldung.spring.data.jpa.naturalid.repository.NaturalIdRepositoryImpl; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java index c4c9b4c2b6..c8cd1fada4 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java @@ -2,8 +2,10 @@ package com.baeldung.spring.data.jpa.naturalid; import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; + import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; + import org.hibernate.Session; import org.springframework.stereotype.Service; @@ -12,24 +14,24 @@ import java.util.Optional; @Service public class HotelRoomsService { - private final EntityManager entityManager; + private final EntityManager entityManager; - public HotelRoomsService(EntityManagerFactory entityManagerFactory) { - this.entityManager = entityManagerFactory.createEntityManager(); - } + public HotelRoomsService(EntityManagerFactory entityManagerFactory) { + this.entityManager = entityManagerFactory.createEntityManager(); + } - public Optional conferenceRoom(String name) { - Session session = entityManager.unwrap(Session.class); - return session.bySimpleNaturalId(ConferenceRoom.class) - .loadOptional(name); - } + public Optional conferenceRoom(String name) { + Session session = entityManager.unwrap(Session.class); + return session.bySimpleNaturalId(ConferenceRoom.class) + .loadOptional(name); + } - public Optional guestRoom(int roomNumber, int floor) { - Session session = entityManager.unwrap(Session.class); - return session.byNaturalId(GuestRoom.class) - .using("roomNumber", roomNumber) - .using("floor", floor) - .loadOptional(); - } + public Optional guestRoom(int roomNumber, int floor) { + Session session = entityManager.unwrap(Session.class); + return session.byNaturalId(GuestRoom.class) + .using("roomNumber", roomNumber) + .using("floor", floor) + .loadOptional(); + } } diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepoConfig.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepositoryConfig.java similarity index 89% rename from persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepoConfig.java rename to persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepositoryConfig.java index 1461d01a46..94b96ca86c 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepoConfig.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepositoryConfig.java @@ -1,10 +1,11 @@ package com.baeldung.spring.data.jpa.naturalid; import com.baeldung.spring.data.jpa.naturalid.repository.NaturalIdRepositoryImpl; + import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @Configuration @EnableJpaRepositories(repositoryBaseClass = NaturalIdRepositoryImpl.class) -public class NaturalIdRepoConfig { +public class NaturalIdRepositoryConfig { } diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java index 5f72993aa1..6ff7e48a3d 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java @@ -4,53 +4,46 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; + import org.hibernate.annotations.NaturalId; @Entity public class ConferenceRoom { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @NaturalId(mutable = true) - private String name; + @NaturalId + private String name; - private int capacity; + private int capacity; - public ConferenceRoom(String name, int capacity) { - this.name = name; - this.capacity = capacity; - } + public ConferenceRoom(String name, int capacity) { + this.name = name; + this.capacity = capacity; + } - protected ConferenceRoom() { - } + protected ConferenceRoom() { + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public String getName() { + return name; + } - public String getName() { - return name; - } + public int getCapacity() { + return capacity; + } - public int getCapacity() { - return capacity; - } + public void setCapacity(int capacity) { + this.capacity = capacity; + } - public void setCapacity(int capacity) { - this.capacity = capacity; - } - - @Override - public String toString() { - return "HotelRoom{" + - "id=" + id + - ", name='" + name + '\'' + - ", capacity=" + capacity + - '}'; - } + @Override + public String toString() { + return "HotelRoom{" + "id=" + id + ", name='" + name + '\'' + ", capacity=" + capacity + '}'; + } } diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java index e6ec6bb3dc..1219178625 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java @@ -4,70 +4,64 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; + import org.hibernate.annotations.NaturalId; @Entity public class GuestRoom { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @NaturalId - private Integer roomNumber; + @NaturalId + private Integer roomNumber; - @NaturalId - private Integer floor; + @NaturalId + private Integer floor; - private String name; - private int capacity; + private String name; + private int capacity; + public GuestRoom(int roomNumber, int floor, String name, int capacity) { + this.roomNumber = roomNumber; + this.floor = floor; + this.name = name; + this.capacity = capacity; + } - public GuestRoom(int roomNumber, int floor, String name, int capacity) { - this.roomNumber = roomNumber; - this.floor = floor; - this.name = name; - this.capacity = capacity; - } + protected GuestRoom() { + } - protected GuestRoom() { - } + public Long getId() { + return id; + } - public Long getId() { - return id; - } + public Integer getRoomNumber() { + return roomNumber; + } - public Integer getRoomNumber() { - return roomNumber; - } + public Integer getFloor() { + return floor; + } - public Integer getFloor() { - return floor; - } + public int getCapacity() { + return capacity; + } - public int getCapacity() { - return capacity; - } + public void setCapacity(int capacity) { + this.capacity = capacity; + } - public void setCapacity(int capacity) { - this.capacity = capacity; - } + public String getName() { + return name; + } - public String getName() { - return name; - } + public void setName(String name) { + this.name = name; + } - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "GuestRoom{" + - "id=" + id + - ", roomNumber=" + roomNumber + - ", floor=" + floor + - ", name=" + name + - ", capacity=" + capacity + - '}'; - } + @Override + public String toString() { + return "GuestRoom{" + "id=" + id + ", roomNumber=" + roomNumber + ", floor=" + floor + ", name=" + name + ", capacity=" + capacity + '}'; + } } diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomJpaRepo.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomJpaRepo.java deleted file mode 100644 index 0f6d2a4b18..0000000000 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomJpaRepo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.spring.data.jpa.naturalid.repository; - -import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface ConferenceRoomJpaRepo extends JpaRepository { -} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java index 5d98ca930a..d12695f40f 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java @@ -1,6 +1,7 @@ package com.baeldung.spring.data.jpa.naturalid.repository; import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; + import org.springframework.stereotype.Repository; @Repository diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepo.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepository.java similarity index 75% rename from persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepo.java rename to persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepository.java index 4caf327d76..dd761d6660 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepo.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepository.java @@ -1,9 +1,10 @@ package com.baeldung.spring.data.jpa.naturalid.repository; import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; + import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository -public interface GuestRoomJpaRepo extends JpaRepository { +public interface GuestRoomJpaRepository extends JpaRepository { } diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java index 36a71f4ffa..5fe710c0a5 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java @@ -6,6 +6,6 @@ import org.springframework.data.repository.NoRepositoryBean; import java.util.Optional; @NoRepositoryBean -public interface NaturalIdRepository extends JpaRepository { - Optional naturalId(ID naturalId); +public interface NaturalIdRepository extends JpaRepository { + Optional naturalId(ID naturalId); } diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java index 8442237ab1..2c6e62e189 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java @@ -1,6 +1,7 @@ package com.baeldung.spring.data.jpa.naturalid.repository; import jakarta.persistence.EntityManager; + import org.hibernate.Session; import org.springframework.data.jpa.repository.support.JpaEntityInformation; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; @@ -11,18 +12,18 @@ import java.io.Serializable; import java.util.Optional; public class NaturalIdRepositoryImpl extends SimpleJpaRepository implements NaturalIdRepository { - private final EntityManager entityManager; + private final EntityManager entityManager; - public NaturalIdRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { - super(entityInformation, entityManager); - this.entityManager = entityManager; - } + public NaturalIdRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { + super(entityInformation, entityManager); + this.entityManager = entityManager; + } - @Override - public Optional naturalId(ID naturalId) { - return entityManager.unwrap(Session.class) - .bySimpleNaturalId(this.getDomainClass()) - .loadOptional(naturalId); - } + @Override + public Optional naturalId(ID naturalId) { + return entityManager.unwrap(Session.class) + .bySimpleNaturalId(this.getDomainClass()) + .loadOptional(naturalId); + } } \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java index d9f0c68a51..96cc805082 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java @@ -1,61 +1,56 @@ package com.baeldung.spring.data.jpa.naturalid; -import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; -import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; -import com.baeldung.spring.data.jpa.naturalid.repository.ConferenceRoomJpaRepo; -import com.baeldung.spring.data.jpa.naturalid.repository.ConferenceRoomRepository; -import com.baeldung.spring.data.jpa.naturalid.repository.GuestRoomJpaRepo; -import jakarta.transaction.Transactional; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.Rollback; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; +import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; +import com.baeldung.spring.data.jpa.naturalid.repository.ConferenceRoomRepository; +import com.baeldung.spring.data.jpa.naturalid.repository.GuestRoomJpaRepository; @SpringBootTest class NaturalIdIntegrationTest { - @Autowired - private HotelRoomsService service; + @Autowired + private HotelRoomsService service; - @Autowired - private GuestRoomJpaRepo guestRoomJpaRepo; - @Autowired - private ConferenceRoomJpaRepo conferenceRoomJpaRepo; + @Autowired + private GuestRoomJpaRepository guestRoomJpaRepository; + @Autowired + private ConferenceRoomRepository conferenceRoomRepository; - @Autowired - private ConferenceRoomRepository conferenceRoomRepository; + @Test + void whenWeFindByNaturalKey_thenEntityIsReturnedCorrectly() { + guestRoomJpaRepository.save(new GuestRoom(23, 3, "B-423", 4)); - @Test - void whenWeFindByNaturalKey_thenEntityIsReturnedCorrectly() { - guestRoomJpaRepo.save(new GuestRoom(23, 3, "B-423", 4)); + Optional result = service.guestRoom(23, 3); - Optional result = service.guestRoom(23, 3); + assertThat(result).isPresent() + .hasValueSatisfying(room -> "B-423".equals(room.getName())); + } - assertThat(result).isPresent() - .hasValueSatisfying(room -> "B-423".equals(room.getName())); - } + @Test + void whenWeFindBySimpleNaturalKey_thenEntityIsReturnedCorrectly() { + conferenceRoomRepository.save(new ConferenceRoom("Colorado", 100)); - @Test - void whenWeFindBySimpleNaturalKey_thenEntityIsReturnedCorrectly() { - conferenceRoomJpaRepo.save(new ConferenceRoom("Colorado", 100)); + Optional result = service.conferenceRoom("Colorado"); - Optional result = service.conferenceRoom("Colorado"); + assertThat(result).isPresent() + .hasValueSatisfying(room -> "Colorado".equals(room.getName())); + } - assertThat(result).isPresent() - .hasValueSatisfying(room -> "Colorado".equals(room.getName())); - } + @Test + void givenNaturalIdRepository_whenWeFindBySimpleNaturalKey_thenEntityIsReturnedCorrectly() { + conferenceRoomRepository.save(new ConferenceRoom("Nevada", 200)); - @Test - void givenNaturalIdRepo_whenWeFindBySimpleNaturalKey_thenEntityIsReturnedCorrectly() { - conferenceRoomJpaRepo.save(new ConferenceRoom("Nevada", 200)); + Optional result = conferenceRoomRepository.naturalId("Nevada"); - Optional result = conferenceRoomRepository.naturalId("Nevada"); - - assertThat(result).isPresent() - .hasValueSatisfying(room -> "Nevada".equals(room.getName())); - } + assertThat(result).isPresent() + .hasValueSatisfying(room -> "Nevada".equals(room.getName())); + } } \ No newline at end of file From 4fb65f5c6e41e73f183def7cabbca393d1a5e856 Mon Sep 17 00:00:00 2001 From: Ehsan Sasanianno Date: Sun, 14 May 2023 19:13:06 +0200 Subject: [PATCH 12/46] JAVA-16946 Upgrade h2 database version for remaining modules (#13976) --- core-java-modules/core-java-lang-oop-modifiers/pom.xml | 2 +- core-java-modules/pom.xml | 2 +- persistence-modules/java-jpa-2/pom.xml | 2 +- .../src/main/java/com/baeldung/jpa/defaultvalues/User.java | 2 +- .../java-jpa-2/src/main/resources/META-INF/persistence.xml | 2 +- .../java-jpa-2/src/test/resources/META-INF/persistence.xml | 2 +- persistence-modules/pom.xml | 2 +- persistence-modules/spring-jooq/pom.xml | 4 ++-- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/core-java-modules/core-java-lang-oop-modifiers/pom.xml b/core-java-modules/core-java-lang-oop-modifiers/pom.xml index c193073a0e..459aa21721 100644 --- a/core-java-modules/core-java-lang-oop-modifiers/pom.xml +++ b/core-java-modules/core-java-lang-oop-modifiers/pom.xml @@ -23,7 +23,7 @@ - 1.4.197 + 2.1.214 \ No newline at end of file diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 66456d2045..91f0dbfc28 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -97,7 +97,7 @@ core-java-lang-oop-constructors core-java-lang-oop-patterns core-java-lang-oop-generics - + core-java-lang-oop-modifiers core-java-lang-oop-types core-java-lang-oop-types-2 core-java-lang-oop-inheritance diff --git a/persistence-modules/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml index b736b50dd1..38dd64d7b2 100644 --- a/persistence-modules/java-jpa-2/pom.xml +++ b/persistence-modules/java-jpa-2/pom.xml @@ -137,7 +137,7 @@ 3.3.3 3.0.0 4.3.1 - 1.4.200 + 2.1.214 \ No newline at end of file diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/User.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/User.java index 436c708d40..83b05fbc59 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/User.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/User.java @@ -5,7 +5,7 @@ import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; -@Entity +@Entity(name = "users") public class User { @Id diff --git a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml index 3bc81910d9..1e3d3470ed 100644 --- a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml @@ -197,7 +197,7 @@ + value="jdbc:h2:mem:test;MODE=LEGACY" /> + value="jdbc:h2:mem:test;MODE=LEGACY" /> spring-jpa spring-jpa-2 FAILED --> spring-jdbc - + spring-jooq spring-mybatis spring-persistence-simple diff --git a/persistence-modules/spring-jooq/pom.xml b/persistence-modules/spring-jooq/pom.xml index 9848c726c5..d12a921212 100644 --- a/persistence-modules/spring-jooq/pom.xml +++ b/persistence-modules/spring-jooq/pom.xml @@ -195,11 +195,11 @@ - 3.14.15 + 3.16.18 1.0.0 1.5 1.0.0 - 1.4.200 + 2.1.214 \ No newline at end of file From 65f6f416c57c4fff6eb10e72881cd3817f1badec Mon Sep 17 00:00:00 2001 From: Dileesha Rajapakse Date: Sun, 14 May 2023 22:45:57 +0530 Subject: [PATCH 13/46] Add java interface single implementation examples (#13972) --- .../baeldung/interfacesingleimpl/Animal.java | 5 ++ .../interfacesingleimpl/AnimalCare.java | 13 +++++ .../com/baeldung/interfacesingleimpl/Cat.java | 21 ++++++++ .../com/baeldung/interfacesingleimpl/Dog.java | 22 ++++++++ .../InterfaceSingleImplUnitTest.java | 51 +++++++++++++++++++ .../interfacesingleimpl/MockAnimal.java | 8 +++ 6 files changed, 120 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Animal.java create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/AnimalCare.java create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Cat.java create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Dog.java create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/InterfaceSingleImplUnitTest.java create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/MockAnimal.java diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Animal.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Animal.java new file mode 100644 index 0000000000..b20c01cac9 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Animal.java @@ -0,0 +1,5 @@ +package com.baeldung.interfacesingleimpl; + +public interface Animal { + String makeSound(); +} diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/AnimalCare.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/AnimalCare.java new file mode 100644 index 0000000000..0d7b732056 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/AnimalCare.java @@ -0,0 +1,13 @@ +package com.baeldung.interfacesingleimpl; + +public class AnimalCare { + private Animal animal; + + public AnimalCare(Animal animal) { + this.animal = animal; + } + + public String animalSound() { + return animal.makeSound(); + } +} diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Cat.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Cat.java new file mode 100644 index 0000000000..7540e0823b --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Cat.java @@ -0,0 +1,21 @@ +package com.baeldung.interfacesingleimpl; + +public class Cat { + private String name; + + public Cat(String name) { + this.name = name; + } + + public String makeSound() { + return "Meow! My name is " + name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Dog.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Dog.java new file mode 100644 index 0000000000..1dfd3bea0d --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Dog.java @@ -0,0 +1,22 @@ +package com.baeldung.interfacesingleimpl; + +public class Dog implements Animal { + private String name; + + public Dog(String name) { + this.name = name; + } + + @Override + public String makeSound() { + return "Woof! My name is " + name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/InterfaceSingleImplUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/InterfaceSingleImplUnitTest.java new file mode 100644 index 0000000000..4044a554a3 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/InterfaceSingleImplUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.interfacesingleimpl; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class InterfaceSingleImplUnitTest { + @Test + public void whenUsingMockAnimal_thenAnimalSoundIsCorrect() { + MockAnimal mockAnimal = new MockAnimal(); + String expected = "Mock animal sound!"; + AnimalCare animalCare = new AnimalCare(mockAnimal); + assertThat(animalCare.animalSound()).isEqualTo(expected); + } + + @Test + public void whenCreatingDog_thenDogMakesWoofSound() { + Dog dog = new Dog("Buddy"); + String expected = "Woof! My name is Buddy"; + assertThat(dog.makeSound()).isEqualTo(expected); + } + + @Test + public void whenCreatingCat_thenCatMakesMeowSound() { + Cat cat = new Cat("FuzzBall"); + String expected = "Meow! My name is FuzzBall"; + assertThat(cat.makeSound()).isEqualTo(expected); + } + + @Test + public void whenCreatingAnimalCareWithDog_thenDogMakesWoofSound() { + Animal dog = new Dog("Ham"); + AnimalCare animalCare = new AnimalCare(dog); + String expected = "Woof! My name is Ham"; + assertThat(animalCare.animalSound()).isEqualTo(expected); + } + + @Test + public void whenCreatingCatCareWithCat_thenCatMakesMeowSound() { + Cat cat = new Cat("Grumpy"); + String expected = "Meow! My name is Grumpy"; + assertThat(cat.makeSound()).isEqualTo(expected); + } + + @Test + public void whenCreatingMockAnimal_thenMockAnimalMakesMockAnimalSound() { + MockAnimal mockAnimal = new MockAnimal(); + String expected = "Mock animal sound!"; + assertThat(mockAnimal.makeSound()).isEqualTo(expected); + } +} diff --git a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/MockAnimal.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/MockAnimal.java new file mode 100644 index 0000000000..1d3b264f45 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/MockAnimal.java @@ -0,0 +1,8 @@ +package com.baeldung.interfacesingleimpl; + +public class MockAnimal implements Animal { + @Override + public String makeSound() { + return "Mock animal sound!"; + } +} From 2da5d14e25cb9e31911d7d428d1c1136a5356e12 Mon Sep 17 00:00:00 2001 From: Bahaa El-Din Helmy Date: Mon, 15 May 2023 18:14:21 +0300 Subject: [PATCH 14/46] Add files via upload (#14006) --- .../core-java-collections-list-5/pom.xml | 73 ++++++++++--------- .../ArrayAndArrayListPerformance.java | 65 +++++++++++++++++ 2 files changed, 105 insertions(+), 33 deletions(-) create mode 100644 core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java diff --git a/core-java-modules/core-java-collections-list-5/pom.xml b/core-java-modules/core-java-collections-list-5/pom.xml index b51dda4091..c7ee3c3efd 100644 --- a/core-java-modules/core-java-collections-list-5/pom.xml +++ b/core-java-modules/core-java-collections-list-5/pom.xml @@ -1,34 +1,41 @@ - - - 4.0.0 - core-java-collections-list-5 - core-java-collections-list-5 - jar - - - com.baeldung.core-java-modules - core-java-modules - 0.0.1-SNAPSHOT - - - - - commons-lang - commons-lang - ${commons-lang.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - - 2.2 - 3.12.0 - - + + + 4.0.0 + core-java-collections-list-5 + core-java-collections-list-5 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.openjdk.jmh + jmh-core + 1.36 + + + + commons-lang + commons-lang + ${commons-lang.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + 1.21 + 2.2 + 3.12.0 + + \ No newline at end of file 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 new file mode 100644 index 0000000000..3b8fa8c9f3 --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java @@ -0,0 +1,65 @@ +package com.baeldung.arrayandlistperformance; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.options.OptionsBuilder; +import java.util.ArrayList; +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()); + runner.run(); + } + } \ No newline at end of file From 7750bafc1d091829e45c824accd0eb4511c8d342 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Mon, 15 May 2023 23:10:14 +0530 Subject: [PATCH 15/46] JAVA-20828 Fixed module name (#14018) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 996ebdc459..0744823446 100644 --- a/pom.xml +++ b/pom.xml @@ -1201,7 +1201,7 @@ web-modules/bootique web-modules/dropwizard web-modules/google-web-toolkit - web-modules/google-jakarta-ee + web-modules/jakarta-ee From f07f239d8df64dfd22217d55b1c9806f31538426 Mon Sep 17 00:00:00 2001 From: Dmytro Budym <46810751+dbudim@users.noreply.github.com> Date: Mon, 15 May 2023 19:43:53 +0200 Subject: [PATCH 16/46] fix SeleniumOpenNewTabLiveTest (#14019) --- ...wTabIntegrationTest.java => SeleniumOpenNewTabLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/{SeleniumOpenNewTabIntegrationTest.java => SeleniumOpenNewTabLiveTest.java} (96%) diff --git a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabIntegrationTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabLiveTest.java similarity index 96% rename from testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabIntegrationTest.java rename to testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabLiveTest.java index 4316fedebf..9e64073cb9 100644 --- a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabIntegrationTest.java +++ b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/tabs/SeleniumOpenNewTabLiveTest.java @@ -13,7 +13,7 @@ import org.testng.annotations.Test; import java.time.Duration; -public class SeleniumOpenNewTabIntegrationTest { +public class SeleniumOpenNewTabLiveTest { private WebDriver driver; private static final int TIMEOUT = 10; From 3fce001db643195f688fa4eb8af2617b53e25fd8 Mon Sep 17 00:00:00 2001 From: Gaetano Piazzolla Date: Mon, 15 May 2023 21:16:21 +0200 Subject: [PATCH 17/46] BAEL-6493 - Read last N messages from a Kafka Topic (#14020) --- .../kafka/KafaConsumeLastNMessages.java | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessages.java diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessages.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessages.java new file mode 100644 index 0000000000..94f5907525 --- /dev/null +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessages.java @@ -0,0 +1,138 @@ +package com.baeldung.kafka; + +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.TopicPartition; +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; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.ExecutionException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Testcontainers +public class KafaConsumeLastNMessages { + + private static String TOPIC1 = "baeldung-github"; + private static String TOPIC2 = "baeldung-blog"; + private static String MESSAGE_KEY = "message"; + private static KafkaProducer producer; + private static KafkaConsumer consumer; + private static KafkaProducer transactionalProducer; + + @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.GROUP_ID_CONFIG, "ConsumerGroup1"); + + Properties transactionalProducerProprieties = new Properties(); + transactionalProducerProprieties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + transactionalProducerProprieties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + transactionalProducerProprieties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + transactionalProducerProprieties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true"); + transactionalProducerProprieties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "prod-0"); + + producer = new KafkaProducer<>(producerProperties); + consumer = new KafkaConsumer<>(consumerProperties); + transactionalProducer = new KafkaProducer<>(transactionalProducerProprieties); + } + + @AfterAll + static void destroy() { + KAFKA_CONTAINER.stop(); + } + + @Test + void whenSeekingKafkaTopicCursorToEnd_consumerRetrievesOnlyDesiredNumberOfMessages() throws ExecutionException, InterruptedException { + int messagesInTopic = 100; + int messagesToRetrieve = 20; + + for (int i = 0; i < messagesInTopic; i++) { + producer.send(new ProducerRecord<>(TOPIC1, null, MESSAGE_KEY, String.valueOf(i))) + .get(); + } + + TopicPartition partition = new TopicPartition(TOPIC1, 0); + List partitions = new ArrayList<>(); + partitions.add(partition); + consumer.assign(partitions); + + consumer.seekToEnd(partitions); + long startIndex = consumer.position(partition) - messagesToRetrieve; + consumer.seek(partition, startIndex); + + ConsumerRecords records = consumer.poll(Duration.ofMinutes(1)); + int recordsReceived = 0; + for (ConsumerRecord record : records) { + assertEquals(MESSAGE_KEY, record.key()); + assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve)); + recordsReceived++; + } + + assertEquals(messagesToRetrieve, recordsReceived); + } + + @Test + void havingTransactionalProducer_whenSeekingKafkaTopicCursorToEnd_consumerRetrievesLessMessages() throws ExecutionException, InterruptedException { + int messagesInTopic = 100; + int messagesToRetrieve = 20; + + transactionalProducer.initTransactions(); + for (int i = 0; i < messagesInTopic; i++) { + transactionalProducer.beginTransaction(); + transactionalProducer.send(new ProducerRecord<>(TOPIC2, null, MESSAGE_KEY, String.valueOf(i))) + .get(); + transactionalProducer.commitTransaction(); + } + + TopicPartition partition = new TopicPartition(TOPIC2, 0); + List partitions = new ArrayList<>(); + partitions.add(partition); + consumer.assign(partitions); + + consumer.seekToEnd(partitions); + long startIndex = consumer.position(partition) - messagesToRetrieve; + consumer.seek(partition, startIndex); + + ConsumerRecords records = consumer.poll(Duration.ofMinutes(1)); + int recordsReceived = 0; + for (ConsumerRecord record : records) { + assertEquals(MESSAGE_KEY, record.key()); + assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve)); + recordsReceived++; + } + + assertTrue(messagesToRetrieve > recordsReceived); + } + +} From 389a106697fe9e7cc0205df06b39ba3a1164cde4 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Tue, 16 May 2023 08:28:25 +0200 Subject: [PATCH 18/46] BAEL-6398: Java PrintStream to String (#13998) --- .../PrintStreamToStringUtil.java | 68 +++++++++++++++++++ .../PrintStreamToStringUtilUnitTest.java | 32 +++++++++ 2 files changed, 100 insertions(+) create mode 100644 core-java-modules/core-java-io-conversions-2/src/main/java/com/baeldung/printstreamtostring/PrintStreamToStringUtil.java create mode 100644 core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/printstreamtostring/PrintStreamToStringUtilUnitTest.java diff --git a/core-java-modules/core-java-io-conversions-2/src/main/java/com/baeldung/printstreamtostring/PrintStreamToStringUtil.java b/core-java-modules/core-java-io-conversions-2/src/main/java/com/baeldung/printstreamtostring/PrintStreamToStringUtil.java new file mode 100644 index 0000000000..72bba78db0 --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/src/main/java/com/baeldung/printstreamtostring/PrintStreamToStringUtil.java @@ -0,0 +1,68 @@ +package com.baeldung.printstreamtostring; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; + +public class PrintStreamToStringUtil { + + public static String usingByteArrayOutputStreamClass(String input) throws IOException { + if (input == null) { + return null; + } + + String output; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream)) { + printStream.print(input); + + output = outputStream.toString(); + } + + return output; + } + + public static String usingApacheCommonsIO(String input) { + if (input == null) { + return null; + } + + org.apache.commons.io.output.ByteArrayOutputStream outputStream = new org.apache.commons.io.output.ByteArrayOutputStream(); + try (PrintStream printStream = new PrintStream(outputStream)) { + printStream.print(input); + } + + return new String(outputStream.toByteArray()); + } + + public static String usingCustomOutputStream(String input) throws IOException { + if (input == null) { + return null; + } + + String output; + try (CustomOutputStream outputStream = new CustomOutputStream(); PrintStream printStream = new PrintStream(outputStream)) { + printStream.print(input); + + output = outputStream.toString(); + } + + return output; + } + + private static class CustomOutputStream extends OutputStream { + + private StringBuilder stringBuilder = new StringBuilder(); + + @Override + public void write(int b) throws IOException { + this.stringBuilder.append((char) b); + } + + @Override + public String toString() { + return this.stringBuilder.toString(); + } + } + +} diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/printstreamtostring/PrintStreamToStringUtilUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/printstreamtostring/PrintStreamToStringUtilUnitTest.java new file mode 100644 index 0000000000..4db60b604e --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/printstreamtostring/PrintStreamToStringUtilUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.printstreamtostring; + +import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class PrintStreamToStringUtilUnitTest { + + @Test + public void whenUsingByteArrayOutputStreamClass_thenConvert() throws IOException { + assertEquals("test", PrintStreamToStringUtil.usingByteArrayOutputStreamClass("test")); + assertEquals("", PrintStreamToStringUtil.usingByteArrayOutputStreamClass("")); + assertNull(PrintStreamToStringUtil.usingByteArrayOutputStreamClass(null)); + } + + @Test + public void whenCustomOutputStream_thenConvert() throws IOException { + assertEquals("world", PrintStreamToStringUtil.usingCustomOutputStream("world")); + assertEquals("", PrintStreamToStringUtil.usingCustomOutputStream("")); + assertNull(PrintStreamToStringUtil.usingCustomOutputStream(null)); + } + + @Test + public void whenUsingApacheCommonsIO_thenConvert() { + assertEquals("hello", PrintStreamToStringUtil.usingApacheCommonsIO("hello")); + assertEquals("", PrintStreamToStringUtil.usingApacheCommonsIO("")); + assertNull(PrintStreamToStringUtil.usingApacheCommonsIO(null)); + } +} From a9a44221fce4bf51bc9294df2e0bddcbf2ff0aba Mon Sep 17 00:00:00 2001 From: Ehsan Sasanianno Date: Tue, 16 May 2023 12:48:03 +0200 Subject: [PATCH 19/46] Revert "JAVA-20280: remove wrong property (#13874)" (#14021) This reverts commit 561e893e86d9c51b1e61818f5450d6194d9959fd. --- .../src/main/resources/application.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/spring-reactive-modules/spring-reactive-exceptions/src/main/resources/application.yaml b/spring-reactive-modules/spring-reactive-exceptions/src/main/resources/application.yaml index 935ab2a263..50bcbff433 100644 --- a/spring-reactive-modules/spring-reactive-exceptions/src/main/resources/application.yaml +++ b/spring-reactive-modules/spring-reactive-exceptions/src/main/resources/application.yaml @@ -1,3 +1,7 @@ +spring: + codec: + max-in-memory-size: 500KB + server: port: 8080 host: http://localhost:${server.port} From 43c4e4b3371e7ad5e642fdd7fbed6e96734078be Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Tue, 16 May 2023 15:21:10 +0000 Subject: [PATCH 20/46] Hashing with Argon2 in Java (#14009) * Hashing with Argon2 in Java * Hashing with Argon2 in Java --- .../core-java-security-3/pom.xml | 8 ++- .../hash/argon/HashPasswordUnitTest.java | 65 +++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-security-3/src/test/java/com/baeldung/hash/argon/HashPasswordUnitTest.java diff --git a/core-java-modules/core-java-security-3/pom.xml b/core-java-modules/core-java-security-3/pom.xml index fef8b53289..a4f60b4db5 100644 --- a/core-java-modules/core-java-security-3/pom.xml +++ b/core-java-modules/core-java-security-3/pom.xml @@ -30,12 +30,18 @@ jaxb-api ${jaxb-api.version} + + org.springframework.security + spring-security-crypto + ${spring-security-crypto.version} + - 1.60 + 1.70 1.11 2.3.1 + 6.0.3 \ No newline at end of file diff --git a/core-java-modules/core-java-security-3/src/test/java/com/baeldung/hash/argon/HashPasswordUnitTest.java b/core-java-modules/core-java-security-3/src/test/java/com/baeldung/hash/argon/HashPasswordUnitTest.java new file mode 100644 index 0000000000..6e0e326821 --- /dev/null +++ b/core-java-modules/core-java-security-3/src/test/java/com/baeldung/hash/argon/HashPasswordUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.hash.argon; + +import static org.junit.jupiter.api.Assertions.*; + +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; + +import org.bouncycastle.crypto.generators.Argon2BytesGenerator; +import org.bouncycastle.crypto.params.Argon2Parameters; +import org.bouncycastle.util.encoders.Hex; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; + +import java.util.Arrays; +import java.util.Base64; + +public class HashPasswordUnitTest { + + @Test + public void givenRawPassword_whenEncodedWithArgon2_thenMatchesEncodedPassword() { + String rawPassword = "Baeldung"; + + Argon2PasswordEncoder arg2SpringSecurity = new Argon2PasswordEncoder(16, 32, 1, 60000, 10); + String hashPassword = arg2SpringSecurity.encode(rawPassword); + + assertTrue(arg2SpringSecurity.matches(rawPassword, hashPassword)); + } + + @Test + public void givenRawPasswordAndSalt_whenArgon2AlgorithmIsUsed_thenHashIsCorrect() { + byte[] salt = generateSalt16Byte(); + String password = "Baeldung"; + + int iterations = 2; + int memLimit = 66536; + int hashLength = 32; + int parallelism = 1; + Argon2Parameters.Builder builder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).withVersion(Argon2Parameters.ARGON2_VERSION_13) + .withIterations(iterations) + .withMemoryAsKB(memLimit) + .withParallelism(parallelism) + .withSalt(salt); + + Argon2BytesGenerator generate = new Argon2BytesGenerator(); + generate.init(builder.build()); + byte[] result = new byte[hashLength]; + generate.generateBytes(password.getBytes(StandardCharsets.UTF_8), result, 0, result.length); + + Argon2BytesGenerator verifier = new Argon2BytesGenerator(); + verifier.init(builder.build()); + byte[] testHash = new byte[hashLength]; + verifier.generateBytes(password.getBytes(StandardCharsets.UTF_8), testHash, 0, testHash.length); + + assertTrue(Arrays.equals(result, testHash)); + } + + private static byte[] generateSalt16Byte() { + SecureRandom secureRandom = new SecureRandom(); + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + return salt; + } + +} From 7b8fad5dc938aa9f5669100311f4a5a3f6d1d36e Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Tue, 16 May 2023 22:56:17 +0530 Subject: [PATCH 21/46] JAVA-13721 Fixing the formatting --- testing-modules/mockito-simple/pom.xml | 2 - .../mockito/argumentcaptor/Credentials.java | 34 ++-- .../mockito/argumentcaptor/Format.java | 3 +- .../mockito/argumentmatchers/Message.java | 70 ++++---- .../mockito/argumentmatchers/MessageDTO.java | 42 ++--- .../controller/FlowerController.java | 20 +-- .../controller/MessageController.java | 24 +-- .../service/MessageService.java | 2 +- .../mockito/junit5/repository/MailClient.java | 2 +- .../mockito/junit5/service/UserService.java | 2 +- .../mockito/mockedstatic/StaticUtils.java | 20 +-- .../java/com/baeldung/mockito/FinalList.java | 8 +- .../com/baeldung/mockito/MyDictionary.java | 26 +-- .../java/com/baeldung/mockito/MyList.java | 30 ++-- .../MockitoAnnotationUnitTest.java | 150 ++++++++--------- ...tionsInitWithMockitoJUnitRuleUnitTest.java | 18 +- ...ckitoAnnotationsInjectIntoSpyUnitTest.java | 30 ++-- ...ckitoAnnotationsUninitializedUnitTest.java | 16 +- .../argumentcaptor/EmailServiceUnitTest.java | 118 ++++++------- .../FlowerControllerUnitTest.java | 80 ++++----- .../MessageControllerUnitTest.java | 52 +++--- .../argumentmatchers/MessageMatcher.java | 9 +- .../MockitoWhenThenExamplesUnitTest.java | 130 +++++++-------- .../exceptions/MockitoExceptionUnitTest.java | 71 ++++---- .../mockito/junit5/UserServiceUnitTest.java | 12 +- .../mockito/mockfinal/MockFinalsUnitTest.java | 24 +-- .../MockitoMockMethodsUnitTest.java | 82 ++++----- .../mockstatic/MockStaticUnitTest.java | 38 ++--- .../spy/MockitoMisusingMockOrSpyUnitTest.java | 8 +- .../mockito/spy/MockitoSpyUnitTest.java | 86 +++++----- .../verify/MockitoVerifyExamplesUnitTest.java | 156 +++++++++--------- .../MockitoVoidMethodsUnitTest.java | 112 +++++++------ 32 files changed, 738 insertions(+), 739 deletions(-) diff --git a/testing-modules/mockito-simple/pom.xml b/testing-modules/mockito-simple/pom.xml index f96cb98d46..30928cfe35 100644 --- a/testing-modules/mockito-simple/pom.xml +++ b/testing-modules/mockito-simple/pom.xml @@ -29,14 +29,12 @@ spring-context ${spring-framework.version} - org.apache.commons commons-lang3 ${commons-lang3.version} - org.mockito diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java index 3ec86b4499..598c7c93fa 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java @@ -1,25 +1,25 @@ package com.baeldung.mockito.argumentcaptor; public class Credentials { - private final String name; - private final String password; - private final String key; + private final String name; + private final String password; + private final String key; - public Credentials(String name, String password, String key) { - this.name = name; - this.password = password; - this.key = key; - } + public Credentials(String name, String password, String key) { + this.name = name; + this.password = password; + this.key = key; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java index 4c10375159..50363d7c17 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java @@ -1,6 +1,5 @@ package com.baeldung.mockito.argumentcaptor; public enum Format { - TEXT_ONLY, - HTML + TEXT_ONLY, HTML } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java index 13d285de8d..60ddc5ac04 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java @@ -5,49 +5,49 @@ import java.util.UUID; public class Message { - private String from; - private String to; - private String text; - private Date date; - private UUID id; + private String from; + private String to; + private String text; + private Date date; + private UUID id; - public String getFrom() { - return from; - } + public String getFrom() { + return from; + } - public void setFrom(String from) { - this.from = from; - } + public void setFrom(String from) { + this.from = from; + } - public String getTo() { - return to; - } + public String getTo() { + return to; + } - public void setTo(String to) { - this.to = to; - } + public void setTo(String to) { + this.to = to; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public void setText(String text) { - this.text = text; - } + public void setText(String text) { + this.text = text; + } - public Date getDate() { - return date; - } + public Date getDate() { + return date; + } - public void setDate(Date date) { - this.date = date; - } + public void setDate(Date date) { + this.date = date; + } - public UUID getId() { - return id; - } + public UUID getId() { + return id; + } - public void setId(UUID id) { - this.id = id; - } + public void setId(UUID id) { + this.id = id; + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java index 76989e758c..7dce0ab75b 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java @@ -2,31 +2,31 @@ package com.baeldung.mockito.argumentmatchers; public class MessageDTO { - private String from; - private String to; - private String text; + private String from; + private String to; + private String text; - public String getFrom() { - return from; - } + public String getFrom() { + return from; + } - public void setFrom(String from) { - this.from = from; - } + public void setFrom(String from) { + this.from = from; + } - public String getTo() { - return to; - } + public String getTo() { + return to; + } - public void setTo(String to) { - this.to = to; - } + public void setTo(String to) { + this.to = to; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public void setText(String text) { - this.text = text; - } + public void setText(String text) { + this.text = text; + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java index 29c8dbb15d..e0c7cfb62e 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java @@ -13,16 +13,16 @@ import com.baeldung.mockito.argumentmatchers.service.FlowerService; @RequestMapping("/flowers") public class FlowerController { - @Autowired - private FlowerService flowerService; + @Autowired + private FlowerService flowerService; - @PostMapping("/isAFlower") - public String isAFlower(@RequestBody String flower) { - return flowerService.analyze(flower); - } + @PostMapping("/isAFlower") + public String isAFlower(@RequestBody String flower) { + return flowerService.analyze(flower); + } - @PostMapping("/isABigFlower") - public Boolean isABigFlower(@RequestBody Flower flower) { - return flowerService.isABigFlower(flower.getName(), flower.getPetals()); - } + @PostMapping("/isABigFlower") + public Boolean isABigFlower(@RequestBody Flower flower) { + return flowerService.isABigFlower(flower.getName(), flower.getPetals()); + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java index 16eb041044..4a6cb3f5d6 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java @@ -18,18 +18,18 @@ import java.util.UUID; @RequestMapping("/message") public class MessageController { - @Autowired - private MessageService messageService; + @Autowired + private MessageService messageService; - @PostMapping - public Message createMessage(@RequestBody MessageDTO messageDTO) { - Message message = new Message(); - message.setText(messageDTO.getText()); - message.setFrom(messageDTO.getFrom()); - message.setTo(messageDTO.getTo()); - message.setDate(Date.from(Instant.now())); - message.setId(UUID.randomUUID()); + @PostMapping + public Message createMessage(@RequestBody MessageDTO messageDTO) { + Message message = new Message(); + message.setText(messageDTO.getText()); + message.setFrom(messageDTO.getFrom()); + message.setTo(messageDTO.getTo()); + message.setDate(Date.from(Instant.now())); + message.setId(UUID.randomUUID()); - return messageService.deliverMessage(message); - } + return messageService.deliverMessage(message); + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java index beeccf763a..3f9265db0e 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java @@ -7,7 +7,7 @@ import com.baeldung.mockito.argumentmatchers.Message; @Service public class MessageService { - public Message deliverMessage (Message message) { + public Message deliverMessage(Message message) { return message; } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java index 722c4fff71..258de77cd5 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java @@ -5,5 +5,5 @@ import com.baeldung.mockito.junit5.User; public interface MailClient { void sendUserRegistrationMail(User user); - + } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java index b781747a45..fe1fbe4f13 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java @@ -3,7 +3,7 @@ package com.baeldung.mockito.junit5.service; import com.baeldung.mockito.junit5.User; public interface UserService { - + User register(User user); } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java index e7ee3a0aa6..5b2e57ae26 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java @@ -6,16 +6,16 @@ import java.util.stream.IntStream; public class StaticUtils { - private StaticUtils() { - } + private StaticUtils() { + } - public static List range(int start, int end) { - return IntStream.range(start, end) - .boxed() - .collect(Collectors.toList()); - } + public static List range(int start, int end) { + return IntStream.range(start, end) + .boxed() + .collect(Collectors.toList()); + } - public static String name() { - return "Baeldung"; - } + public static String name() { + return "Baeldung"; + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java index 87e8b5de77..c81e0bb79b 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java @@ -2,9 +2,9 @@ package com.baeldung.mockito; public final class FinalList extends MyList { - @Override - public int size() { - return 1; - } + @Override + public int size() { + return 1; + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java index 6877d7fb6a..bb7b076ea6 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java @@ -5,21 +5,21 @@ import java.util.Map; public class MyDictionary { - private Map wordMap; + private Map wordMap; - public MyDictionary() { - wordMap = new HashMap<>(); - } + public MyDictionary() { + wordMap = new HashMap<>(); + } - public MyDictionary(Map wordMap) { - this.wordMap = wordMap; - } + public MyDictionary(Map wordMap) { + this.wordMap = wordMap; + } - public void add(final String word, final String meaning) { - wordMap.put(word, meaning); - } + public void add(final String word, final String meaning) { + wordMap.put(word, meaning); + } - public String getMeaning(final String word) { - return wordMap.get(word); - } + public String getMeaning(final String word) { + return wordMap.get(word); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java index 8324af8ae8..ac3a76e04a 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java @@ -4,22 +4,22 @@ import java.util.AbstractList; public class MyList extends AbstractList { - @Override - public String get(final int index) { - return null; - } + @Override + public String get(final int index) { + return null; + } - @Override - public int size() { - return 1; - } + @Override + public int size() { + return 1; + } - @Override - public void add(int index, String element) { - // no-op - } + @Override + public void add(int index, String element) { + // no-op + } - final public int finalMethod() { - return 0; - } + final public int finalMethod() { + return 0; + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java index 5e12b5c34a..20c70ce27b 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java @@ -25,106 +25,106 @@ import com.baeldung.mockito.MyDictionary; @ExtendWith(MockitoExtension.class) class MockitoAnnotationUnitTest { - @Mock - private List mockedList; + @Mock + private List mockedList; - @Spy - private List spiedList = new ArrayList<>(); + @Spy + private List spiedList = new ArrayList<>(); - // Use either @ExtendWith(MockitoExtension.class) or manually openMocks in the @BeforeEach method - /* - @BeforeEach - public void init() { - MockitoAnnotations.openMocks(this); - } - */ + // Use either @ExtendWith(MockitoExtension.class) or manually openMocks in the @BeforeEach method + /* + @BeforeEach + public void init() { + MockitoAnnotations.openMocks(this); + } + */ - // tests + // tests - @Test - void whenNotUseMockAnnotation_thenCorrect() { - final List mockList = mock(ArrayList.class); + @Test + void whenNotUseMockAnnotation_thenCorrect() { + final List mockList = mock(ArrayList.class); - mockList.add("one"); - verify(mockList).add("one"); - assertEquals(0, mockList.size()); + mockList.add("one"); + verify(mockList).add("one"); + assertEquals(0, mockList.size()); - when(mockList.size()).thenReturn(100); - assertEquals(100, mockList.size()); - } + when(mockList.size()).thenReturn(100); + assertEquals(100, mockList.size()); + } - @Test - void whenUseMockAnnotation_thenMockIsInjected() { - mockedList.add("one"); - verify(mockedList).add("one"); - assertEquals(0, mockedList.size()); + @Test + void whenUseMockAnnotation_thenMockIsInjected() { + mockedList.add("one"); + verify(mockedList).add("one"); + assertEquals(0, mockedList.size()); - when(mockedList.size()).thenReturn(100); - assertEquals(100, mockedList.size()); - } + when(mockedList.size()).thenReturn(100); + assertEquals(100, mockedList.size()); + } - @Test - void whenNotUseSpyAnnotation_thenCorrect() { - final List spyList = spy(new ArrayList()); + @Test + void whenNotUseSpyAnnotation_thenCorrect() { + final List spyList = spy(new ArrayList()); - spyList.add("one"); - spyList.add("two"); + spyList.add("one"); + spyList.add("two"); - verify(spyList).add("one"); - verify(spyList).add("two"); + verify(spyList).add("one"); + verify(spyList).add("two"); - assertEquals(2, spyList.size()); + assertEquals(2, spyList.size()); - doReturn(100).when(spyList).size(); - assertEquals(100, spyList.size()); - } + doReturn(100).when(spyList).size(); + assertEquals(100, spyList.size()); + } - @Test - void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() { - spiedList.add("one"); - spiedList.add("two"); + @Test + void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() { + spiedList.add("one"); + spiedList.add("two"); - verify(spiedList).add("one"); - verify(spiedList).add("two"); + verify(spiedList).add("one"); + verify(spiedList).add("two"); - assertEquals(2, spiedList.size()); + assertEquals(2, spiedList.size()); - doReturn(100).when(spiedList).size(); - assertEquals(100, spiedList.size()); - } + doReturn(100).when(spiedList).size(); + assertEquals(100, spiedList.size()); + } - @Test - void whenNotUseCaptorAnnotation_thenCorrect() { - final List mockList = mock(List.class); - final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class); + @Test + void whenNotUseCaptorAnnotation_thenCorrect() { + final List mockList = mock(List.class); + final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class); - mockList.add("one"); - verify(mockList).add(arg.capture()); + mockList.add("one"); + verify(mockList).add(arg.capture()); - assertEquals("one", arg.getValue()); - } + assertEquals("one", arg.getValue()); + } - @Captor - private ArgumentCaptor argCaptor; + @Captor + private ArgumentCaptor argCaptor; - @Test - void whenUseCaptorAnnotation_thenTheSame() { - mockedList.add("one"); - verify(mockedList).add(argCaptor.capture()); + @Test + void whenUseCaptorAnnotation_thenTheSame() { + mockedList.add("one"); + verify(mockedList).add(argCaptor.capture()); - assertEquals("one", argCaptor.getValue()); - } + assertEquals("one", argCaptor.getValue()); + } - @Mock - private Map wordMap; + @Mock + private Map wordMap; - @InjectMocks - private MyDictionary dic = new MyDictionary(); + @InjectMocks + private MyDictionary dic = new MyDictionary(); - @Test - void whenUseInjectMocksAnnotation_thenCorrect() { - when(wordMap.get("aWord")).thenReturn("aMeaning"); + @Test + void whenUseInjectMocksAnnotation_thenCorrect() { + when(wordMap.get("aWord")).thenReturn("aMeaning"); - assertEquals("aMeaning", dic.getMeaning("aWord")); - } + assertEquals("aMeaning", dic.getMeaning("aWord")); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java index 437462fcb4..b8dadc6deb 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java @@ -13,16 +13,16 @@ import static org.mockito.Mockito.when; public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest { - @Rule - public MockitoRule initRule = MockitoJUnit.rule(); + @Rule + public MockitoRule initRule = MockitoJUnit.rule(); - @Mock - private List mockedList; + @Mock + private List mockedList; - @Test - public void whenUsingMockitoJUnitRule_thenMocksInitialized() { - when(mockedList.size()).thenReturn(41); + @Test + public void whenUsingMockitoJUnitRule_thenMocksInitialized() { + when(mockedList.size()).thenReturn(41); - assertThat(mockedList).hasSize(41); - } + assertThat(mockedList).hasSize(41); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java index 44b8d5ec8f..91dd30a20b 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java @@ -19,24 +19,24 @@ import com.baeldung.mockito.MyDictionary; @ExtendWith(MockitoExtension.class) class MockitoAnnotationsInjectIntoSpyUnitTest { - @BeforeEach - public void init() { - openMocks(this); - spyDic = spy(new MyDictionary(wordMap)); - } + @BeforeEach + public void init() { + openMocks(this); + spyDic = spy(new MyDictionary(wordMap)); + } - @Mock - private Map wordMap; + @Mock + private Map wordMap; - @InjectMocks - private MyDictionary dic = new MyDictionary(); + @InjectMocks + private MyDictionary dic = new MyDictionary(); - private MyDictionary spyDic; + private MyDictionary spyDic; - @Test - void whenUseInjectMocksAnnotation_thenCorrect() { - when(wordMap.get("aWord")).thenReturn("aMeaning"); + @Test + void whenUseInjectMocksAnnotation_thenCorrect() { + when(wordMap.get("aWord")).thenReturn("aMeaning"); - assertEquals("aMeaning", spyDic.getMeaning("aWord")); - } + assertEquals("aMeaning", spyDic.getMeaning("aWord")); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java index 1b7db32c37..7c317c6aca 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java @@ -10,13 +10,13 @@ import org.mockito.Mock; class MockitoAnnotationsUninitializedUnitTest { - @Mock - List mockedList; + @Mock + List mockedList; - @Test - void whenMockitoAnnotationsUninitialized_thenNPEThrown() { - assertThrows(NullPointerException.class, () -> { - when(mockedList.size()).thenReturn(1); - }); - } + @Test + void whenMockitoAnnotationsUninitialized_thenNPEThrown() { + assertThrows(NullPointerException.class, () -> { + when(mockedList.size()).thenReturn(1); + }); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java index a0d542e152..36c26659a6 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java @@ -18,84 +18,84 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class EmailServiceUnitTest { - @Mock - DeliveryPlatform platform; + @Mock + DeliveryPlatform platform; - @InjectMocks - EmailService emailService; + @InjectMocks + EmailService emailService; - @Captor - ArgumentCaptor emailCaptor; + @Captor + ArgumentCaptor emailCaptor; - @Captor - ArgumentCaptor credentialsCaptor; + @Captor + ArgumentCaptor credentialsCaptor; - @Test - void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() { - String to = "info@baeldung.com"; - String subject = "Using ArgumentCaptor"; - String body = "Hey, let'use ArgumentCaptor"; + @Test + void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() { + String to = "info@baeldung.com"; + String subject = "Using ArgumentCaptor"; + String body = "Hey, let'use ArgumentCaptor"; - emailService.send(to, subject, body, false); + emailService.send(to, subject, body, false); - verify(platform).deliver(emailCaptor.capture()); - Email emailCaptorValue = emailCaptor.getValue(); - assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY); - } + verify(platform).deliver(emailCaptor.capture()); + Email emailCaptorValue = emailCaptor.getValue(); + assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY); + } - @Test - void whenDoesSupportHtml_expectHTMLEmailFormat() { - String to = "info@baeldung.com"; - String subject = "Using ArgumentCaptor"; - String body = "Hey, let'use ArgumentCaptor"; + @Test + void whenDoesSupportHtml_expectHTMLEmailFormat() { + String to = "info@baeldung.com"; + String subject = "Using ArgumentCaptor"; + String body = "Hey, let'use ArgumentCaptor"; - emailService.send(to, subject, body, true); + emailService.send(to, subject, body, true); - verify(platform).deliver(emailCaptor.capture()); - Email value = emailCaptor.getValue(); - assertThat(value.getFormat()).isEqualTo(Format.HTML); - } + verify(platform).deliver(emailCaptor.capture()); + Email value = emailCaptor.getValue(); + assertThat(value.getFormat()).isEqualTo(Format.HTML); + } - @Test - void whenServiceRunning_expectUpResponse() { - when(platform.getServiceStatus()).thenReturn("OK"); + @Test + void whenServiceRunning_expectUpResponse() { + when(platform.getServiceStatus()).thenReturn("OK"); - ServiceStatus serviceStatus = emailService.checkServiceStatus(); + ServiceStatus serviceStatus = emailService.checkServiceStatus(); - assertThat(serviceStatus).isEqualTo(ServiceStatus.UP); - } + assertThat(serviceStatus).isEqualTo(ServiceStatus.UP); + } - @Test - void whenServiceNotRunning_expectDownResponse() { - when(platform.getServiceStatus()).thenReturn("Error"); + @Test + void whenServiceNotRunning_expectDownResponse() { + when(platform.getServiceStatus()).thenReturn("Error"); - ServiceStatus serviceStatus = emailService.checkServiceStatus(); + ServiceStatus serviceStatus = emailService.checkServiceStatus(); - assertThat(serviceStatus).isEqualTo(ServiceStatus.DOWN); - } + assertThat(serviceStatus).isEqualTo(ServiceStatus.DOWN); + } - @Test - void whenUsingArgumentMatcherForValidCredentials_expectTrue() { - Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); - when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); + @Test + void whenUsingArgumentMatcherForValidCredentials_expectTrue() { + Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); + when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); - assertTrue(emailService.authenticatedSuccessfully(credentials)); - } + assertTrue(emailService.authenticatedSuccessfully(credentials)); + } - @Test - void whenUsingArgumentCaptorForValidCredentials_expectTrue() { - Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); - when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); + @Test + void whenUsingArgumentCaptorForValidCredentials_expectTrue() { + Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); + when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); - assertTrue(emailService.authenticatedSuccessfully(credentials)); - assertThat(credentialsCaptor.getValue()).isEqualTo(credentials); - } + assertTrue(emailService.authenticatedSuccessfully(credentials)); + assertThat(credentialsCaptor.getValue()).isEqualTo(credentials); + } - @Test - void whenNotAuthenticated_expectFalse() { - Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key"); - when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); + @Test + void whenNotAuthenticated_expectFalse() { + Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key"); + when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); - assertFalse(emailService.authenticatedSuccessfully(credentials)); - } + assertFalse(emailService.authenticatedSuccessfully(credentials)); + } } \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java index 5db7f2e112..e9dcc4a774 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java @@ -24,57 +24,57 @@ import com.baeldung.mockito.argumentmatchers.service.FlowerService; @ExtendWith(MockitoExtension.class) class FlowerControllerUnitTest { - @InjectMocks - private FlowerController flowerController; + @InjectMocks + private FlowerController flowerController; - @Mock - private FlowerService flowerService; + @Mock + private FlowerService flowerService; - @Test - void givenPoppyFlower_whenUsingDoReturn_thenCorrect() { - doReturn("Flower").when(flowerService).analyze("poppy"); + @Test + void givenPoppyFlower_whenUsingDoReturn_thenCorrect() { + doReturn("Flower").when(flowerService).analyze("poppy"); - String response = flowerController.isAFlower("poppy"); - assertThat(response).isEqualTo("Flower"); - } + String response = flowerController.isAFlower("poppy"); + assertThat(response).isEqualTo("Flower"); + } - @Test - void givenAnyFlower_whenUsingArgumentMatcher_thenCorrect() { - when(flowerService.analyze(anyString())).thenReturn("Flower"); + @Test + void givenAnyFlower_whenUsingArgumentMatcher_thenCorrect() { + when(flowerService.analyze(anyString())).thenReturn("Flower"); - String response = flowerController.isAFlower("violetta"); - assertThat(response).isEqualTo("Flower"); - } + String response = flowerController.isAFlower("violetta"); + assertThat(response).isEqualTo("Flower"); + } - @Test - void givenIncorrectMatchers_whenUsingArgumentMatchers_thenThrowsError() { - assertThrows(InvalidUseOfMatchersException.class, - () -> when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true)); - } + @Test + void givenIncorrectMatchers_whenUsingArgumentMatchers_thenThrowsError() { + assertThrows(InvalidUseOfMatchersException.class, + () -> when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true)); + } - @Test - void givenCorrectMatchers_whenUsingArgumentMatchers_thenCorrect() { - when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true); + @Test + void givenCorrectMatchers_whenUsingArgumentMatchers_thenCorrect() { + when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true); - Flower flower = new Flower("poppy", 15); + Flower flower = new Flower("poppy", 15); - Boolean response = flowerController.isABigFlower(flower); - assertThat(response).isTrue(); - } + Boolean response = flowerController.isABigFlower(flower); + assertThat(response).isTrue(); + } - @Test - void givenMatchersOutsideofStubbing_whenUsingMatchersAsReturnValue_thenThrowsError() { - flowerController.isAFlower("poppy"); + @Test + void givenMatchersOutsideofStubbing_whenUsingMatchersAsReturnValue_thenThrowsError() { + flowerController.isAFlower("poppy"); - String orMatcher = or(eq("poppy"), endsWith("y")); - assertThrows(InvalidUseOfMatchersException.class, - () -> verify(flowerService).analyze(orMatcher)); - } + String orMatcher = or(eq("poppy"), endsWith("y")); + assertThrows(InvalidUseOfMatchersException.class, + () -> verify(flowerService).analyze(orMatcher)); + } - @Test - void givenMatchersAsOngoingStubbing_whenUsingMatchers_thenCorrect() { - flowerController.isAFlower("poppy"); + @Test + void givenMatchersAsOngoingStubbing_whenUsingMatchers_thenCorrect() { + flowerController.isAFlower("poppy"); - verify(flowerService).analyze(or(eq("poppy"), endsWith("y"))); - } + verify(flowerService).analyze(or(eq("poppy"), endsWith("y"))); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java index 5a64f37696..89548c9a99 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java @@ -17,38 +17,38 @@ import com.baeldung.mockito.argumentmatchers.service.MessageService; @ExtendWith(MockitoExtension.class) class MessageControllerUnitTest { - @InjectMocks - private MessageController messageController; + @InjectMocks + private MessageController messageController; - @Mock - private MessageService messageService; + @Mock + private MessageService messageService; - @Test - void givenMsg_whenVerifyUsingAnyMatcher_thenOk() { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setFrom("me"); - messageDTO.setTo("you"); - messageDTO.setText("Hello, you!"); + @Test + void givenMsg_whenVerifyUsingAnyMatcher_thenOk() { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setFrom("me"); + messageDTO.setTo("you"); + messageDTO.setText("Hello, you!"); - messageController.createMessage(messageDTO); + messageController.createMessage(messageDTO); - verify(messageService, times(1)).deliverMessage(any(Message.class)); - } + verify(messageService, times(1)).deliverMessage(any(Message.class)); + } - @Test - void givenMsg_whenVerifyUsingMessageMatcher_thenOk() { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setFrom("me"); - messageDTO.setTo("you"); - messageDTO.setText("Hello, you!"); + @Test + void givenMsg_whenVerifyUsingMessageMatcher_thenOk() { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setFrom("me"); + messageDTO.setTo("you"); + messageDTO.setText("Hello, you!"); - messageController.createMessage(messageDTO); + messageController.createMessage(messageDTO); - Message message = new Message(); - message.setFrom("me"); - message.setTo("you"); - message.setText("Hello, you!"); + Message message = new Message(); + message.setFrom("me"); + message.setTo("you"); + message.setText("Hello, you!"); - verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message))); - } + verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message))); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java index e50c8ac9d7..8834df6c38 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java @@ -12,10 +12,9 @@ public class MessageMatcher implements ArgumentMatcher { @Override public boolean matches(Message right) { - return left.getFrom().equals(right.getFrom()) && - left.getTo().equals(right.getTo()) && - left.getText().equals(right.getText()) && - right.getDate() != null && - right.getId() != null; + return left.getFrom().equals(right.getFrom()) && + left.getTo().equals(right.getTo()) && + left.getText().equals(right.getText()) && + right.getDate() != null && right.getId() != null; } } \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java index 4fd70007ab..c4551f43ec 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java @@ -19,87 +19,87 @@ import com.baeldung.mockito.MyList; class MockitoWhenThenExamplesUnitTest { - @Test - final void whenSimpleReturnBehaviourConfigured_thenCorrect() { - final MyList listMock = mock(MyList.class); - when(listMock.add(anyString())).thenReturn(false); + @Test + final void whenSimpleReturnBehaviourConfigured_thenCorrect() { + final MyList listMock = mock(MyList.class); + when(listMock.add(anyString())).thenReturn(false); - final boolean added = listMock.add(randomAlphabetic(6)); - assertThat(added).isFalse(); - } + final boolean added = listMock.add(randomAlphabetic(6)); + assertThat(added).isFalse(); + } - @Test - final void whenSimpleReturnBehaviourConfiguredAlternatively_thenCorrect() { - final MyList listMock = mock(MyList.class); - doReturn(false).when(listMock).add(anyString()); + @Test + final void whenSimpleReturnBehaviourConfiguredAlternatively_thenCorrect() { + final MyList listMock = mock(MyList.class); + doReturn(false).when(listMock).add(anyString()); - final boolean added = listMock.add(randomAlphabetic(6)); - assertThat(added).isFalse(); - } + final boolean added = listMock.add(randomAlphabetic(6)); + assertThat(added).isFalse(); + } - @Test - final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() { - final MyList listMock = mock(MyList.class); - when(listMock.add(anyString())).thenThrow(IllegalStateException.class); + @Test + final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() { + final MyList listMock = mock(MyList.class); + when(listMock.add(anyString())).thenThrow(IllegalStateException.class); - assertThrows(IllegalStateException.class, () -> listMock.add(randomAlphabetic(6))); - } + assertThrows(IllegalStateException.class, () -> listMock.add(randomAlphabetic(6))); + } - @Test - final void givenMethodHasNoReturnType_whenCallingMethod_thenExceptionIsThrown() { - final MyList listMock = mock(MyList.class); - doThrow(NullPointerException.class).when(listMock).clear(); + @Test + final void givenMethodHasNoReturnType_whenCallingMethod_thenExceptionIsThrown() { + final MyList listMock = mock(MyList.class); + doThrow(NullPointerException.class).when(listMock).clear(); - assertThrows(NullPointerException.class, () -> listMock.clear()); - } + assertThrows(NullPointerException.class, () -> listMock.clear()); + } - @Test - final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() { - final MyList listMock = mock(MyList.class); - when(listMock.add(anyString())) - .thenReturn(false) - .thenThrow(IllegalStateException.class); + @Test + final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() { + final MyList listMock = mock(MyList.class); + when(listMock.add(anyString())) + .thenReturn(false) + .thenThrow(IllegalStateException.class); - assertThrows(IllegalStateException.class, () -> { - listMock.add(randomAlphabetic(6)); - listMock.add(randomAlphabetic(6)); - }); - } + assertThrows(IllegalStateException.class, () -> { + listMock.add(randomAlphabetic(6)); + listMock.add(randomAlphabetic(6)); + }); + } - @Test - final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() { - final MyList listMock = mock(MyList.class); - when(listMock.add(anyString())) - .thenReturn(false) - .thenThrow(IllegalStateException.class); + @Test + final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() { + final MyList listMock = mock(MyList.class); + when(listMock.add(anyString())) + .thenReturn(false) + .thenThrow(IllegalStateException.class); - assertThatNoException().isThrownBy(() -> listMock.add(randomAlphabetic(6))); - } + assertThatNoException().isThrownBy(() -> listMock.add(randomAlphabetic(6))); + } - @Test - final void whenSpyBehaviourConfigured_thenCorrect() { - final MyList instance = new MyList(); - final MyList spy = spy(instance); + @Test + final void whenSpyBehaviourConfigured_thenCorrect() { + final MyList instance = new MyList(); + final MyList spy = spy(instance); - doThrow(NullPointerException.class).when(spy).size(); + doThrow(NullPointerException.class).when(spy).size(); - assertThrows(NullPointerException.class, () -> spy.size()); - } + assertThrows(NullPointerException.class, () -> spy.size()); + } - @Test - final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() { - final MyList listMock = mock(MyList.class); - when(listMock.size()).thenCallRealMethod(); + @Test + final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() { + final MyList listMock = mock(MyList.class); + when(listMock.size()).thenCallRealMethod(); - assertThat(listMock).hasSize(1); - } + assertThat(listMock).hasSize(1); + } - @Test - final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenCustomerAnswerIsCalled() { - final MyList listMock = mock(MyList.class); - doAnswer(invocation -> "Always the same").when(listMock).get(anyInt()); + @Test + final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenCustomerAnswerIsCalled() { + final MyList listMock = mock(MyList.class); + doAnswer(invocation -> "Always the same").when(listMock).get(anyInt()); - final String element = listMock.get(1); - assertThat(element).isEqualTo("Always the same"); - } + final String element = listMock.get(1); + assertThat(element).isEqualTo("Always the same"); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java index b612749328..112a6fd7b6 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java @@ -13,45 +13,46 @@ import com.baeldung.mockito.MyDictionary; class MockitoExceptionUnitTest { - @Test - void givenNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() { - MyDictionary dictMock = mock(MyDictionary.class); - when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class); + @Test + void givenNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class); - assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word")); - } + assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word")); + } - @Test - void givenVoidReturnType_whenUsingDoThrow_thenExceptionIsThrown() { - MyDictionary dictMock = mock(MyDictionary.class); - doThrow(IllegalStateException.class).when(dictMock).add(anyString(), anyString()); - - assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning")); - } + @Test + void givenVoidReturnType_whenUsingDoThrow_thenExceptionIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + doThrow(IllegalStateException.class).when(dictMock) + .add(anyString(), anyString()); - @Test - void givenNonVoidReturnType_whenUsingWhenThenAndExeceptionAsNewObject_thenExceptionIsThrown() { - MyDictionary dictMock = mock(MyDictionary.class); - when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred")); - - assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word")); - } + assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning")); + } - @Test - void givenNonVoidReturnType_whenUsingDoThrowAndExeceptionAsNewObject_thenExceptionIsThrown() { - MyDictionary dictMock = mock(MyDictionary.class); - doThrow(new IllegalStateException("Error occurred")).when(dictMock).add(anyString(), anyString()); - - assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning")); + @Test + void givenNonVoidReturnType_whenUsingWhenThenAndExeceptionAsNewObject_thenExceptionIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred")); - } + assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word")); + } - @Test - void givenSpyAndNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() { - MyDictionary dict = new MyDictionary(); - MyDictionary spy = Mockito.spy(dict); - when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class); - - assertThrows(NullPointerException.class, () -> spy.getMeaning("word")); - } + @Test + void givenNonVoidReturnType_whenUsingDoThrowAndExeceptionAsNewObject_thenExceptionIsThrown() { + MyDictionary dictMock = mock(MyDictionary.class); + doThrow(new IllegalStateException("Error occurred")).when(dictMock).add(anyString(), anyString()); + + assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning")); + + } + + @Test + void givenSpyAndNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() { + MyDictionary dict = new MyDictionary(); + MyDictionary spy = Mockito.spy(dict); + when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class); + + assertThrows(NullPointerException.class, () -> spy.getMeaning("word")); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java index 461e377a39..45eb42a00f 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java @@ -43,14 +43,14 @@ class UserServiceUnitTest { @BeforeEach void init(@Mock SettingRepository settingRepository) { userService = new DefaultUserService(userRepository, settingRepository, mailClient); - + lenient().when(settingRepository.getUserMinAge()).thenReturn(10); - + when(settingRepository.getUserNameMinLength()).thenReturn(4); - + lenient().when(userRepository.isUsernameAlreadyExists(any(String.class))) .thenReturn(false); - + this.settingRepository = settingRepository; } @@ -80,8 +80,8 @@ class UserServiceUnitTest { verify(mailClient).sendUserRegistrationMail(insertedUser); } - //additional tests - + // additional tests + @Test void givenShortName_whenSaveUser_thenGiveShortUsernameError() { // Given diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java index 10fd480015..705f2ac7ad 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java @@ -11,21 +11,21 @@ import com.baeldung.mockito.MyList; class MockFinalsUnitTest { - @Test - void whenMockFinalMethod_thenMockWorks() { + @Test + void whenMockFinalMethod_thenMockWorks() { - MyList mock = mock(MyList.class); - when(mock.finalMethod()).thenReturn(1); + MyList mock = mock(MyList.class); + when(mock.finalMethod()).thenReturn(1); - assertThat(mock.finalMethod()).isNotZero(); - } + assertThat(mock.finalMethod()).isNotZero(); + } - @Test - void whenMockFinalClass_thenMockWorks() { + @Test + void whenMockFinalClass_thenMockWorks() { - FinalList mock = mock(FinalList.class); - when(mock.size()).thenReturn(2); + FinalList mock = mock(FinalList.class); + when(mock.size()).thenReturn(2); - assertThat(mock.size()).isNotEqualTo(1); - } + assertThat(mock.size()).isNotEqualTo(1); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java index 0a113ed143..696208c9ec 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java @@ -20,54 +20,54 @@ import com.baeldung.mockito.MyList; class MockitoMockMethodsUnitTest { - @Test - void whenUsingSimpleMock_thenCorrect() { - MyList listMock = mock(MyList.class); - when(listMock.add(anyString())).thenReturn(false); + @Test + void whenUsingSimpleMock_thenCorrect() { + MyList listMock = mock(MyList.class); + when(listMock.add(anyString())).thenReturn(false); - boolean added = listMock.add(randomAlphabetic(6)); + boolean added = listMock.add(randomAlphabetic(6)); - assertThat(added).isFalse(); - verify(listMock).add(anyString()); - } + assertThat(added).isFalse(); + verify(listMock).add(anyString()); + } - @Test - void givenFewActualInvocationThanConfigured_whenUsingMockWithName_thenExceptionIsThrown() { - MyList listMock = mock(MyList.class, "myMock"); - - when(listMock.add(anyString())).thenReturn(false); - listMock.add(randomAlphabetic(6)); + @Test + void givenFewActualInvocationThanConfigured_whenUsingMockWithName_thenExceptionIsThrown() { + MyList listMock = mock(MyList.class, "myMock"); - assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString())) - .isInstanceOf(TooFewActualInvocations.class) - .hasMessageContaining("myMock.add"); - } + when(listMock.add(anyString())).thenReturn(false); + listMock.add(randomAlphabetic(6)); - private static class CustomAnswer implements Answer { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return false; - } - } + assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString())) + .isInstanceOf(TooFewActualInvocations.class) + .hasMessageContaining("myMock.add"); + } - @Test - void whenUsingMockWithAnswer_thenCorrect() { - MyList listMock = mock(MyList.class, new CustomAnswer()); - boolean added = listMock.add(randomAlphabetic(6)); + private static class CustomAnswer implements Answer { - verify(listMock).add(anyString()); - assertThat(added).isFalse(); - } + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + return false; + } + } - @Test - void whenUsingMockWithSettings_thenCorrect() { - MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer()); - MyList listMock = mock(MyList.class, customSettings); - - boolean added = listMock.add(randomAlphabetic(6)); + @Test + void whenUsingMockWithAnswer_thenCorrect() { + MyList listMock = mock(MyList.class, new CustomAnswer()); + boolean added = listMock.add(randomAlphabetic(6)); - verify(listMock).add(anyString()); - assertThat(added).isFalse(); - } + verify(listMock).add(anyString()); + assertThat(added).isFalse(); + } + + @Test + void whenUsingMockWithSettings_thenCorrect() { + MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer()); + MyList listMock = mock(MyList.class, customSettings); + + boolean added = listMock.add(randomAlphabetic(6)); + + verify(listMock).add(anyString()); + assertThat(added).isFalse(); + } } \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java index 0d653940a4..b9268f3c6a 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java @@ -12,30 +12,30 @@ import java.util.Arrays; class MockStaticUnitTest { - @Test - void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() { - assertThat(StaticUtils.name()).isEqualTo("Baeldung"); + @Test + void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() { + assertThat(StaticUtils.name()).isEqualTo("Baeldung"); - try (MockedStatic utilities = mockStatic(StaticUtils.class)) { - utilities.when(StaticUtils::name).thenReturn("Eugen"); - assertThat(StaticUtils.name()).isEqualTo("Eugen"); - } + try (MockedStatic utilities = mockStatic(StaticUtils.class)) { + utilities.when(StaticUtils::name).thenReturn("Eugen"); + assertThat(StaticUtils.name()).isEqualTo("Eugen"); + } - assertThat(StaticUtils.name()).isEqualTo("Baeldung"); - } + assertThat(StaticUtils.name()).isEqualTo("Baeldung"); + } - @Test - void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() { - assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); + @Test + void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() { + assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); - try (MockedStatic utilities = mockStatic(StaticUtils.class)) { - utilities.when(() -> StaticUtils.range(2, 6)) - .thenReturn(Arrays.asList(10, 11, 12)); + try (MockedStatic utilities = mockStatic(StaticUtils.class)) { + utilities.when(() -> StaticUtils.range(2, 6)) + .thenReturn(Arrays.asList(10, 11, 12)); - assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12); - } + assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12); + } - assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); - } + assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java index e1023c5e57..0a510ba6cb 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java @@ -18,14 +18,14 @@ class MockitoMisusingMockOrSpyUnitTest { List list = new ArrayList(); assertThatThrownBy(() -> doReturn(100).when(list).size()) - .isInstanceOf(NotAMockException.class) - .hasMessageContaining("Argument passed to when() is not a mock!"); + .isInstanceOf(NotAMockException.class) + .hasMessageContaining("Argument passed to when() is not a mock!"); } - + @Test void givenASpy_whenDoReturn_thenNoError() { final List spyList = spy(new ArrayList<>()); - + assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size()); } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java index d154044191..400de07886 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java @@ -18,64 +18,64 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MockitoSpyUnitTest { - @Test - void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() { - final List list = new ArrayList(); - final List spyList = spy(list); + @Test + void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() { + final List list = new ArrayList(); + final List spyList = spy(list); - spyList.add("one"); - spyList.add("two"); + spyList.add("one"); + spyList.add("two"); - verify(spyList).add("one"); - verify(spyList).add("two"); + verify(spyList).add("one"); + verify(spyList).add("two"); - assertThat(spyList).hasSize(2); - } + assertThat(spyList).hasSize(2); + } - @Spy - private List aSpyList = new ArrayList(); + @Spy + private List aSpyList = new ArrayList(); - @Test - void givenUsingSpyAnnotation_whenSpyingOnList_thenCorrect() { - aSpyList.add("one"); - aSpyList.add("two"); + @Test + void givenUsingSpyAnnotation_whenSpyingOnList_thenCorrect() { + aSpyList.add("one"); + aSpyList.add("two"); - verify(aSpyList).add("one"); - verify(aSpyList).add("two"); + verify(aSpyList).add("one"); + verify(aSpyList).add("two"); - assertThat(aSpyList).hasSize(2); - } + assertThat(aSpyList).hasSize(2); + } - @Test - void givenASpy_whenStubbingTheBehaviour_thenCorrect() { - final List list = new ArrayList(); - final List spyList = spy(list); + @Test + void givenASpy_whenStubbingTheBehaviour_thenCorrect() { + final List list = new ArrayList(); + final List spyList = spy(list); - assertEquals(0, spyList.size()); + assertEquals(0, spyList.size()); - doReturn(100).when(spyList).size(); - - assertThat(spyList).hasSize(100); - } + doReturn(100).when(spyList).size(); - @Test - void whenCreateMock_thenCreated() { - final List mockedList = mock(ArrayList.class); + assertThat(spyList).hasSize(100); + } - mockedList.add("one"); - verify(mockedList).add("one"); + @Test + void whenCreateMock_thenCreated() { + final List mockedList = mock(ArrayList.class); - assertThat(mockedList).hasSize(0); - } + mockedList.add("one"); + verify(mockedList).add("one"); - @Test - void whenCreateSpy_thenCreate() { - final List spyList = spy(new ArrayList<>()); + assertThat(mockedList).hasSize(0); + } - spyList.add("one"); - verify(spyList).add("one"); + @Test + void whenCreateSpy_thenCreate() { + final List spyList = spy(new ArrayList<>()); - assertThat(spyList).hasSize(1); - } + spyList.add("one"); + verify(spyList).add("one"); + + assertThat(spyList).hasSize(1); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java index 383231b458..902bad33f5 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java @@ -25,102 +25,102 @@ import com.google.common.collect.Lists; class MockitoVerifyExamplesUnitTest { - @Test - final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); - verify(mockedList).size(); - } + @Test + final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); + verify(mockedList).size(); + } - @Test - final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); - verify(mockedList, times(1)).size(); - } + @Test + final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); + verify(mockedList, times(1)).size(); + } - @Test - final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - verifyNoInteractions(mockedList); - } + @Test + final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + verifyNoInteractions(mockedList); + } - @Test - final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - verify(mockedList, times(0)).size(); - } + @Test + final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + verify(mockedList, times(0)).size(); + } - @Test - final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() { - final List mockedList = mock(MyList.class); - mockedList.size(); - mockedList.clear(); + @Test + final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() { + final List mockedList = mock(MyList.class); + mockedList.size(); + mockedList.clear(); - verify(mockedList).size(); + verify(mockedList).size(); - assertThrows(NoInteractionsWanted.class, () -> verifyNoMoreInteractions(mockedList)); - } + assertThrows(NoInteractionsWanted.class, () -> verifyNoMoreInteractions(mockedList)); + } - @Test - final void givenInteractionsInOrder_whenVerifyingOrderOfInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); - mockedList.add("a parameter"); - mockedList.clear(); + @Test + final void givenInteractionsInOrder_whenVerifyingOrderOfInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); + mockedList.add("a parameter"); + mockedList.clear(); - final InOrder inOrder = inOrder(mockedList); - inOrder.verify(mockedList).size(); - inOrder.verify(mockedList).add("a parameter"); - inOrder.verify(mockedList).clear(); - } + final InOrder inOrder = inOrder(mockedList); + inOrder.verify(mockedList).size(); + inOrder.verify(mockedList).add("a parameter"); + inOrder.verify(mockedList).clear(); + } - @Test - final void givenNoInteraction_whenVerifyingAnInteraction_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); + @Test + final void givenNoInteraction_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); - verify(mockedList, never()).clear(); - } + verify(mockedList, never()).clear(); + } - @Test - final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.clear(); - mockedList.clear(); - mockedList.clear(); + @Test + final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.clear(); + mockedList.clear(); + mockedList.clear(); - verify(mockedList, atLeast(1)).clear(); - verify(mockedList, atMost(10)).clear(); - } + verify(mockedList, atLeast(1)).clear(); + verify(mockedList, atMost(10)).clear(); + } - // with arguments + // with arguments - @Test - final void givenInteractionWithExactArgument_whenVerifyingAnInteraction_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.add("test"); + @Test + final void givenInteractionWithExactArgument_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.add("test"); - verify(mockedList).add("test"); - } + verify(mockedList).add("test"); + } - @Test - final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.add("test"); + @Test + final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.add("test"); - verify(mockedList).add(anyString()); - } + verify(mockedList).add(anyString()); + } - @Test - final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.addAll(Lists. newArrayList("someElement")); + @Test + final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.addAll(Lists. newArrayList("someElement")); - final ArgumentCaptor> argumentCaptor = ArgumentCaptor.forClass(List.class); - verify(mockedList).addAll(argumentCaptor.capture()); + final ArgumentCaptor> argumentCaptor = ArgumentCaptor.forClass(List.class); + verify(mockedList).addAll(argumentCaptor.capture()); - final List capturedArgument = argumentCaptor.getValue(); - assertThat(capturedArgument).contains("someElement"); - } + final List capturedArgument = argumentCaptor.getValue(); + assertThat(capturedArgument).contains("someElement"); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java index ef4f91139d..ee8c36435a 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java @@ -20,69 +20,71 @@ import com.baeldung.mockito.MyList; class MockitoVoidMethodsUnitTest { - @Test - void whenAddCalled_thenVerified() { - MyList myList = mock(MyList.class); - doNothing().when(myList).add(isA(Integer.class), isA(String.class)); - myList.add(0, ""); - - verify(myList, times(1)).add(0, ""); - } - - @Test - void whenAddCalled_thenVerified2() { - MyList myList = mock(MyList.class); - myList.add(0, ""); + @Test + void whenAddCalled_thenVerified() { + MyList myList = mock(MyList.class); + doNothing().when(myList).add(isA(Integer.class), isA(String.class)); + myList.add(0, ""); - verify(myList, times(1)).add(0, ""); - } + verify(myList, times(1)).add(0, ""); + } - @Test - void givenNull_whenAddCalled_thenThrowsException() { - MyList myList = mock(MyList.class); - - assertThrows(Exception.class, () -> { - doThrow().when(myList).add(isA(Integer.class), isNull()); - }); + @Test + void whenAddCalled_thenVerified2() { + MyList myList = mock(MyList.class); + myList.add(0, ""); - myList.add(0, null); - } + verify(myList, times(1)).add(0, ""); + } - @Test - void givenArgumentCaptor_whenAddCalled_thenValueCaptured() { - MyList myList = mock(MyList.class); - - ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); - doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); - - myList.add(0, "captured"); + @Test + void givenNull_whenAddCalled_thenThrowsException() { + MyList myList = mock(MyList.class); - assertEquals("captured", valueCapture.getValue()); - } + assertThrows(Exception.class, () -> { + doThrow().when(myList).add(isA(Integer.class), isNull()); + }); - @Test - void givenDoAnswer_whenAddCalled_thenAnswered() { - MyList myList = mock(MyList.class); + myList.add(0, null); + } - doAnswer(invocation -> { - Object arg0 = invocation.getArgument(0); - Object arg1 = invocation.getArgument(1); + @Test + void givenArgumentCaptor_whenAddCalled_thenValueCaptured() { + MyList myList = mock(MyList.class); - assertEquals(3, arg0); - assertEquals("answer me", arg1); - return null; - }).when(myList).add(any(Integer.class), any(String.class)); - - myList.add(3, "answer me"); - } + ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); + doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); - @Test - void givenDoCallRealMethod_whenAddCalled_thenRealMethodCalled() { - MyList myList = mock(MyList.class); - - doCallRealMethod().when(myList).add(any(Integer.class), any(String.class)); - myList.add(1, "real"); + myList.add(0, "captured"); - verify(myList, times(1)).add(1, "real"); - } + assertEquals("captured", valueCapture.getValue()); + } + + @Test + void givenDoAnswer_whenAddCalled_thenAnswered() { + MyList myList = mock(MyList.class); + + doAnswer(invocation -> { + Object arg0 = invocation.getArgument(0); + Object arg1 = invocation.getArgument(1); + + assertEquals(3, arg0); + assertEquals("answer me", arg1); + return null; + }).when(myList) + .add(any(Integer.class), any(String.class)); + + myList.add(3, "answer me"); + } + + @Test + void givenDoCallRealMethod_whenAddCalled_thenRealMethodCalled() { + MyList myList = mock(MyList.class); + + doCallRealMethod().when(myList) + .add(any(Integer.class), any(String.class)); + myList.add(1, "real"); + + verify(myList, times(1)).add(1, "real"); + } } From 585d1e1575b51e50c0103ca65c0fe90ed1f5f9a7 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Tue, 16 May 2023 23:06:58 +0530 Subject: [PATCH 22/46] JAVA-13721 Further formatting of files --- .../argumentcaptor/AuthenticationStatus.java | 4 +--- .../mockito/argumentcaptor/ServiceStatus.java | 4 +--- .../argumentmatchers/service/FlowerService.java | 6 +++--- .../java/com/baeldung/mockito/junit5/User.java | 13 +++++++++---- .../junit5/repository/SettingRepository.java | 2 +- .../junit5/repository/UserRepository.java | 3 ++- .../junit5/service/DefaultUserService.java | 17 +++++++++-------- .../baeldung/mockito/junit5/service/Errors.java | 2 +- 8 files changed, 27 insertions(+), 24 deletions(-) diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/AuthenticationStatus.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/AuthenticationStatus.java index 8307b4323b..0ba8a70021 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/AuthenticationStatus.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/AuthenticationStatus.java @@ -1,7 +1,5 @@ package com.baeldung.mockito.argumentcaptor; public enum AuthenticationStatus { - AUTHENTICATED, - NOT_AUTHENTICATED, - ERROR + AUTHENTICATED, NOT_AUTHENTICATED, ERROR } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/ServiceStatus.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/ServiceStatus.java index 65def5af64..3951174b30 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/ServiceStatus.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/ServiceStatus.java @@ -1,7 +1,5 @@ package com.baeldung.mockito.argumentcaptor; public enum ServiceStatus { - UP, - DOWN, - AUTHENTICATED + UP, DOWN, AUTHENTICATED } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/FlowerService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/FlowerService.java index 364f2b57d7..f654638fd3 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/FlowerService.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/FlowerService.java @@ -11,15 +11,15 @@ public class FlowerService { private List flowers = Arrays.asList("Poppy", "Ageratum", "Carnation", "Diascia", "Lantana"); public String analyze(String name) { - if(flowers.contains(name)) { + if (flowers.contains(name)) { return "flower"; } return null; } public boolean isABigFlower(String name, int petals) { - if(flowers.contains(name)) { - if(petals > 10) { + if (flowers.contains(name)) { + if (petals > 10) { return true; } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/User.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/User.java index 0f0b93e30b..4457d59b02 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/User.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/User.java @@ -1,34 +1,39 @@ package com.baeldung.mockito.junit5; public class User { - + private Integer id; private String name; private int age; - + public User() { } - + public User(String name, int age) { this.name = name; this.age = age; } - + public Integer getId() { return id; } + public void setId(Integer id) { this.id = 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/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/SettingRepository.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/SettingRepository.java index 78249c9fd9..094be12770 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/SettingRepository.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/SettingRepository.java @@ -1,7 +1,7 @@ package com.baeldung.mockito.junit5.repository; public interface SettingRepository { - + int getUserMinAge(); int getUserNameMinLength(); diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/UserRepository.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/UserRepository.java index 5ce624b73b..9bc1b0d38c 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/UserRepository.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/UserRepository.java @@ -5,6 +5,7 @@ import com.baeldung.mockito.junit5.User; public interface UserRepository { User insert(User user); + boolean isUsernameAlreadyExists(String userName); - + } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/DefaultUserService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/DefaultUserService.java index c239bba2b3..bad4e46682 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/DefaultUserService.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/DefaultUserService.java @@ -6,11 +6,11 @@ import com.baeldung.mockito.junit5.repository.SettingRepository; import com.baeldung.mockito.junit5.repository.UserRepository; public class DefaultUserService implements UserService { - + private UserRepository userRepository; private SettingRepository settingRepository; private MailClient mailClient; - + public DefaultUserService(UserRepository userRepository, SettingRepository settingRepository, MailClient mailClient) { this.userRepository = userRepository; this.settingRepository = settingRepository; @@ -26,19 +26,20 @@ public class DefaultUserService implements UserService { } private void validate(User user) { - if(user.getName() == null) { + if (user.getName() == null) { throw new RuntimeException(Errors.USER_NAME_REQUIRED); } - if(user.getName().length() < settingRepository.getUserNameMinLength()) { + if (user.getName() + .length() < settingRepository.getUserNameMinLength()) { throw new RuntimeException(Errors.USER_NAME_SHORT); } - - if(user.getAge() < settingRepository.getUserMinAge()) { + + if (user.getAge() < settingRepository.getUserMinAge()) { throw new RuntimeException(Errors.USER_AGE_YOUNG); } - - if(userRepository.isUsernameAlreadyExists(user.getName())) { + + if (userRepository.isUsernameAlreadyExists(user.getName())) { throw new RuntimeException(Errors.USER_NAME_DUPLICATE); } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/Errors.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/Errors.java index c46688f484..8a6882124a 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/Errors.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/Errors.java @@ -6,5 +6,5 @@ public class Errors { public static final String USER_NAME_SHORT = "user.name.short"; public static final String USER_AGE_YOUNG = "user.age.young"; public static final String USER_NAME_DUPLICATE = "user.name.duplicate"; - + } From a96f8f3e75dbfcbec73413118cfa877ffe1632a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20G=C5=82=C3=B3wka?= Date: Tue, 16 May 2023 20:45:11 +0200 Subject: [PATCH 23/46] BAEL-4369: Multiple ways of declaring dependency versions in Gradle (#13825) --- .../dependency-version/.gitattributes | 9 + .../gradle-7/dependency-version/.gitignore | 5 + .../gradle-7/dependency-version/build.gradle | 19 ++ .../gradle/wrapper/gradle-wrapper.properties | 6 + .../gradle-7/dependency-version/gradlew | 244 ++++++++++++++++++ .../gradle-7/dependency-version/gradlew.bat | 92 +++++++ .../dependency-version/settings.gradle | 10 + 7 files changed, 385 insertions(+) create mode 100644 gradle-modules/gradle-7/dependency-version/.gitattributes create mode 100644 gradle-modules/gradle-7/dependency-version/.gitignore create mode 100644 gradle-modules/gradle-7/dependency-version/build.gradle create mode 100644 gradle-modules/gradle-7/dependency-version/gradle/wrapper/gradle-wrapper.properties create mode 100755 gradle-modules/gradle-7/dependency-version/gradlew create mode 100644 gradle-modules/gradle-7/dependency-version/gradlew.bat create mode 100644 gradle-modules/gradle-7/dependency-version/settings.gradle diff --git a/gradle-modules/gradle-7/dependency-version/.gitattributes b/gradle-modules/gradle-7/dependency-version/.gitattributes new file mode 100644 index 0000000000..097f9f98d9 --- /dev/null +++ b/gradle-modules/gradle-7/dependency-version/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/gradle-modules/gradle-7/dependency-version/.gitignore b/gradle-modules/gradle-7/dependency-version/.gitignore new file mode 100644 index 0000000000..1b6985c009 --- /dev/null +++ b/gradle-modules/gradle-7/dependency-version/.gitignore @@ -0,0 +1,5 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/gradle-modules/gradle-7/dependency-version/build.gradle b/gradle-modules/gradle-7/dependency-version/build.gradle new file mode 100644 index 0000000000..7a8b51f5cc --- /dev/null +++ b/gradle-modules/gradle-7/dependency-version/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'java' +} + +group = "com.baeldung.gradle" +version = "1.0.0-SNAPSHOT" +sourceCompatibility = JavaVersion.VERSION_17 + +repositories { + mavenLocal() + mavenCentral() +} + +dependencies { + implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0' + implementation group: 'org.apache.commons', name: 'commons-collections4', version: '4.+' + implementation group: 'org.apache.commons', name: 'commons-math3', version: '[3.4, 3.5)' + implementation group: 'org.apache.commons', name: 'commons-text', version: 'latest.release' +} \ No newline at end of file diff --git a/gradle-modules/gradle-7/dependency-version/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-7/dependency-version/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..bdc9a83b1e --- /dev/null +++ b/gradle-modules/gradle-7/dependency-version/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradle-modules/gradle-7/dependency-version/gradlew b/gradle-modules/gradle-7/dependency-version/gradlew new file mode 100755 index 0000000000..79a61d421c --- /dev/null +++ b/gradle-modules/gradle-7/dependency-version/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# 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*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# 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/dependency-version/gradlew.bat b/gradle-modules/gradle-7/dependency-version/gradlew.bat new file mode 100644 index 0000000000..93e3f59f13 --- /dev/null +++ b/gradle-modules/gradle-7/dependency-version/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/gradle-modules/gradle-7/dependency-version/settings.gradle b/gradle-modules/gradle-7/dependency-version/settings.gradle new file mode 100644 index 0000000000..a2e76e5b21 --- /dev/null +++ b/gradle-modules/gradle-7/dependency-version/settings.gradle @@ -0,0 +1,10 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/8.0.2/userguide/multi_project_builds.html + */ + +rootProject.name = 'dependency-version' From 00ca91bd5840f218fafe150073ff883c4c0dd4f7 Mon Sep 17 00:00:00 2001 From: thibaultfaure Date: Tue, 16 May 2023 20:59:16 +0200 Subject: [PATCH 24/46] =?UTF-8?q?BAEL-6246=20Code=20for=20the=20article=20?= =?UTF-8?q?Send=20MultipartFile=20Request=20with=20RestAs=E2=80=A6=20(#138?= =?UTF-8?q?03)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * BAEL-6246 Code for the article Send MultipartFile Request with RestAssured * Fix code style in rest assured integration tests --------- Co-authored-by: thibault.faure --- testing-modules/rest-assured/pom.xml | 12 +- .../RestAssured2IntegrationTest.java | 42 +++---- .../RestAssuredIntegrationTest.java | 69 +++++------ .../RestAssuredMultipartIntegrationTest.java | 107 ++++++++++++++++++ .../RestAssuredXML2IntegrationTest.java | 37 +++--- .../RestAssuredXMLIntegrationTest.java | 48 ++++---- .../src/test/resources/baeldung.txt | 1 + .../src/test/resources/helloworld.txt | 1 + 8 files changed, 215 insertions(+), 102 deletions(-) create mode 100644 testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredMultipartIntegrationTest.java create mode 100644 testing-modules/rest-assured/src/test/resources/baeldung.txt create mode 100644 testing-modules/rest-assured/src/test/resources/helloworld.txt diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index b19ad1270a..647411e567 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -139,16 +139,25 @@ io.rest-assured rest-assured + ${rest-assured.version} test io.rest-assured spring-mock-mvc + ${rest-assured.version} test io.rest-assured json-schema-validator + ${rest-assured.version} + test + + + io.rest-assured + xml-path + ${rest-assured.version} test @@ -172,8 +181,9 @@ 2.9.6 1.1 1.2 - 2.4.1 + 2.27.2 2.5.3 + 5.3.0 \ No newline at end of file diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java index c579f1c260..8de7e6dad6 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java @@ -1,14 +1,8 @@ package com.baeldung.restassured; -import com.github.tomakehurst.wiremock.WireMockServer; -import io.restassured.RestAssured; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.containing; -import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; @@ -16,6 +10,14 @@ import static io.restassured.RestAssured.get; import static io.restassured.RestAssured.with; import static org.hamcrest.Matchers.hasItems; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.github.tomakehurst.wiremock.WireMockServer; + +import io.restassured.RestAssured; + public class RestAssured2IntegrationTest { private static WireMockServer wireMockServer; @@ -24,44 +26,42 @@ public class RestAssured2IntegrationTest { private static final String ODDS = getJson(); @BeforeClass - public static void before() throws Exception { + public static void before() { System.out.println("Setting up!"); final int port = Util.getAvailablePort(); wireMockServer = new WireMockServer(port); wireMockServer.start(); configureFor("localhost", port); RestAssured.port = port; - stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( - aResponse().withStatus(200) + stubFor(com.github.tomakehurst.wiremock.client.WireMock.get(urlEqualTo(EVENTS_PATH)) + .willReturn(aResponse().withStatus(200) .withHeader("Content-Type", APPLICATION_JSON) .withBody(ODDS))); - stubFor(post(urlEqualTo("/odds/new")) - .withRequestBody(containing("{\"price\":5.25,\"status\":1,\"ck\":13.1,\"name\":\"X\"}")) - .willReturn(aResponse().withStatus(201))); + stubFor(post(urlEqualTo("/odds/new")).withRequestBody(containing("{\"price\":5.25,\"status\":1,\"ck\":13.1,\"name\":\"X\"}")) + .willReturn(aResponse().withStatus(201))); } @Test public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() { - get("/odds").then().body("odds.findAll { it.status > 0 }.price", - hasItems(5.25f, 1.2f)); + get("/odds").then() + .body("odds.findAll { it.status > 0 }.price", hasItems(5.25f, 1.2f)); } @Test public void whenRequestedPost_thenCreated() { with().body(new Odd(5.25f, 1, 13.1f, "X")) - .when() - .request("POST", "/odds/new") - .then() - .statusCode(201); + .when() + .request("POST", "/odds/new") + .then() + .statusCode(201); } private static String getJson() { - return Util.inputStreamToString(RestAssured2IntegrationTest.class - .getResourceAsStream("/odds.json")); + return Util.inputStreamToString(RestAssured2IntegrationTest.class.getResourceAsStream("/odds.json")); } @AfterClass - public static void after() throws Exception { + public static void after() { System.out.println("Running: tearDown"); wireMockServer.stop(); } diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java index e4279897e2..3c3e1cc39f 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java @@ -1,17 +1,7 @@ package com.baeldung.restassured; -import com.github.fge.jsonschema.SchemaVersion; -import com.github.fge.jsonschema.cfg.ValidationConfiguration; -import com.github.fge.jsonschema.main.JsonSchemaFactory; -import com.github.tomakehurst.wiremock.WireMockServer; -import io.restassured.RestAssured; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; -import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static io.restassured.RestAssured.get; @@ -20,6 +10,17 @@ import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.github.fge.jsonschema.SchemaVersion; +import com.github.fge.jsonschema.cfg.ValidationConfiguration; +import com.github.fge.jsonschema.main.JsonSchemaFactory; +import com.github.tomakehurst.wiremock.WireMockServer; + +import io.restassured.RestAssured; + public class RestAssuredIntegrationTest { private static WireMockServer wireMockServer; @@ -28,79 +29,79 @@ public class RestAssuredIntegrationTest { private static final String GAME_ODDS = getEventJson(); @BeforeClass - public static void before() throws Exception { + public static void before() { System.out.println("Setting up!"); final int port = Util.getAvailablePort(); wireMockServer = new WireMockServer(port); wireMockServer.start(); RestAssured.port = port; configureFor("localhost", port); - stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( - aResponse().withStatus(200) + stubFor(com.github.tomakehurst.wiremock.client.WireMock.get(urlEqualTo(EVENTS_PATH)) + .willReturn(aResponse().withStatus(200) .withHeader("Content-Type", APPLICATION_JSON) .withBody(GAME_ODDS))); } @Test public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() { - get("/events?id=390").then().assertThat() + get("/events?id=390").then() + .assertThat() .body("odd.ck", equalTo(12.2f)); } @Test public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() { - get("/events?id=390").then().statusCode(200).assertThat() + get("/events?id=390").then() + .statusCode(200) + .assertThat() .body("id", equalTo("390")); } @Test public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() { - get("/events?id=390").then().assertThat() + get("/events?id=390").then() + .assertThat() .body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20")); } @Test public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() { - get("/events?id=390").then().assertThat() + get("/events?id=390").then() + .assertThat() .body(matchesJsonSchemaInClasspath("event_0.json")); } @Test public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() { - JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory - .newBuilder() - .setValidationConfiguration( - ValidationConfiguration.newBuilder() - .setDefaultVersion(SchemaVersion.DRAFTV4) - .freeze()).freeze(); + JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.newBuilder() + .setValidationConfiguration(ValidationConfiguration.newBuilder() + .setDefaultVersion(SchemaVersion.DRAFTV4) + .freeze()) + .freeze(); - get("/events?id=390") - .then() + get("/events?id=390").then() .assertThat() - .body(matchesJsonSchemaInClasspath("event_0.json").using( - jsonSchemaFactory)); + .body(matchesJsonSchemaInClasspath("event_0.json").using(jsonSchemaFactory)); } @Test public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() { - get("/events?id=390") - .then() + get("/events?id=390").then() .assertThat() - .body(matchesJsonSchemaInClasspath("event_0.json").using( - settings().with().checkedValidation(false))); + .body(matchesJsonSchemaInClasspath("event_0.json").using(settings().with() + .checkedValidation(false))); } @AfterClass - public static void after() throws Exception { + public static void after() { System.out.println("Running: tearDown"); wireMockServer.stop(); } private static String getEventJson() { - return Util.inputStreamToString(RestAssuredIntegrationTest.class - .getResourceAsStream("/event_0.json")); + return Util.inputStreamToString(RestAssuredIntegrationTest.class.getResourceAsStream("/event_0.json")); } } diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredMultipartIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredMultipartIntegrationTest.java new file mode 100644 index 0000000000..677a205986 --- /dev/null +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredMultipartIntegrationTest.java @@ -0,0 +1,107 @@ +package com.baeldung.restassured; + +import static com.github.tomakehurst.wiremock.client.WireMock.aMultipart; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static io.restassured.RestAssured.given; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.ClassPathResource; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.matching.MultipartValuePatternBuilder; + +import io.restassured.RestAssured; +import io.restassured.builder.MultiPartSpecBuilder; +import io.restassured.specification.MultiPartSpecification; + +class RestAssuredMultipartIntegrationTest { + + private WireMockServer wireMockServer; + + @BeforeEach + void startServer() { + int port = Util.getAvailablePort(); + wireMockServer = new WireMockServer(port); + wireMockServer.start(); + configureFor("localhost", port); + RestAssured.port = port; + } + + @AfterEach + void stopServer() { + wireMockServer.stop(); + } + + @Test + void whenUploadOneFile_ThenSuccess() throws IOException { + stubFor(post(urlEqualTo("/upload")).withHeader("Content-Type", containing("multipart/form-data")) + .withRequestBody(containing("file")) + .withRequestBody(containing(getFileContent("baeldung.txt"))) + .willReturn(aResponse().withStatus(200))); + + given().multiPart("file", getFile("baeldung.txt")) + .when() + .post("/upload") + .then() + .statusCode(200); + } + + @Test + void whenUploadTwoFiles_ThenSuccess() throws IOException { + stubFor(post(urlEqualTo("/upload")).withHeader("Content-Type", containing("multipart/form-data")) + .withRequestBody(containing(getFileContent("baeldung.txt"))) + .withRequestBody(containing(getFileContent("helloworld.txt"))) + .willReturn(aResponse().withStatus(200))); + + given().multiPart("file", getFile("baeldung.txt")) + .multiPart("helloworld", getFile("helloworld.txt")) + .when() + .post("/upload") + .then() + .statusCode(200); + } + + @Test + void whenBuildingMultipartSpecification_ThenSuccess() { + MultipartValuePatternBuilder multipartValuePatternBuilder = aMultipart().withName("file") + .withHeader("Content-Disposition", containing("file.txt")) + .withBody(equalTo("File content")) + .withHeader("Content-Type", containing("text/plain")); + + stubFor(post(urlEqualTo("/upload")).withMultipartRequestBody(multipartValuePatternBuilder) + .willReturn(aResponse().withStatus(200))); + + MultiPartSpecification multiPartSpecification = new MultiPartSpecBuilder("File content".getBytes()).fileName("file.txt") + .controlName("file") + .mimeType("text/plain") + .build(); + + given().multiPart(multiPartSpecification) + .when() + .post("/upload") + .then() + .statusCode(200); + } + + private String getFileContent(String fileName) throws IOException { + return new String(Files.readAllBytes(Paths.get(getFile(fileName).getPath()))); + } + + private File getFile(String fileName) throws IOException { + return new ClassPathResource(fileName).getFile(); + } + +} diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java index f71cce603c..e99be9c716 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java @@ -1,19 +1,19 @@ package com.baeldung.restassured; -import com.github.tomakehurst.wiremock.WireMockServer; -import io.restassured.RestAssured; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static io.restassured.RestAssured.get; +import static org.hamcrest.Matchers.hasItems; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static io.restassured.RestAssured.get; -import static io.restassured.RestAssured.port; -import static org.hamcrest.Matchers.hasItems; +import com.github.tomakehurst.wiremock.WireMockServer; + +import io.restassured.RestAssured; public class RestAssuredXML2IntegrationTest { private static WireMockServer wireMockServer; @@ -23,34 +23,31 @@ public class RestAssuredXML2IntegrationTest { private static final String TEACHERS = getXml(); @BeforeClass - public static void before() throws Exception { + public static void before() { System.out.println("Setting up!"); final int port = Util.getAvailablePort(); wireMockServer = new WireMockServer(port); wireMockServer.start(); RestAssured.port = port; configureFor("localhost", port); - stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( - aResponse().withStatus(200) + stubFor(com.github.tomakehurst.wiremock.client.WireMock.get(urlEqualTo(EVENTS_PATH)) + .willReturn(aResponse().withStatus(200) .withHeader("Content-Type", APPLICATION_XML) .withBody(TEACHERS))); } @Test public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() { - get("/teachers") - .then() - .body("teachers.teacher.find { it.@department == 'science' }.subject", - hasItems("math", "physics")); + get("/teachers").then() + .body("teachers.teacher.find { it.@department == 'science' }.subject", hasItems("math", "physics")); } private static String getXml() { - return Util.inputStreamToString(RestAssuredXML2IntegrationTest.class - .getResourceAsStream("/teachers.xml")); + return Util.inputStreamToString(RestAssuredXML2IntegrationTest.class.getResourceAsStream("/teachers.xml")); } @AfterClass - public static void after() throws Exception { + public static void after() { System.out.println("Running: tearDown"); wireMockServer.stop(); } diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java index 082dace526..95dd479f43 100644 --- a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java @@ -1,14 +1,7 @@ package com.baeldung.restassured; -import com.github.tomakehurst.wiremock.WireMockServer; -import io.restassured.RestAssured; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; -import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static io.restassured.RestAssured.post; @@ -16,6 +9,14 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.xml.HasXPath.hasXPath; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.github.tomakehurst.wiremock.WireMockServer; + +import io.restassured.RestAssured; + public class RestAssuredXMLIntegrationTest { private static WireMockServer wireMockServer; @@ -24,28 +25,30 @@ public class RestAssuredXMLIntegrationTest { private static final String EMPLOYEES = getXml(); @BeforeClass - public static void before() throws Exception { + public static void before() { System.out.println("Setting up!"); final int port = Util.getAvailablePort(); wireMockServer = new WireMockServer(port); wireMockServer.start(); configureFor("localhost", port); RestAssured.port = port; - stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn( - aResponse().withStatus(200) + stubFor(com.github.tomakehurst.wiremock.client.WireMock.post(urlEqualTo(EVENTS_PATH)) + .willReturn(aResponse().withStatus(200) .withHeader("Content-Type", APPLICATION_XML) .withBody(EMPLOYEES))); } @Test public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() { - post("/employees").then().assertThat() + post("/employees").then() + .assertThat() .body("employees.employee.first-name", equalTo("Jane")); } @Test public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() { - post("/employees").then().assertThat() + post("/employees").then() + .assertThat() .body("employees.employee.first-name", equalTo("Jane")) .body("employees.employee.last-name", equalTo("Daisy")) .body("employees.employee.sex", equalTo("f")); @@ -53,38 +56,31 @@ public class RestAssuredXMLIntegrationTest { @Test public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() { - post("/employees") - .then() + post("/employees").then() .assertThat() - .body("employees.employee.first-name", equalTo("Jane"), - "employees.employee.last-name", equalTo("Daisy"), - "employees.employee.sex", equalTo("f")); + .body("employees.employee.first-name", equalTo("Jane"), "employees.employee.last-name", equalTo("Daisy"), "employees.employee.sex", equalTo("f")); } @Test public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() { - post("/employees") - .then() + post("/employees").then() .assertThat() - .body(hasXPath("/employees/employee/first-name", - containsString("Ja"))); + .body(hasXPath("/employees/employee/first-name", containsString("Ja"))); } @Test public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() { - post("/employees") - .then() + post("/employees").then() .assertThat() .body(hasXPath("/employees/employee/first-name[text()='Jane']")); } private static String getXml() { - return Util - .inputStreamToString(RestAssuredXMLIntegrationTest.class.getResourceAsStream("/employees.xml")); + return Util.inputStreamToString(RestAssuredXMLIntegrationTest.class.getResourceAsStream("/employees.xml")); } @AfterClass - public static void after() throws Exception { + public static void after() { System.out.println("Running: tearDown"); wireMockServer.stop(); } diff --git a/testing-modules/rest-assured/src/test/resources/baeldung.txt b/testing-modules/rest-assured/src/test/resources/baeldung.txt new file mode 100644 index 0000000000..e0d72ef800 --- /dev/null +++ b/testing-modules/rest-assured/src/test/resources/baeldung.txt @@ -0,0 +1 @@ +baeldung \ No newline at end of file diff --git a/testing-modules/rest-assured/src/test/resources/helloworld.txt b/testing-modules/rest-assured/src/test/resources/helloworld.txt new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/testing-modules/rest-assured/src/test/resources/helloworld.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file From d37926eddf1aaa25cbb74ac395589bf478590177 Mon Sep 17 00:00:00 2001 From: Saikat Chakraborty <40471715+saikatcse03@users.noreply.github.com> Date: Wed, 17 May 2023 00:33:45 +0530 Subject: [PATCH 25/46] Bael 4582: Custom Authentication using shared secret (#13801) * Spring custom security filter add * Integration Tests add * Add Project into parent pom * refactor code * refactor code * remove .env and refactor code * refactor code * exclude auto configuration * Refactored code * removed ssl certificate for security * Set session management to statelees * Refactor tests * Refactor authentication logic * Refactor authentication logic * Refactor authentication logic * Remove unused code * Remove unused code * Remove unused appconfig --- spring-security-modules/pom.xml | 1 + .../spring-security-web-boot-5/pom.xml | 51 ++++++++++++++ .../customauth/SpringSecurityApplication.java | 12 ++++ .../RequestHeaderAuthenticationProvider.java | 36 ++++++++++ .../configuration/SecurityConfig.java | 68 +++++++++++++++++++ .../customauth/controller/ApiController.java | 13 ++++ .../controller/HealthCheckController.java | 13 ++++ .../src/main/resources/application.properties | 5 ++ .../customauth/SpringContextTest.java | 16 +++++ .../ApiControllerIntegrationTest.java | 68 +++++++++++++++++++ .../HealthCheckControllerIntegrationTest.java | 34 ++++++++++ .../src/test/resources/application.properties | 5 ++ 12 files changed, 322 insertions(+) create mode 100644 spring-security-modules/spring-security-web-boot-5/pom.xml create mode 100644 spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/SpringSecurityApplication.java create mode 100644 spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/authprovider/RequestHeaderAuthenticationProvider.java create mode 100644 spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/configuration/SecurityConfig.java create mode 100644 spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/controller/ApiController.java create mode 100644 spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/controller/HealthCheckController.java create mode 100644 spring-security-modules/spring-security-web-boot-5/src/main/resources/application.properties create mode 100644 spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/SpringContextTest.java create mode 100644 spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/ApiControllerIntegrationTest.java create mode 100644 spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/HealthCheckControllerIntegrationTest.java create mode 100644 spring-security-modules/spring-security-web-boot-5/src/test/resources/application.properties diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 223f0894d5..030f1ef876 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -33,6 +33,7 @@ spring-security-web-boot-2 spring-security-web-boot-3 spring-security-web-boot-4 + spring-security-web-boot-5 spring-security-web-digest-auth spring-security-web-login spring-security-web-login-2 diff --git a/spring-security-modules/spring-security-web-boot-5/pom.xml b/spring-security-modules/spring-security-web-boot-5/pom.xml new file mode 100644 index 0000000000..f4e2e3ad92 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + spring-security-web-boot-5 + 0.0.1-SNAPSHOT + spring-security-web-boot-5 + jar + Spring Security Custom Auth Application + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/SpringSecurityApplication.java b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/SpringSecurityApplication.java new file mode 100644 index 0000000000..500b8fbef8 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/SpringSecurityApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.customauth; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringSecurityApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringSecurityApplication.class, args); + } +} diff --git a/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/authprovider/RequestHeaderAuthenticationProvider.java b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/authprovider/RequestHeaderAuthenticationProvider.java new file mode 100644 index 0000000000..e9741f7a7a --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/authprovider/RequestHeaderAuthenticationProvider.java @@ -0,0 +1,36 @@ +package com.baeldung.customauth.authprovider; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; + +@Service +public class RequestHeaderAuthenticationProvider implements AuthenticationProvider { + + @Value("${api.auth.secret}") + private String apiAuthSecret; + + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + String authSecretKey = String.valueOf(authentication.getPrincipal()); + + if(StringUtils.isBlank(authSecretKey) || !authSecretKey.equals(apiAuthSecret)) { + throw new BadCredentialsException("Bad Request Header Credentials"); + } + + return new PreAuthenticatedAuthenticationToken(authentication.getPrincipal(), null, new ArrayList<>()); + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(PreAuthenticatedAuthenticationToken.class); + } +} diff --git a/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/configuration/SecurityConfig.java b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/configuration/SecurityConfig.java new file mode 100644 index 0000000000..53ab890792 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/configuration/SecurityConfig.java @@ -0,0 +1,68 @@ +package com.baeldung.customauth.configuration; + +import com.baeldung.customauth.authprovider.RequestHeaderAuthenticationProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter; +import org.springframework.security.web.header.HeaderWriterFilter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; + +import javax.servlet.http.HttpServletResponse; +import java.util.Collections; + +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + private final RequestHeaderAuthenticationProvider requestHeaderAuthenticationProvider; + + @Value("${api.auth.header.name}") + private String apiAuthHeaderName; + + @Autowired + public SecurityConfig( RequestHeaderAuthenticationProvider requestHeaderAuthenticationProvider){ + this.requestHeaderAuthenticationProvider = requestHeaderAuthenticationProvider; + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.cors().and().csrf() + .disable() + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .addFilterAfter(requestHeaderAuthenticationFilter(), HeaderWriterFilter.class) + .authorizeHttpRequests() + .antMatchers(HttpMethod.GET,"/health").permitAll() + .antMatchers("/api/**").authenticated().and() + .exceptionHandling().authenticationEntryPoint((request, response, authException) -> + response.sendError(HttpServletResponse.SC_UNAUTHORIZED)); + + return http.build(); + } + + @Bean + public RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() { + RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter(); + filter.setPrincipalRequestHeader(apiAuthHeaderName); + filter.setExceptionIfHeaderMissing(false); + filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/api/**")); + filter.setAuthenticationManager(authenticationManager()); + + return filter; + } + + @Bean + protected AuthenticationManager authenticationManager() { + return new ProviderManager(Collections.singletonList(requestHeaderAuthenticationProvider)); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/controller/ApiController.java b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/controller/ApiController.java new file mode 100644 index 0000000000..89a66b6a0e --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/controller/ApiController.java @@ -0,0 +1,13 @@ +package com.baeldung.customauth.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ApiController { + + @GetMapping(path = "/api/hello") + public String hello(){ + return "hello"; + } +} diff --git a/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/controller/HealthCheckController.java b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/controller/HealthCheckController.java new file mode 100644 index 0000000000..38d96b9b3d --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/main/java/com/baeldung/customauth/controller/HealthCheckController.java @@ -0,0 +1,13 @@ +package com.baeldung.customauth.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HealthCheckController { + + @GetMapping(path = "/health") + public String getHealthStatus(){ + return "OK"; + } +} diff --git a/spring-security-modules/spring-security-web-boot-5/src/main/resources/application.properties b/spring-security-modules/spring-security-web-boot-5/src/main/resources/application.properties new file mode 100644 index 0000000000..3a431720c2 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.application.name=spring-security-app +server.servlet.context-path=/app +server.port=8085 +api.auth.header.name=x-auth-secret-key +logging.level.org.springframework.security=DEBUG \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/SpringContextTest.java b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/SpringContextTest.java new file mode 100644 index 0000000000..a63d9d2bce --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.customauth; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = SpringSecurityApplication.class) +class SpringContextTest { + + @Test + void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/ApiControllerIntegrationTest.java b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/ApiControllerIntegrationTest.java new file mode 100644 index 0000000000..f04dcc30d4 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/ApiControllerIntegrationTest.java @@ -0,0 +1,68 @@ +package com.baeldung.customauth.controller; + +import com.baeldung.customauth.SpringSecurityApplication; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.net.URI; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +@SpringBootTest(classes = SpringSecurityApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@ExtendWith(SpringExtension.class) +class ApiControllerIntegrationTest { + + private final TestRestTemplate restTemplate = new TestRestTemplate(); + + private static final String API_ENDPOINT = "http://localhost:8080/app/api/hello"; + + @Test + void givenAuthHeaderSecretIsValid_whenApiControllerCalled_thenReturnOk() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.add("x-auth-secret-key", "test-secret"); + + ResponseEntity response = restTemplate.exchange(new URI(API_ENDPOINT), HttpMethod.GET, + new HttpEntity<>(headers), String.class); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertEquals("hello", response.getBody()); + } + + @Test + void givenAAuthHeaderIsInvalid_whenApiControllerCalled_thenReturnUnAuthorised() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.add("x-auth-secret-key", "invalid"); + + ResponseEntity response = restTemplate.exchange(new URI(API_ENDPOINT), HttpMethod.GET, + new HttpEntity<>(headers), String.class); + + assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); + } + + @Test + void givenAuthHeaderNameIsInValid_whenApiControllerCalled_thenReturnUnAuthorised() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.add("x-auth-secret", "test-secret"); + + ResponseEntity response = restTemplate.exchange(new URI(API_ENDPOINT), HttpMethod.GET, + new HttpEntity<>(headers), String.class); + + assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); + } + + @Test + void givenAuthHeaderIsMissing_whenApiControllerCalled_thenReturnUnAuthorised() throws Exception { + HttpHeaders headers = new HttpHeaders(); + + ResponseEntity response = restTemplate.exchange(new URI(API_ENDPOINT), HttpMethod.GET, + new HttpEntity<>(headers), String.class); + + assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); + } +} diff --git a/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/HealthCheckControllerIntegrationTest.java b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/HealthCheckControllerIntegrationTest.java new file mode 100644 index 0000000000..ea6fdcf292 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/HealthCheckControllerIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.customauth.controller; + +import com.baeldung.customauth.SpringSecurityApplication; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.net.URI; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@SpringBootTest(classes = SpringSecurityApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@ExtendWith(SpringExtension.class) +class HealthCheckControllerIntegrationTest { + + private final TestRestTemplate restTemplate = new TestRestTemplate(); + + private static final String HEALTH_CHECK_ENDPOINT = "http://localhost:8080/app/health"; + + @Test + void givenApplicationIsRunning_whenHealthCheckControllerCalled_thenReturnOk() throws Exception { + HttpHeaders headers = new HttpHeaders(); + + ResponseEntity response = restTemplate.exchange(new URI(HEALTH_CHECK_ENDPOINT), HttpMethod.GET, + new HttpEntity<>(headers), String.class); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertEquals("OK", response.getBody()); + } +} diff --git a/spring-security-modules/spring-security-web-boot-5/src/test/resources/application.properties b/spring-security-modules/spring-security-web-boot-5/src/test/resources/application.properties new file mode 100644 index 0000000000..27e9cad28a --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-5/src/test/resources/application.properties @@ -0,0 +1,5 @@ +spring.application.name=spring-security-app +server.servlet.context-path=/app +server.port=8080 +api.auth.header.name=x-auth-secret-key +api.auth.secret=test-secret From 7f601b84d235318b4874cd6025ad90622a8b5c21 Mon Sep 17 00:00:00 2001 From: Dmytro Budym <46810751+dbudim@users.noreply.github.com> Date: Wed, 17 May 2023 00:11:14 +0200 Subject: [PATCH 26/46] disable AWSS3ObjectIntegrationTest due to need real credentials (#14028) make AWSS3ObjectIntegrationTest manual --- ...jectIntegrationTest.java => AWSS3ObjectManualTest.java} | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) rename aws-modules/aws-s3/src/test/java/com/baeldung/s3/{AWSS3ObjectIntegrationTest.java => AWSS3ObjectManualTest.java} (89%) diff --git a/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectIntegrationTest.java b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectManualTest.java similarity index 89% rename from aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectIntegrationTest.java rename to aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectManualTest.java index 7fe9081fe3..02cc22367a 100644 --- a/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectIntegrationTest.java +++ b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectManualTest.java @@ -10,7 +10,12 @@ import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; -public class AWSS3ObjectIntegrationTest { +/** + * Required defined environment variables AWS_ACCESS_KEY_ID & AWS_ACCESS_KEY to access S3. + * Required S3 bucket and key that exist. + */ + +public class AWSS3ObjectManualTest { private static final String BUCKET = "your-bucket"; private static final String KEY_THAT_EXIST = "your-key-that-exist"; From 0f7a00193b74914ad9539d3f1f01911945322361 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 20:16:47 +0800 Subject: [PATCH 27/46] Update README.md [skip ci] --- spring-boot-modules/spring-boot-3-observation/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-3-observation/README.md b/spring-boot-modules/spring-boot-3-observation/README.md index edfb23ce2b..6d8c02af67 100644 --- a/spring-boot-modules/spring-boot-3-observation/README.md +++ b/spring-boot-modules/spring-boot-3-observation/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Observability with Spring Boot 3](https://www.baeldung.com/spring-boot-3-observability) +- [Intercept SQL Logging with P6Spy](https://www.baeldung.com/java-p6spy-intercept-sql-logging) From ff2ca369267b8761d21fe477eb5f863541bcd46e Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 20:24:12 +0800 Subject: [PATCH 28/46] 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 1633dc4828..2fd945e5d9 100644 --- a/core-java-modules/core-java-io-apis-2/README.md +++ b/core-java-modules/core-java-io-apis-2/README.md @@ -8,3 +8,4 @@ This module contains articles about core Java input/output(IO) APIs. - [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path) - [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer) - [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) From 4e27f78bf0658d4b1745b9bb1af509a7f58b15a8 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 20:28:36 +0800 Subject: [PATCH 29/46] 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 2fd945e5d9..a4ea869946 100644 --- a/core-java-modules/core-java-io-apis-2/README.md +++ b/core-java-modules/core-java-io-apis-2/README.md @@ -9,3 +9,4 @@ This module contains articles about core Java input/output(IO) APIs. - [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer) - [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) From 1f9c1fdb370e17c33e3058deeebee6e372865ef7 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 20:33:02 +0800 Subject: [PATCH 30/46] Update README.md [skip ci] --- core-java-modules/core-java-string-apis-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-apis-2/README.md b/core-java-modules/core-java-string-apis-2/README.md index 5476e91169..d1ec0d8388 100644 --- a/core-java-modules/core-java-string-apis-2/README.md +++ b/core-java-modules/core-java-string-apis-2/README.md @@ -4,3 +4,4 @@ This module contains articles about string APIs. ### Relevant Articles: - [Retain Only Digits and Decimal Separator in String](https://www.baeldung.com/java-string-retain-digits-decimal) +- [Difference Between null and Empty String in Java](https://www.baeldung.com/java-string-null-vs-empty) From 9f2bee0824592d1b3d63419fd6450ec3ef9d0799 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 20:36:14 +0800 Subject: [PATCH 31/46] Update README.md [skip ci] --- core-java-modules/core-java-io-conversions-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-io-conversions-2/README.md b/core-java-modules/core-java-io-conversions-2/README.md index c83a3fb1d7..06befa5517 100644 --- a/core-java-modules/core-java-io-conversions-2/README.md +++ b/core-java-modules/core-java-io-conversions-2/README.md @@ -10,4 +10,5 @@ This module contains articles about core Java input/output(IO) conversions. - [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array) - [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv) - [How to Convert InputStream to Base64 String](https://www.baeldung.com/java-inputstream-to-base64-string) +- [Convert an OutputStream to an InputStream](https://www.baeldung.com/java-convert-outputstream-to-inputstream) - More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions) From 558f03a8d272e60d8445cea6e5f74698995b5767 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 20:42:22 +0800 Subject: [PATCH 32/46] Update README.md [skip ci] --- core-java-modules/core-java-concurrency-collections-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-collections-2/README.md b/core-java-modules/core-java-concurrency-collections-2/README.md index c812ed4284..2d65cf88e7 100644 --- a/core-java-modules/core-java-concurrency-collections-2/README.md +++ b/core-java-modules/core-java-concurrency-collections-2/README.md @@ -4,4 +4,5 @@ - [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue) - [Java Concurrent HashSet Equivalent to ConcurrentHashMap](https://www.baeldung.com/java-concurrent-hashset-concurrenthashmap) - [Reading and Writing With a ConcurrentHashMap](https://www.baeldung.com/concurrenthashmap-reading-and-writing) +- [ArrayBlockingQueue vs. LinkedBlockingQueue](https://www.baeldung.com/java-arrayblockingqueue-vs-linkedblockingqueue) - [[<-- Prev]](/core-java-modules/core-java-concurrency-collections) From 2248a3940960ec059fdea61f925e91dfa2abf0a5 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 20:54:43 +0800 Subject: [PATCH 33/46] Update README.md [skip ci] --- core-java-modules/core-java-regex-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-regex-2/README.md b/core-java-modules/core-java-regex-2/README.md index f733d7770a..ccf60f56d9 100644 --- a/core-java-modules/core-java-regex-2/README.md +++ b/core-java-modules/core-java-regex-2/README.md @@ -6,4 +6,5 @@ - [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement) - [Creating a Java Array from Regular Expression Matches](https://www.baeldung.com/java-array-regex-matches) - [Getting the Text That Follows After the Regex Match in Java](https://www.baeldung.com/java-regex-text-after-match) +- [Regular Expression: \z vs \Z Anchors in Java](https://www.baeldung.com/java-regular-expression-z-vs-z-anchors) - More articles: [[<-- prev]](/core-java-modules/core-java-regex) From 768e6b767a448c611765fc65d002659b9720fc04 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 20:58:22 +0800 Subject: [PATCH 34/46] Update README.md [skip ci] --- core-java-modules/core-java-lang-oop-patterns/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-oop-patterns/README.md b/core-java-modules/core-java-lang-oop-patterns/README.md index df68a1413a..ea3309dc0a 100644 --- a/core-java-modules/core-java-lang-oop-patterns/README.md +++ b/core-java-modules/core-java-lang-oop-patterns/README.md @@ -8,3 +8,4 @@ This module contains articles about Object-oriented programming (OOP) patterns i - [Immutable Objects in Java](https://www.baeldung.com/java-immutable-object) - [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy) - [Using an Interface vs. Abstract Class in Java](https://www.baeldung.com/java-interface-vs-abstract-class) +- [Should We Create an Interface for Only One Implementation?](https://www.baeldung.com/java-interface-single-implementation) From f96add5372ade5b2e74bb8cca8a67244a6ef0d57 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 21:08:27 +0800 Subject: [PATCH 35/46] Update README.md [skip ci] --- testing-modules/selenium-junit-testng/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/selenium-junit-testng/README.md b/testing-modules/selenium-junit-testng/README.md index e262fb326f..922f5d6a52 100644 --- a/testing-modules/selenium-junit-testng/README.md +++ b/testing-modules/selenium-junit-testng/README.md @@ -11,7 +11,7 @@ - [Implicit Wait vs Explicit Wait in Selenium Webdriver](https://www.baeldung.com/selenium-implicit-explicit-wait) - [StaleElementReferenceException in Selenium](https://www.baeldung.com/selenium-staleelementreferenceexception) - [Retrieve the Value of an HTML Input in Selenium WebDriver](https://www.baeldung.com/java-selenium-html-input-value) - +- [Opening a New Tab Using Selenium WebDriver in Java](https://www.baeldung.com/java-selenium-open-new-tab) #### Notes: - to run the live tests for the article *Fixing Selenium WebDriver Executable Path Error*, follow the manual setup described [Fixing Selenium WebDriver Executable Path Error](https://www.baeldung.com/java-selenium-webdriver-path-error#manual-setup); download the 3 From 73885aade0aed4794b078d0a15f0810022d44027 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Wed, 17 May 2023 21:12:44 +0800 Subject: [PATCH 36/46] Update README.md [skip ci] --- core-java-modules/core-java-io-conversions-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-io-conversions-2/README.md b/core-java-modules/core-java-io-conversions-2/README.md index 06befa5517..4e179a84d2 100644 --- a/core-java-modules/core-java-io-conversions-2/README.md +++ b/core-java-modules/core-java-io-conversions-2/README.md @@ -11,4 +11,5 @@ This module contains articles about core Java input/output(IO) conversions. - [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv) - [How to Convert InputStream to Base64 String](https://www.baeldung.com/java-inputstream-to-base64-string) - [Convert an OutputStream to an InputStream](https://www.baeldung.com/java-convert-outputstream-to-inputstream) +- [Java PrintStream to String](https://www.baeldung.com/java-printstream-to-string) - More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions) From deec7f1647cde65f8bff936329d84d83fabd5b81 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 17 May 2023 19:24:21 +0530 Subject: [PATCH 37/46] JAVA-20828: changes made for resolving botique module (#14027) --- pom.xml | 14 ++------------ web-modules/bootique/pom.xml | 9 +++++++++ web-modules/pom.xml | 8 ++++---- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/pom.xml b/pom.xml index 0744823446..473d3453a8 100644 --- a/pom.xml +++ b/pom.xml @@ -938,12 +938,7 @@ persistence-modules/questdb vaadin libraries-3 - web-modules/apache-tapestry - web-modules/blade - web-modules/bootique - web-modules/dropwizard - web-modules/google-web-toolkit - web-modules/jakarta-ee + web-modules @@ -1196,12 +1191,7 @@ persistence-modules/questdb vaadin libraries-3 - web-modules/apache-tapestry - web-modules/blade - web-modules/bootique - web-modules/dropwizard - web-modules/google-web-toolkit - web-modules/jakarta-ee + web-modules diff --git a/web-modules/bootique/pom.xml b/web-modules/bootique/pom.xml index d06f835889..8da24ebf0a 100644 --- a/web-modules/bootique/pom.xml +++ b/web-modules/bootique/pom.xml @@ -53,6 +53,15 @@ maven-shade-plugin ${maven-shade-plugin.version} + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + + + diff --git a/web-modules/pom.xml b/web-modules/pom.xml index 90e8297e09..14b40dd51e 100644 --- a/web-modules/pom.xml +++ b/web-modules/pom.xml @@ -20,22 +20,22 @@ dropwizard google-web-toolkit jakarta-ee - java-lite + - ratpack + From 31bc69c282270bc101c530ddfb39a748079d120a Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Wed, 17 May 2023 16:55:48 +0300 Subject: [PATCH 38/46] [JAVA-20626]Moved vertx-modules to jdk9-and-above profile + upgraded vertx version to 3.9.15 (#13960) --- pom.xml | 4 ++-- vertx-modules/spring-vertx/pom.xml | 2 +- vertx-modules/vertx-and-rxjava/pom.xml | 7 +------ vertx-modules/vertx/pom.xml | 2 +- 4 files changed, 5 insertions(+), 10 deletions(-) diff --git a/pom.xml b/pom.xml index 473d3453a8..cde2965040 100644 --- a/pom.xml +++ b/pom.xml @@ -434,7 +434,6 @@ spring-websockets static-analysis testing-modules - vertx-modules video-tutorials xml xml-2 @@ -611,7 +610,6 @@ spring-websockets static-analysis testing-modules - vertx-modules video-tutorials xml xml-2 @@ -929,6 +927,7 @@ spring-threads spring-vault tensorflow-java + vertx-modules xstream webrtc persistence-modules/java-mongodb @@ -1182,6 +1181,7 @@ spring-threads spring-vault tensorflow-java + vertx-modules xstream webrtc persistence-modules/java-mongodb diff --git a/vertx-modules/spring-vertx/pom.xml b/vertx-modules/spring-vertx/pom.xml index 447d31ee55..d19420d571 100644 --- a/vertx-modules/spring-vertx/pom.xml +++ b/vertx-modules/spring-vertx/pom.xml @@ -48,7 +48,7 @@ - 3.4.1 + 3.9.15 \ No newline at end of file diff --git a/vertx-modules/vertx-and-rxjava/pom.xml b/vertx-modules/vertx-and-rxjava/pom.xml index 95bf95020a..16eaf8ebaa 100644 --- a/vertx-modules/vertx-and-rxjava/pom.xml +++ b/vertx-modules/vertx-and-rxjava/pom.xml @@ -36,17 +36,12 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - 3.5.0.Beta1 + 3.9.15 \ No newline at end of file diff --git a/vertx-modules/vertx/pom.xml b/vertx-modules/vertx/pom.xml index f8d72f8ae8..786ce44e79 100644 --- a/vertx-modules/vertx/pom.xml +++ b/vertx-modules/vertx/pom.xml @@ -65,7 +65,7 @@ - 3.8.1 + 3.9.15 3.2.1 From ee664c7822efd5b764e93b6a436817bb25e87e74 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Wed, 17 May 2023 17:00:04 +0300 Subject: [PATCH 39/46] [JAVA-20633 Clean up modules (#14024) --- pom.xml | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/pom.xml b/pom.xml index cde2965040..82e7e3e319 100644 --- a/pom.xml +++ b/pom.xml @@ -349,7 +349,6 @@ core-java-modules/core-java-collections-conversions-2 core-java-modules/core-java-streams-2 - couchbase gradle-modules/gradle/maven-to-gradle @@ -413,15 +412,9 @@ parent-java spring-4 - spring-aop spring-cloud-modules - - spring-exceptions - spring-integration - spring-jenkins-pipeline - spring-security-modules @@ -536,7 +529,6 @@ core-java-modules/core-java-collections-conversions-2 core-java-modules/core-java-streams-2 - couchbase gradle-modules/gradle/maven-to-gradle @@ -593,11 +585,6 @@ spring-cloud-modules - - spring-exceptions - spring-integration - spring-jenkins-pipeline - spring-security-modules From da265d4f810aecefb012906d432aaa153ca44610 Mon Sep 17 00:00:00 2001 From: Bhaskar Ghosh Dastidar Date: Thu, 18 May 2023 02:02:04 +0530 Subject: [PATCH 40/46] [BAEL-6339] custom iterator with testcases (#14038) Co-authored-by: Bhaskar --- .../core-java-collections-5/pom.xml | 20 ++- .../customiterators/CustomMovieIterator.java | 39 +++++ .../com/baeldung/customiterators/Movie.java | 37 +++++ .../com/baeldung/customiterators/MyList.java | 139 ++++++++++++++++++ .../customiterators/PalindromIterator.java | 44 ++++++ .../customiterators/IteratorsUnitTest.java | 53 +++++++ 6 files changed, 328 insertions(+), 4 deletions(-) create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/CustomMovieIterator.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/Movie.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/MyList.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/PalindromIterator.java create mode 100644 core-java-modules/core-java-collections-5/src/test/java/com/baeldung/customiterators/IteratorsUnitTest.java diff --git a/core-java-modules/core-java-collections-5/pom.xml b/core-java-modules/core-java-collections-5/pom.xml index 6baecc2802..84f62c696d 100644 --- a/core-java-modules/core-java-collections-5/pom.xml +++ b/core-java-modules/core-java-collections-5/pom.xml @@ -1,10 +1,22 @@ - + 4.0.0 core-java-collections-5 core-java-collections-5 + + + + org.apache.maven.plugins + maven-compiler-plugin + + 9 + 9 + + + + jar @@ -54,5 +66,5 @@ 0.9.38 1.36 - + diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/CustomMovieIterator.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/CustomMovieIterator.java new file mode 100644 index 0000000000..a1e34dd4c5 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/CustomMovieIterator.java @@ -0,0 +1,39 @@ +package com.baeldung.customiterators; + +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +public class CustomMovieIterator implements Iterator { + private int currentIndex; + private final List list; + + public CustomMovieIterator(List list) { + this.list = list; + this.currentIndex = 0; + } + + @Override + public boolean hasNext() { + while (currentIndex < list.size()) { + Movie currentMovie = list.get(currentIndex); + if (isMovieEligible(currentMovie)) { + return true; + } + currentIndex++; + } + return false; + } + + @Override + public Movie next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return list.get(currentIndex++); + } + + private boolean isMovieEligible(Movie movie) { + return movie.getRating() >= 8; + } +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/Movie.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/Movie.java new file mode 100644 index 0000000000..e1188e69bf --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/Movie.java @@ -0,0 +1,37 @@ +package com.baeldung.customiterators; + +public class Movie { + private String name; + private String director; + private float rating; + + public Movie(String name, String director, float rating) { + this.name = name; + this.director = director; + this.rating = rating; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDirector() { + return director; + } + + public void setDirector(String director) { + this.director = director; + } + + public float getRating() { + return rating; + } + + public void setRating(float rating) { + this.rating = rating; + } +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/MyList.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/MyList.java new file mode 100644 index 0000000000..a0b2f4a943 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/MyList.java @@ -0,0 +1,139 @@ +package com.baeldung.customiterators; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +/** + * Please note that this class has been added for representation purposes of how a custom collection and its iterator would be. + * This does not have working code. + */ +public class MyList implements List { + @Override + public int size() { + return 0; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public boolean contains(Object o) { + return false; + } + + @Override + public boolean add(E e) { + return false; + } + + @Override + public boolean remove(Object o) { + return false; + } + + @Override + public Iterator iterator() { + return new MyListIterator(); + } + + private class MyListIterator implements Iterator { + @Override + public boolean hasNext() { + return false; + } + + @Override + public E next() { + return null; + } + } + + @Override + public Object[] toArray() { + return new Object[0]; + } + + @Override + public T[] toArray(T[] a) { + return null; + } + + @Override + public boolean containsAll(Collection c) { + return false; + } + + @Override + public boolean addAll(Collection c) { + return false; + } + + @Override + public boolean addAll(int index, Collection c) { + return false; + } + + @Override + public boolean removeAll(Collection c) { + return false; + } + + @Override + public boolean retainAll(Collection c) { + return false; + } + + @Override + public void clear() { + + } + + @Override + public E get(int index) { + return null; + } + + @Override + public E set(int index, E element) { + return null; + } + + @Override + public void add(int index, E element) { + + } + + @Override + public E remove(int index) { + return null; + } + + @Override + public int indexOf(Object o) { + return 0; + } + + @Override + public int lastIndexOf(Object o) { + return 0; + } + + @Override + public ListIterator listIterator() { + return null; + } + + @Override + public ListIterator listIterator(int index) { + return null; + } + + @Override + public List subList(int fromIndex, int toIndex) { + return null; + } +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/PalindromIterator.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/PalindromIterator.java new file mode 100644 index 0000000000..50263f52ec --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/PalindromIterator.java @@ -0,0 +1,44 @@ +package com.baeldung.customiterators; + +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +public class PalindromIterator implements Iterator { + private final List list; + private int currentIndex; + + public PalindromIterator(List list) { + this.list = list; + this.currentIndex = 0; + } + + @Override + public boolean hasNext() { + while (currentIndex < list.size()) { + String currString = list.get(currentIndex); + if (isPalindrome(currString)) { + return true; + } + currentIndex++; + } + return false; + } + + @Override + public String next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return list.get(currentIndex++); + } + + private boolean isPalindrome(String input) { + for (int i = 0; i < input.length() / 2; i++) { + if (input.charAt(i) != input.charAt(input.length() - i - 1)) { + return false; + } + } + return true; + } +} diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/customiterators/IteratorsUnitTest.java b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/customiterators/IteratorsUnitTest.java new file mode 100644 index 0000000000..04389eb1d2 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/customiterators/IteratorsUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.customiterators; + +import static org.junit.Assert.assertEquals; + +import java.util.Iterator; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; + +public class IteratorsUnitTest { + @Test + public void givenListOfStrings_whenIteratedWithDefaultIterator() { + List listOfStrings = List.of("hello", "world", "this", "is", "a", "test"); + Iterator iterator = listOfStrings.iterator(); + Assert.assertTrue(iterator.hasNext()); + assertEquals(iterator.next(), "hello"); + } + + @Test + public void givenListOfStrings_whenPalindromIterator_thenOnlyPalindromes() { + List listOfStrings = List.of("oslo", "madam", "car", "deed", "wow", "test"); + PalindromIterator palindromIterator = new PalindromIterator(listOfStrings); + int count = 0; + while (palindromIterator.hasNext()) { + palindromIterator.next(); + count++; + } + assertEquals(count, 3); + } + + @Test + public void givenMovieList_whenMovieIteratorUsed_thenOnlyHighRatedMovies() { + List movies = getMovies(); + CustomMovieIterator movieIterator = new CustomMovieIterator(movies); + int count = 0; + while (movieIterator.hasNext()) { + movieIterator.next(); + count++; + } + assertEquals(4, movies.size()); + assertEquals(2, count); + } + + private List getMovies() { + Movie movie1 = new Movie("The Dark Knight", "Nolan", 10); + Movie movie2 = new Movie("Avatar", "Cameron", 9); + Movie movie3 = new Movie("Tenet", "Nolan", 7); + Movie movie4 = new Movie("Extraction", "Hargrave", 5); + return List.of(movie1, movie2, movie3, movie4); + } + +} From 934390aaefd0408870ca83742fa587b3de313f68 Mon Sep 17 00:00:00 2001 From: thibaultfaure Date: Thu, 18 May 2023 04:02:35 +0200 Subject: [PATCH 41/46] BAEL-6246 Fix AppControllerIntegrationTest (#14039) Co-authored-by: thibault.faure --- testing-modules/rest-assured/pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 647411e567..a4860b641d 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -160,6 +160,12 @@ ${rest-assured.version} test + + io.rest-assured + rest-assured-all + ${rest-assured.version} + test + com.github.scribejava scribejava-apis From 4fbb7815ce6c513c97ce29458443bc6f26289483 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Thu, 18 May 2023 07:44:26 +0530 Subject: [PATCH 42/46] JAVA-20946 Renamed HttpBinServiceUnitTest to LiveTest (#14041) - Since it is making actual live request to httpbin.org --- ...{HttpBinServiceUnitTest.java => HttpBinServiceLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/encoding/service/{HttpBinServiceUnitTest.java => HttpBinServiceLiveTest.java} (97%) diff --git a/spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/encoding/service/HttpBinServiceUnitTest.java b/spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/encoding/service/HttpBinServiceLiveTest.java similarity index 97% rename from spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/encoding/service/HttpBinServiceUnitTest.java rename to spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/encoding/service/HttpBinServiceLiveTest.java index c45f1991e5..47c7815a4a 100644 --- a/spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/encoding/service/HttpBinServiceUnitTest.java +++ b/spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/encoding/service/HttpBinServiceLiveTest.java @@ -8,7 +8,7 @@ import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest -class HttpBinServiceUnitTest { +class HttpBinServiceLiveTest { @Autowired private HttpBinService httpBinService; From 316e5626f21768e36124c3a7baa4d32d28911ee5 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Thu, 18 May 2023 07:51:34 +0530 Subject: [PATCH 43/46] JAVA-21186 Fix references to parents - Week 21 - 2023 (#14036) --- .../custom-validations-opeanpi-codegen/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml index 9add9ae494..9cd6f71892 100644 --- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml +++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml @@ -10,10 +10,10 @@ Demo project for Swagger Custom Validations Codegen - org.springframework.boot - spring-boot-starter-parent - 2.5.4 - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 From 1daa963235659339dfe9f0135f30cdbb30e0d0df Mon Sep 17 00:00:00 2001 From: Kasra Madadipouya Date: Thu, 18 May 2023 04:46:31 +0200 Subject: [PATCH 44/46] JAVA-20630 move the jws module to *-jdk9-and-above profiles (#14030) --- pom.xml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 82e7e3e319..3125c489a3 100644 --- a/pom.xml +++ b/pom.xml @@ -477,7 +477,6 @@ jenkins-modules jhipster-modules - jws @@ -639,7 +638,6 @@ jenkins-modules jhipster-modules - jws @@ -809,6 +807,8 @@ tablesaw geotools + jws + akka-modules @@ -1062,6 +1062,8 @@ tablesaw geotools + jws + akka-modules From ab3e892d6e4288d146cbaf3e3a2b866cf61cd6fc Mon Sep 17 00:00:00 2001 From: Kasra Madadipouya Date: Thu, 18 May 2023 04:49:44 +0200 Subject: [PATCH 45/46] JAVA-20631 move Jetbrains module to *-jdk9-and-above profiles (#14029) * JAVA-20631 move Jetbrains module to *-jdk9-and-above profiles * JAVA-20631 fix parent modules so that the project parent (pom.xml) can be built without error --- pom.xml | 3 ++- spring-reactive-modules/spring-reactor/pom.xml | 7 +++---- spring-reactive-modules/spring-webflux-amqp/pom.xml | 7 +++---- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/pom.xml b/pom.xml index 3125c489a3..8bfdd36c1d 100644 --- a/pom.xml +++ b/pom.xml @@ -355,7 +355,6 @@ - jetbrains language-interop @@ -850,6 +849,7 @@ javaxval javaxval-2 javax-validation-advanced + jetbrains jgit jib @@ -1106,6 +1106,7 @@ javaxval javaxval-2 javax-validation-advanced + jetbrains jgit jib diff --git a/spring-reactive-modules/spring-reactor/pom.xml b/spring-reactive-modules/spring-reactor/pom.xml index c64d449553..22eaa898bd 100644 --- a/spring-reactive-modules/spring-reactor/pom.xml +++ b/spring-reactive-modules/spring-reactor/pom.xml @@ -10,10 +10,9 @@ http://maven.apache.org - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 + com.baeldung.spring.reactive + spring-reactive-modules + 1.0.0-SNAPSHOT diff --git a/spring-reactive-modules/spring-webflux-amqp/pom.xml b/spring-reactive-modules/spring-webflux-amqp/pom.xml index 3ceb33dc3b..8ab8277d08 100755 --- a/spring-reactive-modules/spring-webflux-amqp/pom.xml +++ b/spring-reactive-modules/spring-webflux-amqp/pom.xml @@ -11,10 +11,9 @@ Spring WebFlux AMQP Sample - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 + com.baeldung.spring.reactive + spring-reactive-modules + 1.0.0-SNAPSHOT From a78c978c9b5476cf3df22eb54876feea00103729 Mon Sep 17 00:00:00 2001 From: Hamid Reza Sharifi Date: Thu, 18 May 2023 12:20:26 +0330 Subject: [PATCH 46/46] BAEL-5711: Securing Spring Boot API with API key and secret (#14015) * #bael-5711: add source * #bael-5711: remove extra space * #bael-5711: remove extra space * #bael-5711: remove extra space --------- Co-authored-by: h_sharifi --- .../ApiKeySecretAuthApplication.java | 14 ++++++++ .../configuration/ApiKeyAuthentication.java | 25 ++++++++++++++ .../configuration/AuthenticationFilter.java | 22 ++++++++++++ .../configuration/AuthenticationService.java | 20 +++++++++++ .../configuration/SecurityConfig.java | 34 +++++++++++++++++++ .../controller/ResourceController.java | 12 +++++++ 6 files changed, 127 insertions(+) create mode 100644 spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/ApiKeySecretAuthApplication.java create mode 100644 spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/ApiKeyAuthentication.java create mode 100644 spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationFilter.java create mode 100644 spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationService.java create mode 100644 spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/SecurityConfig.java create mode 100644 spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/controller/ResourceController.java diff --git a/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/ApiKeySecretAuthApplication.java b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/ApiKeySecretAuthApplication.java new file mode 100644 index 0000000000..6dea68f07b --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/ApiKeySecretAuthApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.apikeyauthentication; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration; + +@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class}) +public class ApiKeySecretAuthApplication { + + public static void main(String[] args) { + SpringApplication.run(ApiKeySecretAuthApplication.class, args); + } +} diff --git a/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/ApiKeyAuthentication.java b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/ApiKeyAuthentication.java new file mode 100644 index 0000000000..6f2a78bd4a --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/ApiKeyAuthentication.java @@ -0,0 +1,25 @@ +package com.baeldung.apikeyauthentication.configuration; + +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; +import java.util.Collection; + +public class ApiKeyAuthentication extends AbstractAuthenticationToken { + private final String apiKey; + + public ApiKeyAuthentication(String apiKey, Collection authorities) { + super(authorities); + this.apiKey = apiKey; + setAuthenticated(true); + } + + @Override + public Object getCredentials() { + return null; + } + + @Override + public Object getPrincipal() { + return apiKey; + } +} 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 new file mode 100644 index 0000000000..6c82f9c9ef --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationFilter.java @@ -0,0 +1,22 @@ +package com.baeldung.apikeyauthentication.configuration; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.GenericFilterBean; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +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); + 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 new file mode 100644 index 0000000000..14183f9f62 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/AuthenticationService.java @@ -0,0 +1,20 @@ +package com.baeldung.apikeyauthentication.configuration; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.AuthorityUtils; +import javax.servlet.http.HttpServletRequest; + +public class AuthenticationService { + + private static final String AUTH_TOKEN_HEADER_NAME = "X-API-KEY"; + private static final String AUTH_TOKEN = "Baeldung"; + + 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); + } + + return null; + } +} diff --git a/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/SecurityConfig.java b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/SecurityConfig.java new file mode 100644 index 0000000000..0ce58d1bf8 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/configuration/SecurityConfig.java @@ -0,0 +1,34 @@ +package com.baeldung.apikeyauthentication.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.csrf() + .disable() + .authorizeRequests() + .antMatchers("/**") + .authenticated() + .and() + .httpBasic() + .and() + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .addFilterBefore(new AuthenticationFilter(), + UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + +} diff --git a/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/controller/ResourceController.java b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/controller/ResourceController.java new file mode 100644 index 0000000000..56164a14a0 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-4/src/main/java/com/baeldung/apikeyauthentication/controller/ResourceController.java @@ -0,0 +1,12 @@ +package com.baeldung.apikeyauthentication.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ResourceController { + @GetMapping("/home") + public String homeEndpoint() { + return "Baeldung !"; + } +}