diff --git a/apache-poi-3/pom.xml b/apache-poi-3/pom.xml index 905db3d58c..e6e85d1212 100644 --- a/apache-poi-3/pom.xml +++ b/apache-poi-3/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 apache-poi-3 0.0.1-SNAPSHOT diff --git a/aws-modules/aws-s3-update-object/pom.xml b/aws-modules/aws-s3-update-object/pom.xml deleted file mode 100644 index 3cf7b657b0..0000000000 --- a/aws-modules/aws-s3-update-object/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - aws-s3-update-object - 0.0.1-SNAPSHOT - aws-s3-update-object - Project demonstrating overwriting of S3 objects - - 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-test - test - - - com.amazonaws - aws-java-sdk - ${aws-java-sdk-version} - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - 1.12.523 - - diff --git a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java deleted file mode 100644 index 24866c287b..0000000000 --- a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.awss3updateobject; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class AwsS3UpdateObjectApplication { - - public static void main(String[] args) { - SpringApplication.run(AwsS3UpdateObjectApplication.class, args); - } - -} diff --git a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java deleted file mode 100644 index e87358ef56..0000000000 --- a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.awss3updateobject.controller; - -import com.baeldung.awss3updateobject.service.FileService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -@RestController -@RequestMapping("api/v1/file") -public class FileController { - - @Autowired - FileService fileService; - - @PostMapping("/upload") - public String uploadFile(@RequestParam("file") MultipartFile multipartFile) throws Exception { - return this.fileService.uploadFile(multipartFile); - } - - @PostMapping("/update") - public String updateFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam("filePath") String exitingFilePath) throws Exception { - return this.fileService.updateFile(multipartFile, exitingFilePath); - } -} diff --git a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java deleted file mode 100644 index 23eaad7913..0000000000 --- a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.baeldung.awss3updateobject.service; - -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.AWSStaticCredentialsProvider; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Regions; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3ClientBuilder; -import com.amazonaws.services.s3.model.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import javax.annotation.PostConstruct; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -@Service -public class FileService { - - private static final Logger logger = LoggerFactory.getLogger(FileService.class); - - public AmazonS3 amazonS3; - - @Value("${aws.s3bucket}") - public String awsS3Bucket; - - @PostConstruct - private void init(){ - AWSCredentials credentials = new BasicAWSCredentials( - "AWS AccessKey", - "AWS secretKey" - ); - this.amazonS3 = AmazonS3ClientBuilder.standard() - .withRegion(Regions.fromName("us-east-1")) - .withCredentials(new AWSStaticCredentialsProvider(credentials)) - .build(); - } - - public String uploadFile(MultipartFile multipartFile) throws Exception { - String key = "/documents/" + multipartFile.getOriginalFilename(); - return this.uploadDocument(this.awsS3Bucket, key, multipartFile); - } - - public String updateFile(MultipartFile multipartFile, String key) throws Exception { - return this.uploadDocument(this.awsS3Bucket, key, multipartFile); - } - - private String uploadDocument(String s3bucket, String key, MultipartFile multipartFile) throws Exception { - try { - ObjectMetadata metadata = new ObjectMetadata(); - metadata.setContentType(multipartFile.getContentType()); - Map attributes = new HashMap<>(); - attributes.put("document-content-size", String.valueOf(multipartFile.getSize())); - metadata.setUserMetadata(attributes); - InputStream documentStream = multipartFile.getInputStream(); - PutObjectResult putObjectResult = this.amazonS3.putObject(new PutObjectRequest(s3bucket, key, documentStream, metadata)); - - S3Object s3Object = this.amazonS3.getObject(s3bucket, key); - logger.info("Last Modified: " + s3Object.getObjectMetadata().getLastModified()); - return key; - } catch (AmazonS3Exception ex) { - if (ex.getErrorCode().equalsIgnoreCase("NoSuchBucket")) { - String msg = String.format("No bucket found with name %s", s3bucket); - throw new Exception(msg); - } else if (ex.getErrorCode().equalsIgnoreCase("AccessDenied")) { - String msg = String.format("Access denied to S3 bucket %s", s3bucket); - throw new Exception(msg); - } - throw ex; - } catch (IOException ex) { - String msg = String.format("Error saving file %s to AWS S3 bucket %s", key, s3bucket); - throw new Exception(msg); - } - } -} diff --git a/aws-modules/aws-s3-update-object/src/main/resources/application.properties b/aws-modules/aws-s3-update-object/src/main/resources/application.properties deleted file mode 100644 index c840d970a8..0000000000 --- a/aws-modules/aws-s3-update-object/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -aws.s3bucket=baeldung-documents; diff --git a/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java deleted file mode 100644 index 823391c139..0000000000 --- a/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.awss3updateobject.controller; - -import com.baeldung.awss3updateobject.service.FileService; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.mock.web.MockMultipartFile; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.multipart.MultipartFile; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; - -public class FileControllerUnitTest { - - private MockMvc mockMvc; - - @Mock - private FileService fileService; - - @InjectMocks - private FileController fileController; - - @BeforeEach - public void setUp() { - MockitoAnnotations.openMocks(this); - this.mockMvc = MockMvcBuilders.standaloneSetup(fileController).build(); - } - - @Test - public void givenValidMultipartFile_whenUploadedViaEndpoint_thenCorrectPathIsReturned() throws Exception { - MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "sample file content".getBytes()); - String expectedResult = "File Uploaded Successfully"; - - when(fileService.uploadFile(multipartFile)).thenReturn(expectedResult); - - mockMvc.perform(multipart("/api/v1/file/upload").file(multipartFile)) - .andExpect(status().isOk()) - .andExpect(content().string(expectedResult)); - } - - @Test - public void givenValidMultipartFileAndExistingPath_whenUpdatedViaEndpoint_thenSamePathIsReturned() throws Exception { - MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "updated file content".getBytes()); - String filePath = "some/path/to/file"; - String expectedResult = "File Updated Successfully"; - - when(fileService.updateFile(multipartFile, filePath)).thenReturn(expectedResult); - - mockMvc.perform(multipart("/api/v1/file/update") - .file(multipartFile) - .param("filePath", filePath)) - .andExpect(status().isOk()) - .andExpect(content().string(expectedResult)); - } -} \ No newline at end of file diff --git a/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java deleted file mode 100644 index 90ed77b148..0000000000 --- a/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.baeldung.awss3updateobject.service; - -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.model.AmazonS3Exception; -import com.amazonaws.services.s3.model.PutObjectRequest; -import com.amazonaws.services.s3.model.S3Object; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; -import java.io.InputStream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -public class FileServiceUnitTest { - - @Mock - private AmazonS3 amazonS3; - - @Mock - private MultipartFile multipartFile; - - @InjectMocks - private FileService fileService; - - @BeforeEach - public void setup() { - MockitoAnnotations.openMocks(this); - fileService = new FileService(); - fileService.awsS3Bucket = "test-bucket"; - fileService.amazonS3 = amazonS3; - } - - @Test - public void givenValidFile_whenUploaded_thenKeyMatchesDocumentPath() throws Exception { - when(multipartFile.getName()).thenReturn("testFile"); - when(multipartFile.getOriginalFilename()).thenReturn("testFile"); - when(multipartFile.getContentType()).thenReturn("application/pdf"); - when(multipartFile.getSize()).thenReturn(1024L); - when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class)); - - S3Object s3Object = new S3Object(); - when(amazonS3.putObject(any())).thenReturn(null); - when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object); - - String key = fileService.uploadFile(multipartFile); - - assertEquals("/documents/testFile", key); - } - - @Test - public void givenValidFile_whenUploadFailsDueToNoBucket_thenExceptionIsThrown() throws Exception { - when(multipartFile.getName()).thenReturn("testFile"); - when(multipartFile.getOriginalFilename()).thenReturn("testFile"); - when(multipartFile.getContentType()).thenReturn("application/pdf"); - when(multipartFile.getSize()).thenReturn(1024L); - when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class)); - - AmazonS3Exception exception = new AmazonS3Exception("Test exception"); - exception.setErrorCode("NoSuchBucket"); - when(amazonS3.putObject(any(PutObjectRequest.class))).thenThrow(exception); - - assertThrows(Exception.class, () -> fileService.uploadFile(multipartFile)); - } - - @Test - public void givenExistingFile_whenUpdated_thenSameKeyIsReturned() throws Exception { - when(multipartFile.getName()).thenReturn("testFile"); - when(multipartFile.getContentType()).thenReturn("application/pdf"); - when(multipartFile.getSize()).thenReturn(1024L); - when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class)); - - S3Object s3Object = new S3Object(); - when(amazonS3.putObject(any(PutObjectRequest.class))).thenReturn(null); - when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object); - - String key = "/documents/existingFile"; - String resultKey = fileService.updateFile(multipartFile, key); - - assertEquals(key, resultKey); - } - - @Test - public void givenFileWithIOException_whenUpdated_thenExceptionIsThrown() throws Exception { - when(multipartFile.getName()).thenReturn("testFile"); - when(multipartFile.getContentType()).thenReturn("application/pdf"); - when(multipartFile.getSize()).thenReturn(1024L); - when(multipartFile.getInputStream()).thenThrow(new IOException("Test IO Exception")); - - assertThrows(Exception.class, () -> fileService.updateFile(multipartFile, "/documents/existingFile")); - } -} \ No newline at end of file diff --git a/aws-modules/aws-s3/README.md b/aws-modules/aws-s3/README.md index 9b862c8685..f3b34b584e 100644 --- a/aws-modules/aws-s3/README.md +++ b/aws-modules/aws-s3/README.md @@ -11,3 +11,4 @@ This module contains articles about Simple Storage Service (S3) on AWS - [Listing All AWS S3 Objects in a Bucket Using Java](https://www.baeldung.com/java-aws-s3-list-bucket-objects) - [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object) - [How To Rename Files and Folders in Amazon S3](https://www.baeldung.com/java-amazon-s3-rename-files-folders) +- [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object) diff --git a/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3Application.java b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3Application.java index abf570f0d0..3328006bc0 100644 --- a/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3Application.java +++ b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3Application.java @@ -45,6 +45,13 @@ public class S3Application { new File("/Users/user/Document/hello.txt") ); + s3Service.updateObject( + AWS_BUCKET, + "Document/hello2.txt", + new File("/Users/user/Document/hello2.txt") + ); + + //listing objects s3Service.listObjects(AWS_BUCKET); diff --git a/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3Service.java b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3Service.java index f4f768d1b4..dfc8e9de5f 100644 --- a/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3Service.java +++ b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3Service.java @@ -24,6 +24,7 @@ import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; +import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.model.ListBucketsResponse; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; @@ -99,7 +100,13 @@ class S3Service { .key(key) .build(); - return s3Client.putObject(request, Path.of(file.toURI()) ); + + return s3Client.putObject(request, Path.of(file.toURI())); + } + + //updating object + public PutObjectResponse updateObject(String bucketName, String key, java.io.File file) { + return this.putObject(bucketName, key, file); } //listing objects @@ -110,6 +117,7 @@ class S3Service { ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request); for(S3Object os : listObjectsV2Response.contents()) { + System.out.println(os.key()); } } diff --git a/aws-modules/aws-s3/src/test/java/com/baeldung/s3/S3ServiceIntegrationTest.java b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/S3ServiceIntegrationTest.java index bf24bcaa43..15db15831c 100644 --- a/aws-modules/aws-s3/src/test/java/com/baeldung/s3/S3ServiceIntegrationTest.java +++ b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/S3ServiceIntegrationTest.java @@ -11,6 +11,8 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import java.io.File; +import java.nio.file.Path; import java.util.Collections; import software.amazon.awssdk.services.s3.S3Client; @@ -23,6 +25,7 @@ import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.ListBucketsResponse; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; class S3ServiceIntegrationTest { @@ -38,6 +41,8 @@ class S3ServiceIntegrationTest { private final String AWS_BUCKET = "baeldung-tutorial-s3"; + private File file = new File("/Users/user/Document/hello2.txt"); + @BeforeEach public void setup() { MockitoAnnotations.openMocks(this); @@ -75,6 +80,17 @@ class S3ServiceIntegrationTest { verify(s3Client).createBucket(bucketRequest); } + @Test + void whenVerifyingUploadOfS3Object_thenCorrect() { + PutObjectRequest request = PutObjectRequest.builder() + .bucket(BUCKET_NAME) + .key(KEY_NAME) + .build(); + + s3Service.putObject(BUCKET_NAME, KEY_NAME, file); + verify(s3Client).putObject(request, Path.of(file.toURI()) ); + } + @Test void whenVerifyingListBuckets_thenCorrect() { when(s3Client.listBuckets()).thenReturn(ListBucketsResponse.builder().buckets(Collections.emptyList()).build()); diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml index 66fa4bffa1..06cea2f260 100644 --- a/aws-modules/pom.xml +++ b/aws-modules/pom.xml @@ -28,7 +28,6 @@ aws-miscellaneous aws-reactive aws-s3 - aws-s3-update-object diff --git a/core-java-modules/core-java-12/pom.xml b/core-java-modules/core-java-12/pom.xml index ba6dfc62bc..8165549d8c 100644 --- a/core-java-modules/core-java-12/pom.xml +++ b/core-java-modules/core-java-12/pom.xml @@ -8,9 +8,9 @@ jar - com.baeldung - parent-modules - 1.0.0-SNAPSHOT + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT @@ -21,30 +21,8 @@ - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source.version} - ${maven.compiler.target.version} - --enable-preview - - - - maven-surefire-plugin - - --enable-preview - - - - - - 12 - 12 + 17 \ No newline at end of file diff --git a/core-java-modules/core-java-12/src/test/java/com/baeldung/switchExpression/SwitchUnitTest.java b/core-java-modules/core-java-12/src/test/java/com/baeldung/switchExpression/SwitchUnitTest.java index 708e416090..994c6d9a73 100644 --- a/core-java-modules/core-java-12/src/test/java/com/baeldung/switchExpression/SwitchUnitTest.java +++ b/core-java-modules/core-java-12/src/test/java/com/baeldung/switchExpression/SwitchUnitTest.java @@ -19,19 +19,6 @@ public class SwitchUnitTest { Assert.assertEquals(value, 2); } - @Test - public void switchLocalVariable(){ - var month = Month.AUG; - int i = switch (month){ - case JAN,JUN, JUL -> 3; - case FEB,SEP, OCT, NOV, DEC -> 1; - case MAR,MAY, APR, AUG -> { - int j = month.toString().length() * 4; - break j; - } - }; - Assert.assertEquals(12, i); - } enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC} } diff --git a/core-java-modules/core-java-13/pom.xml b/core-java-modules/core-java-13/pom.xml index 11d6ee7007..52cf227583 100644 --- a/core-java-modules/core-java-13/pom.xml +++ b/core-java-modules/core-java-13/pom.xml @@ -8,39 +8,13 @@ jar - com.baeldung - parent-modules - 1.0.0-SNAPSHOT + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source.version} - ${maven.compiler.target.version} - 13 - --enable-preview - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.plugin.version} - - --enable-preview - - - - - - 13 - 13 - 3.0.0-M3 + 17 \ No newline at end of file diff --git a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java index be1fcfd167..3d3f319218 100644 --- a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java +++ b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java @@ -7,7 +7,6 @@ import org.junit.Test; public class SwitchExpressionsWithYieldUnitTest { @Test - @SuppressWarnings("preview") public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() { var me = 4; var operation = "squareMe"; diff --git a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java index 1f8ddcbfb4..e028e5f02c 100644 --- a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java +++ b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java @@ -8,7 +8,6 @@ public class TextBlocksUnitTest { private static final String JSON_STRING = "{\r\n" + "\"name\" : \"Baeldung\",\r\n" + "\"website\" : \"https://www.%s.com/\"\r\n" + "}"; - @SuppressWarnings("preview") private static final String TEXT_BLOCK_JSON = """ { "name" : "Baeldung", @@ -25,7 +24,6 @@ public class TextBlocksUnitTest { } - @SuppressWarnings("removal") @Test public void whenTextBlocks_thenFormattedWorksAsFormat() { assertThat(TEXT_BLOCK_JSON.formatted("baeldung") diff --git a/core-java-modules/core-java-13/src/test/java/com/baeldung/switchExpression/SwitchExpressionsUnitTest.java b/core-java-modules/core-java-13/src/test/java/com/baeldung/switchExpression/SwitchExpressionsUnitTest.java index bb9250f000..04aea79a67 100644 --- a/core-java-modules/core-java-13/src/test/java/com/baeldung/switchExpression/SwitchExpressionsUnitTest.java +++ b/core-java-modules/core-java-13/src/test/java/com/baeldung/switchExpression/SwitchExpressionsUnitTest.java @@ -13,7 +13,6 @@ import org.junit.Test; public class SwitchExpressionsUnitTest { @Test - @SuppressWarnings ("preview") public void whenSwitchingOverMonthJune_thenWillReturn3() { var month = JUNE; @@ -29,7 +28,6 @@ public class SwitchExpressionsUnitTest { } @Test - @SuppressWarnings ("preview") public void whenSwitchingOverMonthAugust_thenWillReturn24() { var month = AUGUST; @@ -47,7 +45,6 @@ public class SwitchExpressionsUnitTest { } @Test - @SuppressWarnings ("preview") public void whenSwitchingOverMonthJanuary_thenWillReturn3() { Function func = (month) -> { @@ -61,7 +58,6 @@ public class SwitchExpressionsUnitTest { } @Test - @SuppressWarnings ("preview") public void whenSwitchingOverMonthAugust_thenWillReturn2() { var month = AUGUST; diff --git a/core-java-modules/core-java-15/pom.xml b/core-java-modules/core-java-15/pom.xml index 3ac45d26ba..3996c69fa4 100644 --- a/core-java-modules/core-java-15/pom.xml +++ b/core-java-modules/core-java-15/pom.xml @@ -8,10 +8,9 @@ jar - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../pom.xml + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT @@ -27,33 +26,8 @@ - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.release} - --enable-preview - 14 - 14 - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.plugin.version} - - --enable-preview - - - - - - 15 - 3.0.0-M3 + 17 \ No newline at end of file diff --git a/core-java-modules/core-java-21/pom.xml b/core-java-modules/core-java-21/pom.xml index 7b8fa9063f..bfe1cd2c78 100644 --- a/core-java-modules/core-java-21/pom.xml +++ b/core-java-modules/core-java-21/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-21 core-java-21 @@ -12,12 +12,6 @@ 0.0.1-SNAPSHOT - - 21 - 21 - UTF-8 - - @@ -44,4 +38,10 @@ + + 21 + 21 + UTF-8 + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/pom.xml b/core-java-modules/core-java-arrays-operations-advanced-2/pom.xml index 53cccb8a73..a0ae2398a4 100644 --- a/core-java-modules/core-java-arrays-operations-advanced-2/pom.xml +++ b/core-java-modules/core-java-arrays-operations-advanced-2/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-arrays-operations-advanced-2 core-java-arrays-operations-advanced-2 diff --git a/core-java-modules/core-java-collections-array-list-2/pom.xml b/core-java-modules/core-java-collections-array-list-2/pom.xml index 042f6e5bb5..901a4f5c75 100644 --- a/core-java-modules/core-java-collections-array-list-2/pom.xml +++ b/core-java-modules/core-java-collections-array-list-2/pom.xml @@ -1,17 +1,17 @@ - 4.0.0 core-java-collections-array-list-2 core-java-collections-array-list-2 jar + com.baeldung.core-java-modules core-java-modules 0.0.1-SNAPSHOT - + @@ -24,7 +24,7 @@ - + 17 17 diff --git a/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/listoflists/ListOfListsUnitTest.java b/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/listoflists/ListOfListsUnitTest.java index 321fa475f6..f75ca453ea 100644 --- a/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/listoflists/ListOfListsUnitTest.java +++ b/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/listoflists/ListOfListsUnitTest.java @@ -71,4 +71,15 @@ public class ListOfListsUnitTest { assertThat(listOfLists.get(2)).containsExactly("Slack", "Zoom", "Microsoft Teams", "Telegram"); printListOfLists(listOfLists); } -} + + @Test + void givenListOfLists_whenGettingSizeOfSubListsAndSizeOfElements_thenGetExpectedResults() throws URISyntaxException, IOException { + List> listOfLists = getListOfListsFromCsv(); + // size of inner lists + assertThat(listOfLists).hasSize(3); + + // size of all elements in subLists + int totalElements = listOfLists.stream().mapToInt(List::size).sum(); + assertThat(totalElements).isEqualTo(12); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-6/pom.xml b/core-java-modules/core-java-collections-list-6/pom.xml index 9bea6358c4..46ef4ff4c9 100644 --- a/core-java-modules/core-java-collections-list-6/pom.xml +++ b/core-java-modules/core-java-collections-list-6/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-collections-list-6 core-java-collections-list-6 @@ -12,4 +12,5 @@ core-java-modules 0.0.1-SNAPSHOT + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-7/pom.xml b/core-java-modules/core-java-collections-maps-7/pom.xml index bb7c6e9fb5..bcc0915073 100644 --- a/core-java-modules/core-java-collections-maps-7/pom.xml +++ b/core-java-modules/core-java-collections-maps-7/pom.xml @@ -73,6 +73,11 @@ 4.13.1 test + + org.apache.commons + commons-csv + 1.5 + - \ No newline at end of file + diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/PutIfAbsentVsComputeIfAbsentUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/PutIfAbsentVsComputeIfAbsentUnitTest.java new file mode 100644 index 0000000000..304045ab9d --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/PutIfAbsentVsComputeIfAbsentUnitTest.java @@ -0,0 +1,98 @@ +package com.baeldung.map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +class Magic { + public String nullFunc() { + return null; + } + + public String strFunc(String input) { + return input + ": A nice string"; + } +} + +public class PutIfAbsentVsComputeIfAbsentUnitTest { + + private static final Map MY_MAP = new HashMap<>(); + private Magic magic = new Magic(); + + @BeforeEach + void resetTheMap() { + MY_MAP.clear(); + MY_MAP.put("Key A", "value A"); + MY_MAP.put("Key B", "value B"); + MY_MAP.put("Key C", "value C"); + MY_MAP.put("Key Null", null); + } + + @Test + void whenCallingPutIfAbsentWithAbsentKey_thenGetNull() { + String putResult = MY_MAP.putIfAbsent("new key1", magic.nullFunc()); + assertNull(putResult); + + putResult = MY_MAP.putIfAbsent("new key2", magic.strFunc("new key2")); + assertNull(putResult); + + putResult = MY_MAP.putIfAbsent("Key Null", magic.strFunc("Key Null")); + assertNull(putResult); + } + + @Test + void whenCallingComputeIfAbsentWithAbsentKey_thenGetExpectedResult() { + String computeResult = MY_MAP.computeIfAbsent("new key1", k -> magic.nullFunc()); + assertNull(computeResult); + + computeResult = MY_MAP.computeIfAbsent("new key2", k -> magic.strFunc(k)); + assertEquals("new key2: A nice string", computeResult); + + computeResult = MY_MAP.computeIfAbsent("Key Null", k -> magic.strFunc(k)); + assertEquals("Key Null: A nice string", computeResult); + } + + @Test + void whenCallingPutIfAbsentWithAbsentKey_thenNullIsPut() { + assertEquals(4, MY_MAP.size()); // initial: 4 entries + MY_MAP.putIfAbsent("new key", magic.nullFunc()); + assertEquals(5, MY_MAP.size()); + assertTrue(MY_MAP.containsKey("new key")); // new entry has been added to the map + assertNull(MY_MAP.get("new key")); + } + + @Test + void whenCallingComputeIfAbsentWithAbsentKey_thenNullIsNotPut() { + assertEquals(4, MY_MAP.size()); // initial: 4 entries + MY_MAP.computeIfAbsent("new key", k -> magic.nullFunc()); + assertEquals(4, MY_MAP.size()); + assertFalse(MY_MAP.containsKey("new key")); // <- no new entry added + } + + @Test + void whenCallingPutIfAbsent_thenFunctionIsAlwaysCalled() { + Magic spyMagic = spy(magic); + MY_MAP.putIfAbsent("Key A", spyMagic.strFunc("Key A")); + verify(spyMagic, times(1)).strFunc(anyString()); + + MY_MAP.putIfAbsent("new key", spyMagic.strFunc("new key")); + verify(spyMagic, times(2)).strFunc(anyString()); + } + + @Test + void whenCallingComputeIfAbsent_thenFunctionIsCalledOnDemand() { + Magic spyMagic = spy(magic); + MY_MAP.computeIfAbsent("Key A", k -> spyMagic.strFunc(k)); + verify(spyMagic, never()).strFunc(anyString()); + + MY_MAP.computeIfAbsent("new key", k -> spyMagic.strFunc(k)); + verify(spyMagic, times(1)).strFunc(anyString()); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/writehashmaptocsvfile/WriteHashmaptoCVSFileUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/writehashmaptocsvfile/WriteHashmaptoCVSFileUnitTest.java new file mode 100644 index 0000000000..e23a5da8ff --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/writehashmaptocsvfile/WriteHashmaptoCVSFileUnitTest.java @@ -0,0 +1,66 @@ +package com.baeldung.writehashmaptocsvfile; + +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; + +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class WriteHashmaptoCVSFileUnitTest { + public Map employeeData; + + public WriteHashmaptoCVSFileUnitTest() { + employeeData = new HashMap<>(); + employeeData.put("Name", "John Doe"); + employeeData.put("Title", "Software Engineer"); + employeeData.put("Department", "Engineering"); + employeeData.put("Salary", "75000"); + } + + @Test + public void givenEmployeeData_whenWriteToCSVUsingFileWriter_thenCSVFileIsCreated() { + + try (FileWriter csvWriter = new FileWriter("employee_data.csv")) { + // Write header row + csvWriter.append("Name,Title,Department,Salary\n"); + + // Write data row + csvWriter.append(employeeData.get("Name")).append(","); + csvWriter.append(employeeData.get("Title")).append(","); + csvWriter.append(employeeData.get("Department")).append(","); + csvWriter.append(employeeData.get("Salary")).append("\n"); + } catch (IOException e) { + e.printStackTrace(); + } + // Ensure the CSV file exists + assertTrue(new File("employee_data.csv").exists(), "CSV file does not exist!"); + + } + + @Test + public void givenCSVFile_whenWriteToCSVUsingApacheCommons_thenContentsMatchExpected() { + + try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter("employee_data2.csv"), CSVFormat.DEFAULT)) { + // Write header row + csvPrinter.printRecord("Name", "Title", "Department", "Salary"); + + // Write data row + csvPrinter.printRecord(employeeData.get("Name"), employeeData.get("Title"), employeeData.get("Department"), employeeData.get("Salary")); + } catch (IOException e) { + e.printStackTrace(); + } + + // Ensure the CSV file exists + assertTrue(new File("employee_data2.csv").exists()); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-5/pom.xml b/core-java-modules/core-java-concurrency-advanced-5/pom.xml new file mode 100644 index 0000000000..b84d3810bb --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/pom.xml @@ -0,0 +1,36 @@ + + + + 4.0.0 + core-java-concurrency-advanced-5 + core-java-concurrency-advanced-5 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + core-java-concurrency-advanced-5 + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 1.8 + 1.8 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java new file mode 100644 index 0000000000..dca36fe7cb --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java @@ -0,0 +1,24 @@ +package com.baeldung.wait_synchronization; + +public class ConditionChecker { + + private volatile Boolean jobIsDone; + private final Object lock = new Object(); + + public void ensureCondition() { + synchronized (lock) { + while (!jobIsDone) { + try { + lock.wait(); + } catch (InterruptedException e) { } + } + } + } + + public void complete() { + synchronized (lock) { + jobIsDone = true; + lock.notify(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/wait_synchronization/ConditionCheckerUnitTest.java b/core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/wait_synchronization/ConditionCheckerUnitTest.java new file mode 100644 index 0000000000..2698640e6a --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/wait_synchronization/ConditionCheckerUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.wait_synchronization; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; + +class ConditionCheckerUnitTest { + + @Test + public void givenBothMethodsAreSynchronized_whenBothMethodsAreCalled_thenNoExceptionsOrDeadlocks() { + ConditionChecker conditionChecker = new ConditionChecker(); + + ExecutorService executorService = Executors.newFixedThreadPool(2); + + Assertions.assertThatCode(() -> { + executorService.submit(conditionChecker::ensureCondition); + executorService.submit(conditionChecker::complete); + }).doesNotThrowAnyException(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-string/pom.xml b/core-java-modules/core-java-datetime-string/pom.xml index 3efb2fe728..a33114852c 100644 --- a/core-java-modules/core-java-datetime-string/pom.xml +++ b/core-java-modules/core-java-datetime-string/pom.xml @@ -65,7 +65,7 @@ 1.6 - 2.10.10 + 2.12.5 RELEASE 1.9 1.9 diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/throwvsthrows/Main.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/throwvsthrows/Main.java index dfe8fcbd5a..b693bb1219 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/throwvsthrows/Main.java +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/throwvsthrows/Main.java @@ -20,8 +20,9 @@ public class Main { System.out.println("General exception"); } - checkedException(); + checkedExceptionWithTryCatch(); checkedExceptionWithThrows(); + divideByZero(); } private static void checkedExceptionWithThrows() throws FileNotFoundException { @@ -29,7 +30,7 @@ public class Main { FileInputStream stream = new FileInputStream(file); } - private static void checkedException() { + private static void checkedExceptionWithTryCatch() { File file = new File("not_existing_file.txt"); try { FileInputStream stream = new FileInputStream(file); @@ -37,5 +38,11 @@ public class Main { e.printStackTrace(); } } + + private static void divideByZero() { + int numerator = 1; + int denominator = 0; + int result = numerator / denominator; + } } diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/throwvsthrows/NullOrEmptyException.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/throwvsthrows/NullOrEmptyException.java new file mode 100644 index 0000000000..419fb438f2 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/throwvsthrows/NullOrEmptyException.java @@ -0,0 +1,8 @@ +package com.baeldung.exceptions.throwvsthrows; + +public class NullOrEmptyException extends RuntimeException { + + public NullOrEmptyException(String errorMessage) { + super(errorMessage); + } +} diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/sizebenchmark/FileSizeBenchmark.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/sizebenchmark/FileSizeBenchmark.java new file mode 100644 index 0000000000..5998b0be73 --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/sizebenchmark/FileSizeBenchmark.java @@ -0,0 +1,67 @@ +package com.baeldung.sizebenchmark; + +import org.apache.commons.io.FileUtils; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.channels.FileChannel; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Warmup(iterations = 3, time = 10, timeUnit = TimeUnit.NANOSECONDS) +@Measurement(iterations = 3, time = 10, timeUnit = TimeUnit.NANOSECONDS) +public class FileSizeBenchmark { + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + + @Benchmark + public void getFileSizeUsingLengthMethod(Blackhole blackhole) throws Exception { + File file = new File("src/test/resources/size/sample_file_1.in"); + blackhole.consume(file.length()); + } + + @Benchmark + public void getFileSizeUsingFileInputStream(Blackhole blackhole) throws Exception { + try (FileInputStream fis = new FileInputStream("src/test/resources/size/sample_file_1.in")) { + long result = fis.getChannel().size(); + blackhole.consume(result); + } + + } + + @Benchmark + public void getFileSizeUsingInputStreamAndUrl(Blackhole blackhole) throws Exception { + File me = new File("src/test/resources/size/sample_file_1.in"); + URL url = me.toURI().toURL(); + + try (InputStream stream = url.openStream()) { + blackhole.consume(stream.available()); + } + } + + @Benchmark + public void getFileSizeUsingApacheCommon(Blackhole blackhole) { + File imageFile = new File("src/test/resources/size/sample_file_1.in"); + long size = FileUtils.sizeOf(imageFile); + blackhole.consume(size); + } + + @Benchmark + public void getFileSizeUsingFileChannel(Blackhole blackhole) throws IOException { + Path imageFilePath = Paths.get("src/test/resources/size/sample_file_1.in"); + try (FileChannel imageFileChannel = FileChannel.open(imageFilePath)) { + long imageFileSize = imageFileChannel.size(); + blackhole.consume(imageFileSize); + } + } +} diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/size/JavaFileSizeUnitTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/size/JavaFileSizeUnitTest.java index 6b6197c7ce..d015f2602e 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/size/JavaFileSizeUnitTest.java +++ b/core-java-modules/core-java-io/src/test/java/com/baeldung/size/JavaFileSizeUnitTest.java @@ -3,7 +3,10 @@ package com.baeldung.size; import static org.junit.Assert.assertEquals; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStream; +import java.net.URL; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; @@ -62,4 +65,24 @@ public class JavaFileSizeUnitTest { final long length = file.length(); return length; } + + @Test + public void whenGetFileSizeUsingFileInputStream_thenCorrect() throws IOException { + + try (FileInputStream fis = new FileInputStream(filePath)) { + long result = fis.getChannel().size(); + assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, result); + } + } + + @Test + public void whenGetFileSizeUsingUrlAndInputStream_thenCorrect() throws IOException { + + File file = new File(filePath); + URL url = file.toURI().toURL(); + + try (InputStream stream = url.openStream()) { + assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, stream.available()); + } + } } \ No newline at end of file diff --git a/core-java-modules/core-java-lang-math-3/README.md b/core-java-modules/core-java-lang-math-3/README.md index ef9c2ee4c4..37027970b6 100644 --- a/core-java-modules/core-java-lang-math-3/README.md +++ b/core-java-modules/core-java-lang-math-3/README.md @@ -12,4 +12,5 @@ - [Java Program to Print Pascal’s Triangle](https://www.baeldung.com/java-pascal-triangle) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) - [Clamp Function in Java](https://www.baeldung.com/java-clamp-function) +- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square) - More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2) diff --git a/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/MagicSquare.java b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/MagicSquare.java index b6e7ac24f5..f2ddd65ff7 100644 --- a/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/MagicSquare.java +++ b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/MagicSquare.java @@ -1,7 +1,5 @@ package com.baeldung.magicsquare; -import org.junit.platform.commons.util.StringUtils; - import java.util.stream.IntStream; public class MagicSquare { diff --git a/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/README.md b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/README.md deleted file mode 100644 index b2f7ece88a..0000000000 --- a/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/README.md +++ /dev/null @@ -1,2 +0,0 @@ -## Relevant Articles -- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square) diff --git a/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java b/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java index ca04263689..5c93d955a7 100644 --- a/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java +++ b/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java @@ -15,6 +15,7 @@ import java.util.Map; import org.apache.http.client.utils.URIBuilder; import org.apache.http.message.BasicNameValuePair; +import org.junit.Assert; import org.junit.Test; import org.springframework.web.util.UriComponentsBuilder; @@ -23,95 +24,101 @@ import com.google.common.collect.ImmutableMap; public class UrlUnitTest { @Test - public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException { - final URL url = new URL("http://baeldung.com"); + public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException, URISyntaxException { + final URL url = new URI("http://baeldung.com").toURL(); assertEquals("http", url.getProtocol()); } @Test - public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException { - final URL url = new URL("http://baeldung.com"); + public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException, URISyntaxException { + final URL url = new URI("http://baeldung.com").toURL(); assertEquals("baeldung.com", url.getHost()); } @Test - public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException { - final URL url = new URL("http://baeldung.com/articles?topic=java&version=8"); + public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException, URISyntaxException { + final URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL(); assertEquals("/articles?topic=java&version=8", url.getFile()); } @Test - public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException { - final URL url = new URL("http://baeldung.com/guidelines.txt"); + public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException, URISyntaxException { + final URL url = new URI("http://baeldung.com/guidelines.txt").toURL(); assertEquals("/guidelines.txt", url.getFile()); } @Test - public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException { - final URL url = new URL("http://baeldung.com/articles?topic=java&version=8"); + public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException, URISyntaxException { + final URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL(); assertEquals("/articles", url.getPath()); } @Test - public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException { - final URL url = new URL("http://baeldung.com/articles?topic=java"); - assertEquals("topic=java", url.getQuery()); + public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException, URISyntaxException { + final URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL(); + assertEquals("topic=java&version=8", url.getQuery()); } @Test - public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException { - final URL url = new URL("http://baeldung.com"); + public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException, URISyntaxException { + final URL url = new URI("http://baeldung.com").toURL(); assertEquals(-1, url.getPort()); assertEquals(80, url.getDefaultPort()); } @Test - public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException { - final URL url = new URL("http://baeldung.com:8090"); + public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException, URISyntaxException { + final URL url = new URI("http://baeldung.com:8090").toURL(); assertEquals(8090, url.getPort()); assertEquals(80, url.getDefaultPort()); } @Test - public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException { - final URL baseUrl = new URL("http://baeldung.com"); - final URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets"); - assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString()); + public void givenHomeUrlAndFullUrl_whenRelativize_thenCorrect() throws MalformedURLException, URISyntaxException { + final URI homeUri = new URI("http://baeldung.com"); + final URI fullUri = new URI("http://baeldung.com" + "/a-guide-to-java-sockets"); + final URI relativeUri = homeUri.relativize(fullUri); + assertEquals("a-guide-to-java-sockets", relativeUri.toString()); } @Test - public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException { - final URL baseUrl = new URL("http://baeldung.com"); - final URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets"); - assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString()); - } - - @Test - public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException { + public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException, URISyntaxException { final String protocol = "http"; final String host = "baeldung.com"; final String file = "/guidelines.txt"; - final URL url = new URL(protocol, host, file); - assertEquals("http://baeldung.com/guidelines.txt", url.toString()); + final String fragment = "myImage"; + final URL url = new URI(protocol, host, file, fragment).toURL(); + assertEquals("http://baeldung.com/guidelines.txt#myImage", url.toString()); } @Test - public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException { + public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException, URISyntaxException { final String protocol = "http"; + final String username = "admin"; final String host = "baeldung.com"; - final String file = "/articles?topic=java&version=8"; - final URL url = new URL(protocol, host, file); - assertEquals("http://baeldung.com/articles?topic=java&version=8", url.toString()); + final String file = "/articles"; + final String query = "topic=java&version=8"; + final String fragment = "myImage"; + final URL url = new URI(protocol, username, host, -1, file, query, fragment).toURL(); + assertEquals("http://admin@baeldung.com/articles?topic=java&version=8#myImage", url.toString()); } @Test - public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException { + public void givenRelativeUrl_whenCreatesRelativeUrl_thenThrows() throws URISyntaxException, MalformedURLException { + final URI uri = new URI("/a-guide-to-java-sockets"); + Assert.assertThrows(IllegalArgumentException.class, () -> uri.toURL()); + } + + @Test + public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException, URISyntaxException { final String protocol = "http"; + final String username = "admin"; final String host = "baeldung.com"; final int port = 9000; final String file = "/guidelines.txt"; - final URL url = new URL(protocol, host, port, file); - assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString()); + final String fragment = "myImage"; + final URL url = new URI(protocol, username, host, port, file, null, fragment).toURL(); + assertEquals("http://admin@baeldung.com:9000/guidelines.txt#myImage", url.toString()); } @Test @@ -120,7 +127,8 @@ public class UrlUnitTest { uriBuilder.setPort(9090); uriBuilder.addParameter("topic", "java"); uriBuilder.addParameter("version", "8"); - URL url = uriBuilder.build().toURL(); + URL url = uriBuilder.build() + .toURL(); assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString()); } @@ -130,26 +138,27 @@ public class UrlUnitTest { URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles"); uriBuilder.setPort(9090); uriBuilder.addParameters(paramMap.entrySet() - .stream() - .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())) - .collect(toList())); + .stream() + .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())) + .collect(toList())); - URL url = uriBuilder.build().toURL(); + URL url = uriBuilder.build() + .toURL(); assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString()); } @Test public void givenUrlParameters_whenBuildUrlWithSpringUriComponentsBuilder_thenSuccess() throws MalformedURLException { URL url = UriComponentsBuilder.newInstance() - .scheme("http") - .host("baeldung.com") - .port(9090) - .path("articles") - .queryParam("topic", "java") - .queryParam("version", "8") - .build() - .toUri() - .toURL(); + .scheme("http") + .host("baeldung.com") + .port(9090) + .path("articles") + .queryParam("topic", "java") + .queryParam("version", "8") + .build() + .toUri() + .toURL(); assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString()); } diff --git a/core-java-modules/core-java-security-4/pom.xml b/core-java-modules/core-java-security-4/pom.xml index aae33f87d4..2b9809b749 100644 --- a/core-java-modules/core-java-security-4/pom.xml +++ b/core-java-modules/core-java-security-4/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-security-4 core-java-security-4 diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingCollector.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingCollector.java index 8f36550bdc..c6530f4940 100644 --- a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingCollector.java +++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingCollector.java @@ -6,19 +6,23 @@ import java.util.function.BinaryOperator; import java.util.stream.Collector; class SkippingCollector { + private static final BinaryOperator IGNORE_COMBINE = (a, b) -> a; private final int skip; private final List list = new ArrayList<>(); private int currentIndex = 0; + private SkippingCollector(int skip) { this.skip = skip; } private void accept(String item) { final int index = ++currentIndex % skip; - if (index == 0) + if (index == 0) { list.add(item); + } } + private List getResult() { return list; } diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingElements.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingElements.java deleted file mode 100644 index eb382367cc..0000000000 --- a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingElements.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.skippingelements; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -public class SkippingElements { - - private SkippingElements() { - } - - public static List skipNthElementInListWithFilter(List sourceList, int n) { -return IntStream.range(0, sourceList.size()) - .filter(s -> (s + 1) % n == 0) - .mapToObj(sourceList::get) - .collect(Collectors.toList()); - } - - public static List skipNthElementInListWithIterate(List sourceList, int n) { -int limit = sourceList.size() / n; -return IntStream.iterate(n - 1, i -> (i + n)) - .limit(limit) - .mapToObj(sourceList::get) - .collect(Collectors.toList()); - } - - public static List skipNthElementInListWithSublist(List sourceList, int n) { -int limit = sourceList.size() / n; -return Stream.iterate(sourceList, s -> s.subList(n, s.size())) - .limit(limit) - .map(s -> s.get(n - 1)) - .collect(Collectors.toList()); - } - - public static List skipNthElementInListWithFor(List sourceList, int n) { -List result = new ArrayList<>(); -for (int i = n - 1; i < sourceList.size(); i += n) { - result.add(sourceList.get(i)); -} -return result; - } - - public static List skipNthElementInListWithIterator(Stream sourceStream, int n) { -List result = new ArrayList<>(); -final Iterator iterator = sourceStream.iterator(); -int count = 0; -while (iterator.hasNext()) { - if (count % n == n - 1) { - result.add(iterator.next()); - } else { - iterator.next(); - } - ++count; -} -return result; - } - -public static List skipNthElementInStreamWithCollector(Stream sourceStream, int n) { - return sourceStream.collect(SkippingCollector.collector(n)); -} - -} diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/skippingelements/SkippingElementsUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/skippingelements/SkippingElementsUnitTest.java index 2fd6adb0cf..92a13e62ab 100644 --- a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/skippingelements/SkippingElementsUnitTest.java +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/skippingelements/SkippingElementsUnitTest.java @@ -3,7 +3,11 @@ package com.baeldung.skippingelements; import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.ArrayList; +import java.util.Iterator; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -14,21 +18,22 @@ class SkippingElementsUnitTest { private static Stream testSource() { return Stream.of( Arguments.of( - List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", + Stream.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two", "Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty", "Thirty One", "Thirty Two", "Thirty Three"), - List.of("Three", "Six", "Nine", "Twelve", "Fifteen", "Eighteen", "Twenty One", "Twenty Four", "Twenty Seven", "Thirty", "Thirty Three"), + List.of("Three", "Six", "Nine", "Twelve", "Fifteen", "Eighteen", "Twenty One", "Twenty Four", "Twenty Seven", "Thirty", + "Thirty Three"), 3), Arguments.of( - List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", + Stream.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two", "Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty", "Thirty One", "Thirty Two", "Thirty Three"), List.of("Five", "Ten", "Fifteen", "Twenty", "Twenty Five", "Thirty"), 5), Arguments.of( - List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", + Stream.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two", "Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty", "Thirty One", "Thirty Two", "Thirty Three"), @@ -38,29 +43,29 @@ class SkippingElementsUnitTest { "Thirty One", "Thirty Two", "Thirty Three"), 1), Arguments.of( - List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), + Stream.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), List.of("Wednesday", "Saturday"), 3), Arguments.of( - List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), + Stream.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), List.of("Friday"), 5), Arguments.of( - List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), + Stream.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), 1), Arguments.of( - List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", + Stream.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"), List.of("March", "June", "September", "December"), 3), Arguments.of( - List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", + Stream.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"), List.of("May", "October"), 5), Arguments.of( - List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", + Stream.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"), List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"), @@ -70,45 +75,73 @@ class SkippingElementsUnitTest { @ParameterizedTest @MethodSource("testSource") - void givenListSkipNthElementInListWithFilterTestShouldFilterNthElement(List input, List expected, int n) { - final List actual = SkippingElements.skipNthElementInListWithFilter(input, n); + void givenListSkipNthElementInListWithFilterTestShouldFilterNthElement(Stream input, List expected, int n) { + final List sourceList = input.collect(Collectors.toList()); + final List actual = IntStream.range(0, sourceList.size()) + .filter(s -> (s + 1) % n == 0) + .mapToObj(sourceList::get) + .collect(Collectors.toList()); assertEquals(expected, actual); } @ParameterizedTest @MethodSource("testSource") - void givenListSkipNthElementInListWithIterateTestShouldFilterNthElement(List input, List expected, int n) { - final List actual = SkippingElements.skipNthElementInListWithIterate(input, n); + void givenListSkipNthElementInListWithIterateTestShouldFilterNthElement(Stream input, List expected, int n) { + final List sourceList = input.collect(Collectors.toList()); + int limit = sourceList.size() / n; + final List actual = IntStream.iterate(n - 1, i -> (i + n)) + .limit(limit) + .mapToObj(sourceList::get) + .collect(Collectors.toList()); assertEquals(expected, actual); } @ParameterizedTest @MethodSource("testSource") - void givenListSkipNthElementInListWithSublistTestShouldFilterNthElement(List input, List expected, int n) { - final List actual = SkippingElements.skipNthElementInListWithSublist(input, n); + void givenListSkipNthElementInListWithSublistTestShouldFilterNthElement(Stream input, List expected, int n) { + final List sourceList = input.collect(Collectors.toList()); + int limit = sourceList.size() / n; + final List actual = Stream.iterate(sourceList, s -> s.subList(n, s.size())) + .limit(limit) + .map(s -> s.get(n - 1)) + .collect(Collectors.toList()); assertEquals(expected, actual); } @ParameterizedTest @MethodSource("testSource") - void givenListSkipNthElementInListWithForTestShouldFilterNthElement(List input, List expected, int n) { - final List actual = SkippingElements.skipNthElementInListWithFor(input, n); + void givenListSkipNthElementInListWithForTestShouldFilterNthElement(Stream input, List expected, int n) { + final List sourceList = input.collect(Collectors.toList()); + List result = new ArrayList<>(); + for (int i = n - 1; i < sourceList.size(); i += n) { + result.add(sourceList.get(i)); + } + final List actual = result; assertEquals(expected, actual); } @ParameterizedTest @MethodSource("testSource") - void givenListSkipNthElementInStreamWithIteratorTestShouldFilterNthElement(List input, List expected, int n) { - final Stream inputStream = input.stream(); - final List actual = SkippingElements.skipNthElementInListWithIterator(inputStream, n); + void givenListSkipNthElementInStreamWithIteratorTestShouldFilterNthElement(Stream input, List expected, int n) { + List result = new ArrayList<>(); + final Iterator iterator = input.iterator(); + int count = 0; + while (iterator.hasNext()) { + if (count % n == n - 1) { + result.add(iterator.next()); + } else { + iterator.next(); + } + ++count; + } + final List actual = result; assertEquals(expected, actual); } @ParameterizedTest @MethodSource("testSource") - void givenListSkipNthElementInStreamWithCollectorShouldFilterNthElement(List input, List expected, int n) { - final Stream inputStream = input.stream(); - final List actual = SkippingElements.skipNthElementInStreamWithCollector(inputStream, n); + void givenListSkipNthElementInStreamWithCollectorShouldFilterNthElement(Stream input, List expected, int n) { + final List actual = input.collect(SkippingCollector.collector(n)); assertEquals(expected, actual); } } \ No newline at end of file diff --git a/core-java-modules/core-java-streams-simple/README.md b/core-java-modules/core-java-streams-simple/README.md index 94d74f4c49..4cbe32ce32 100644 --- a/core-java-modules/core-java-streams-simple/README.md +++ b/core-java-modules/core-java-streams-simple/README.md @@ -2,6 +2,10 @@ This module contains articles about Streams that are part of the Java Streams Ebook. +### NOTE: + +Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article. + ### Relevant Articles - [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction) @@ -11,4 +15,4 @@ This module contains articles about Streams that are part of the Java Streams Eb - [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap) - [When to Use a Parallel Stream in Java](https://www.baeldung.com/java-when-to-use-parallel-stream) - [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector) -- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) \ No newline at end of file +- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 536175acc2..507e830e8a 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -28,6 +28,11 @@ emoji-java ${emoji-java.version} + + org.apache.commons + commons-text + ${apache-commons-text.version} + @@ -58,6 +63,7 @@ 1.7 3.12.0 5.1.1 + 1.10.0 \ No newline at end of file diff --git a/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/wrappingcharacterwise/Wrapper.java b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/wrappingcharacterwise/Wrapper.java new file mode 100644 index 0000000000..7400745b2f --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/wrappingcharacterwise/Wrapper.java @@ -0,0 +1,28 @@ +package com.baeldung.wrappingcharacterwise; + +import java.lang.IllegalArgumentException; +import java.lang.String; +import java.lang.StringBuilder; + +public class Wrapper { + + public String wrapStringCharacterWise(String input, int n) { + StringBuilder stringBuilder = new StringBuilder(input); + int index = 0; + while(stringBuilder.length() > index + n) { + int lastLineReturn = stringBuilder.lastIndexOf("\n", index + n); + if (lastLineReturn > index) { + index = lastLineReturn; + } else { + index = stringBuilder.lastIndexOf(" ", index + n); + if (index == -1) { + throw new IllegalArgumentException("impossible to slice " + stringBuilder.substring(0, n)); + } + stringBuilder.replace(index, index + 1, "\n"); + index++; + } + } + return stringBuilder.toString(); + } + +} diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/wrappingcharacterwise/WrapperUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/wrappingcharacterwise/WrapperUnitTest.java new file mode 100644 index 0000000000..8dcc323f7b --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/wrappingcharacterwise/WrapperUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.wrappingcharacterwise; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.apache.commons.text.WordUtils; +import org.junit.jupiter.api.Test; + +public class WrapperUnitTest { + + Wrapper wrapper = new Wrapper(); + String lineSeparator = System.lineSeparator(); + + @Test + void givenStringWithLessThanNCharacters_whenWrapStringCharacterWise_thenUnchanged() { + String input = "short sentence"; + assertEquals(input, wrapper.wrapStringCharacterWise(input, 20)); + } + + @Test + void givenStringWithMoreThanNCharacters_whenWrapStringCharacterWise_thenCorrectlyWrapped() { + String input = "Baeldung is a popular website that provides in-depth tutorials and articles on various programming and software development topics, primarily focused on Java and related technologies."; + assertEquals("Baeldung is a\npopular website that\nprovides in-depth\ntutorials and\narticles on various\nprogramming and\nsoftware development\ntopics, primarily\nfocused on Java and\nrelated\ntechnologies.", wrapper.wrapStringCharacterWise(input, 20)); + } + + @Test + void givenStringWithATooLongWord_whenWrapStringCharacterWise_thenThrows() { + String input = "The word straightforward has more than 10 characters"; + assertThrows(IllegalArgumentException.class, () -> wrapper.wrapStringCharacterWise(input, 10)); + } + + @Test + void givenStringWithLineReturns_whenWrapStringCharacterWise_thenWrappedAccordingly() { + String input = "Baeldung\nis a popular website that provides in-depth tutorials and articles on various programming and software development topics, primarily focused on Java and related technologies."; + assertEquals("Baeldung\nis a popular\nwebsite that\nprovides in-depth\ntutorials and\narticles on various\nprogramming and\nsoftware development\ntopics, primarily\nfocused on Java and\nrelated\ntechnologies.", wrapper.wrapStringCharacterWise(input, 20)); + } + + @Test + void givenStringWithLessThanNCharacters_whenWrap_thenUnchanged() { + String input = "short sentence"; + assertEquals(input, WordUtils.wrap(input, 20)); + } + + @Test + void givenStringWithMoreThanNCharacters_whenWrap_thenCorrectlyWrapped() { + String input = "Baeldung is a popular website that provides in-depth tutorials and articles on various programming and software development topics, primarily focused on Java and related technologies."; + assertEquals("Baeldung is a" + lineSeparator + "popular website that" + lineSeparator + "provides in-depth" + lineSeparator + "tutorials and" + lineSeparator + "articles on various" + lineSeparator + "programming and" + lineSeparator + "software development" + lineSeparator + "topics, primarily" + lineSeparator + "focused on Java and" + lineSeparator + "related" + lineSeparator + "technologies.", WordUtils.wrap(input, 20)); + } + + @Test + void givenStringWithATooLongWord_whenWrap_thenLongWordIsNotWrapped() { + String input = "The word straightforward has more than 10 characters"; + assertEquals("The word" + lineSeparator + "straightforward" + lineSeparator + "has more" + lineSeparator + "than 10" + lineSeparator + "characters", WordUtils.wrap(input, 10)); + } + + @Test + void givenStringWithLineReturns_whenWrap_thenWrappedLikeThereWasNone() { + String input = "Baeldung" + lineSeparator + "is a popular website that provides in-depth tutorials and articles on various programming and software development topics, primarily focused on Java and related technologies."; + assertEquals("Baeldung" + lineSeparator + "is a" + lineSeparator + "popular website that" + lineSeparator + "provides in-depth" + lineSeparator + "tutorials and" + lineSeparator + "articles on various" + lineSeparator + "programming and" + lineSeparator + "software development" + lineSeparator + "topics, primarily" + lineSeparator + "focused on Java and" + lineSeparator + "related" + lineSeparator + "technologies.", WordUtils.wrap(input, 20)); + } + +} diff --git a/core-java-modules/core-java-string-conversions-3/pom.xml b/core-java-modules/core-java-string-conversions-3/pom.xml index ddd5f7a497..b494a03fa7 100644 --- a/core-java-modules/core-java-string-conversions-3/pom.xml +++ b/core-java-modules/core-java-string-conversions-3/pom.xml @@ -23,4 +23,12 @@ - \ No newline at end of file + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + diff --git a/core-java-modules/core-java-string-conversions-3/src/main/java/com/baeldung/objecttostring/Person.java b/core-java-modules/core-java-string-conversions-3/src/main/java/com/baeldung/objecttostring/Person.java new file mode 100644 index 0000000000..61c0bd5711 --- /dev/null +++ b/core-java-modules/core-java-string-conversions-3/src/main/java/com/baeldung/objecttostring/Person.java @@ -0,0 +1,34 @@ +package com.baeldung.objecttostring; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class Person { + private String name; + private int age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "Person{name='" + name + "', age=" + age + '}'; + } + + public String toCustomString() { + return new ToStringBuilder(this, ToStringStyle.JSON_STYLE) + .append("name", name) + .append("age", age) + .toString(); + } +} diff --git a/core-java-modules/core-java-string-conversions-3/src/test/java/com/baeldung/objecttostring/PersonUnitTest.java b/core-java-modules/core-java-string-conversions-3/src/test/java/com/baeldung/objecttostring/PersonUnitTest.java new file mode 100644 index 0000000000..7b61956dfc --- /dev/null +++ b/core-java-modules/core-java-string-conversions-3/src/test/java/com/baeldung/objecttostring/PersonUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.objecttostring; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class PersonUnitTest { + @Test + public void givenObject_whenToString_thenConvert() { + Person person = new Person("Sarah", 28); + String expected = "Person{name='Sarah', age=28}"; + String actual = person.toString(); + assertEquals(expected, actual); + } + + @Test + public void givenObject_whenValueOf_thenConvert() { + Person person = new Person("Sarah", 28); + String expected = "Person{name='Sarah', age=28}"; + String actual = String.valueOf(person); + assertEquals(expected, actual); + } + + @Test + public void givenObject_whenConcat_thenConvert() { + Person person = new Person("Sarah", 28); + String expected = "Person{name='Sarah', age=28}"; + String actual = "" + person; + assertEquals(expected, actual); + } + + @Test + public void givenObject_whenToStringBuilder_thenConvert() { + Person person = new Person("Sarah", 28); + String expected = "{\"name\":\"Sarah\",\"age\":28}"; + String actual = person.toCustomString(); + assertEquals(expected, actual); + } +} diff --git a/core-java-modules/core-java-string-operations-7/README.md b/core-java-modules/core-java-string-operations-7/README.md new file mode 100644 index 0000000000..2dce44d217 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/README.md @@ -0,0 +1,2 @@ + +### Relevant Articles: diff --git a/core-java-modules/core-java-string-operations-7/pom.xml b/core-java-modules/core-java-string-operations-7/pom.xml new file mode 100644 index 0000000000..595f918fcd --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + core-java-string-operations-7 + core-java-string-operations-7 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.apache.commons + commons-lang3 + ${apache.commons.lang3.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + org.liquibase + liquibase-core + 4.9.1 + test + + + org.junit.jupiter + junit-jupiter + 5.8.1 + test + + + org.liquibase + liquibase-core + 4.9.1 + test + + + junit + junit + 4.13.2 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 11 + 11 + 3.12.0 + 1.10.0 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java new file mode 100644 index 0000000000..a3f95b0181 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.centertext; + +import liquibase.repackaged.org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; + +public class CenteringTextUnitTest { + + @Test + public void givenTextAndTotalWidth_whenUsingStringFormat_thenTextIsCentered() { + String text = "Centered Text"; + int totalWidth = 15; + int padding = (totalWidth - text.length()) / 2; + String centeredText = String.format("%" + padding + "s%s%" + padding + "s", "", text, ""); + Assert.assertEquals(" Centered Text ", centeredText); + } + + @Test + public void givenTextAndTotalWidth_whenCenterUsingStringBuilder_thenTextIsCentered() { + String text = "Centered Text"; + int width = 15; + int padding = (width - text.length()) / 2; + StringBuilder centeredText = new StringBuilder(); + for (int i = 0; i < padding; i++) { + centeredText.append(" "); + } + centeredText.append(text); + for (int i = 0; i < padding; i++) { + centeredText.append(" "); + } + String centeredTextString = centeredText.toString(); + Assert.assertEquals(" Centered Text ", centeredTextString); + } + + @Test + public void givenTextAndTotalWidth_whenUsingStringUtilsCenterMethod_thenTextIsCentered() { + String text = "Centered Text"; + int width = 15; + String centeredText = StringUtils.center(text, width); + assertEquals(" Centered Text ", centeredText); + } + +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 5b37db6e1a..2152b90bcb 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -27,6 +27,11 @@ + + + + + core-java-9-improvements core-java-9-streams core-java-9 @@ -34,6 +39,9 @@ core-java-11 core-java-11-2 core-java-11-3 + core-java-12 + core-java-13 + core-java-15 core-java-collections-array-list core-java-collections-array-list-2 core-java-collections-list-4 @@ -178,12 +186,18 @@ core-java-string-operations core-java-string-operations-2 core-java-string-operations-6 + core-java-string-operations-7 core-java-regex core-java-regex-2 core-java-uuid core-java-collections-maps-6 core-java-records core-java-9-jigsaw + + core-java-collections-set + core-java-date-operations-1 + + core-java-httpclient diff --git a/json-modules/json-2/pom.xml b/json-modules/json-2/pom.xml index 7253088516..6cca576fb1 100644 --- a/json-modules/json-2/pom.xml +++ b/json-modules/json-2/pom.xml @@ -237,7 +237,6 @@ 0.9.23 1.9.2 1.2.21 - 20211205 1.1.1 0.1.1 0.4.2 diff --git a/json-modules/json-arrays/pom.xml b/json-modules/json-arrays/pom.xml index 0eefbc86fc..10c487fbda 100644 --- a/json-modules/json-arrays/pom.xml +++ b/json-modules/json-arrays/pom.xml @@ -38,7 +38,6 @@ 1.0 - 20230227 2.8.5 1.1.2 2.28.0 diff --git a/json-modules/json-conversion/pom.xml b/json-modules/json-conversion/pom.xml index 680f27fa38..638216f4c5 100644 --- a/json-modules/json-conversion/pom.xml +++ b/json-modules/json-conversion/pom.xml @@ -37,7 +37,6 @@ - 20211205 2.10.1 32.1.2-jre diff --git a/json-modules/json/pom.xml b/json-modules/json/pom.xml index 8210f026e7..27c9262279 100644 --- a/json-modules/json/pom.xml +++ b/json-modules/json/pom.xml @@ -68,7 +68,6 @@ 1.0.72 1.0 1.0.1 - 20230227 2.8.5 1.1.2 2.28.0 diff --git a/json-modules/pom.xml b/json-modules/pom.xml index 306b404049..7ac6ba19ad 100644 --- a/json-modules/pom.xml +++ b/json-modules/pom.xml @@ -34,4 +34,8 @@ + + 20230618 + + \ No newline at end of file diff --git a/lightrun/api-service/.gitignore b/lightrun/lightrun-api-service/.gitignore similarity index 100% rename from lightrun/api-service/.gitignore rename to lightrun/lightrun-api-service/.gitignore diff --git a/lightrun/api-service/pom.xml b/lightrun/lightrun-api-service/pom.xml similarity index 94% rename from lightrun/api-service/pom.xml rename to lightrun/lightrun-api-service/pom.xml index f44ad07edb..b7ed5f951b 100644 --- a/lightrun/api-service/pom.xml +++ b/lightrun/lightrun-api-service/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - api-service + lightrun-api-service 0.0.1-SNAPSHOT - api-service + lightrun-api-service Aggregator Service for LightRun Article diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/ApiServiceApplication.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/ApiServiceApplication.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/ApiServiceApplication.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/ApiServiceApplication.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/RequestIdGenerator.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/RequestIdGenerator.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/RequestIdGenerator.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/RequestIdGenerator.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/RestTemplateConfig.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/RestTemplateConfig.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/RestTemplateConfig.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/RestTemplateConfig.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/WebConfig.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/WebConfig.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/WebConfig.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/WebConfig.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/http/TaskResponse.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/http/TaskResponse.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/http/TaskResponse.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/http/TaskResponse.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/http/TasksController.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/http/TasksController.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/http/TasksController.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/http/TasksController.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/http/UnknownTaskException.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/http/UnknownTaskException.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/http/UnknownTaskException.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/http/UnknownTaskException.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/http/UserResponse.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/http/UserResponse.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/http/UserResponse.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/http/UserResponse.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/tasks/Task.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/tasks/Task.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/tasks/Task.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/tasks/Task.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/tasks/TaskRepository.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/tasks/TaskRepository.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/tasks/TaskRepository.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/tasks/TaskRepository.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/users/User.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/users/User.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/users/User.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/users/User.java diff --git a/lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/users/UserRepository.java b/lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/users/UserRepository.java similarity index 100% rename from lightrun/api-service/src/main/java/com/baeldung/apiservice/adapters/users/UserRepository.java rename to lightrun/lightrun-api-service/src/main/java/com/baeldung/apiservice/adapters/users/UserRepository.java diff --git a/lightrun/api-service/src/main/resources/application.properties b/lightrun/lightrun-api-service/src/main/resources/application.properties similarity index 100% rename from lightrun/api-service/src/main/resources/application.properties rename to lightrun/lightrun-api-service/src/main/resources/application.properties diff --git a/lightrun/tasks-service/.gitignore b/lightrun/lightrun-tasks-service/.gitignore similarity index 100% rename from lightrun/tasks-service/.gitignore rename to lightrun/lightrun-tasks-service/.gitignore diff --git a/lightrun/tasks-service/pom.xml b/lightrun/lightrun-tasks-service/pom.xml similarity index 96% rename from lightrun/tasks-service/pom.xml rename to lightrun/lightrun-tasks-service/pom.xml index c3542b0089..2689a9794d 100644 --- a/lightrun/tasks-service/pom.xml +++ b/lightrun/lightrun-tasks-service/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - tasks-service + lightrun-tasks-service 0.0.1-SNAPSHOT - tasks-service + lightrun-tasks-service Tasks Service for LightRun Article diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/ArtemisConfig.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/ArtemisConfig.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/ArtemisConfig.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/ArtemisConfig.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/SimpleCacheCustomizer.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/SimpleCacheCustomizer.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/SimpleCacheCustomizer.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/SimpleCacheCustomizer.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/TasksServiceApplication.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/TasksServiceApplication.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/TasksServiceApplication.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/TasksServiceApplication.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/CreateTaskRequest.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/CreateTaskRequest.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/CreateTaskRequest.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/CreateTaskRequest.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/PatchTaskRequest.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/PatchTaskRequest.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/PatchTaskRequest.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/PatchTaskRequest.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/TaskResponse.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/TaskResponse.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/TaskResponse.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/TaskResponse.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/TasksController.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/TasksController.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/TasksController.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/TasksController.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/http-client.env.json b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/http-client.env.json similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/http-client.env.json rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/http-client.env.json diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/tasks.http b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/tasks.http similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/tasks.http rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/http/tasks.http diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/jms/JmsConsumer.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/jms/JmsConsumer.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/jms/JmsConsumer.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/jms/JmsConsumer.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/repository/TaskRecord.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/repository/TaskRecord.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/repository/TaskRecord.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/repository/TaskRecord.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/repository/TasksRepository.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/repository/TasksRepository.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/adapters/repository/TasksRepository.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/adapters/repository/TasksRepository.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/service/DeletedUserService.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/service/DeletedUserService.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/service/DeletedUserService.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/service/DeletedUserService.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/service/TasksService.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/service/TasksService.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/service/TasksService.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/service/TasksService.java diff --git a/lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/service/UnknownTaskException.java b/lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/service/UnknownTaskException.java similarity index 100% rename from lightrun/tasks-service/src/main/java/com/baeldung/tasksservice/service/UnknownTaskException.java rename to lightrun/lightrun-tasks-service/src/main/java/com/baeldung/tasksservice/service/UnknownTaskException.java diff --git a/lightrun/tasks-service/src/main/resources/application.properties b/lightrun/lightrun-tasks-service/src/main/resources/application.properties similarity index 100% rename from lightrun/tasks-service/src/main/resources/application.properties rename to lightrun/lightrun-tasks-service/src/main/resources/application.properties diff --git a/lightrun/tasks-service/src/main/resources/db/migration/V1_0_0__create-tasks-table.sql b/lightrun/lightrun-tasks-service/src/main/resources/db/migration/V1_0_0__create-tasks-table.sql similarity index 100% rename from lightrun/tasks-service/src/main/resources/db/migration/V1_0_0__create-tasks-table.sql rename to lightrun/lightrun-tasks-service/src/main/resources/db/migration/V1_0_0__create-tasks-table.sql diff --git a/lightrun/users-service/.gitignore b/lightrun/lightrun-users-service/.gitignore similarity index 100% rename from lightrun/users-service/.gitignore rename to lightrun/lightrun-users-service/.gitignore diff --git a/lightrun/users-service/README.md b/lightrun/lightrun-users-service/README.md similarity index 100% rename from lightrun/users-service/README.md rename to lightrun/lightrun-users-service/README.md diff --git a/lightrun/users-service/pom.xml b/lightrun/lightrun-users-service/pom.xml similarity index 95% rename from lightrun/users-service/pom.xml rename to lightrun/lightrun-users-service/pom.xml index 9560dcf23b..40594db725 100644 --- a/lightrun/users-service/pom.xml +++ b/lightrun/lightrun-users-service/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - users-service + lightrun-users-service 0.0.1-SNAPSHOT - users-service + lightrun-users-service Users Service for LightRun Article diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/JmsConfig.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/JmsConfig.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/JmsConfig.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/JmsConfig.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/UsersServiceApplication.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/UsersServiceApplication.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/UsersServiceApplication.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/UsersServiceApplication.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/CreateUserRequest.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/CreateUserRequest.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/CreateUserRequest.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/CreateUserRequest.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/PatchUserRequest.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/PatchUserRequest.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/PatchUserRequest.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/PatchUserRequest.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/UserResponse.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/UserResponse.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/UserResponse.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/UserResponse.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/UsersController.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/UsersController.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/UsersController.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/UsersController.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/http-client.env.json b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/http-client.env.json similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/http-client.env.json rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/http-client.env.json diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/users.http b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/users.http similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/http/users.http rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/http/users.http diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/jms/JmsSender.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/jms/JmsSender.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/jms/JmsSender.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/jms/JmsSender.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/repository/UserRecord.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/repository/UserRecord.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/repository/UserRecord.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/repository/UserRecord.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/repository/UsersRepository.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/repository/UsersRepository.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/adapters/repository/UsersRepository.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/adapters/repository/UsersRepository.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/service/UnknownUserException.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/service/UnknownUserException.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/service/UnknownUserException.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/service/UnknownUserException.java diff --git a/lightrun/users-service/src/main/java/com/baeldung/usersservice/service/UsersService.java b/lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/service/UsersService.java similarity index 100% rename from lightrun/users-service/src/main/java/com/baeldung/usersservice/service/UsersService.java rename to lightrun/lightrun-users-service/src/main/java/com/baeldung/usersservice/service/UsersService.java diff --git a/lightrun/users-service/src/main/resources/application.properties b/lightrun/lightrun-users-service/src/main/resources/application.properties similarity index 100% rename from lightrun/users-service/src/main/resources/application.properties rename to lightrun/lightrun-users-service/src/main/resources/application.properties diff --git a/lightrun/users-service/src/main/resources/db/migration/V1_0_0__create-users-table.sql b/lightrun/lightrun-users-service/src/main/resources/db/migration/V1_0_0__create-users-table.sql similarity index 100% rename from lightrun/users-service/src/main/resources/db/migration/V1_0_0__create-users-table.sql rename to lightrun/lightrun-users-service/src/main/resources/db/migration/V1_0_0__create-users-table.sql diff --git a/lightrun/pom.xml b/lightrun/pom.xml index 3fcec48cbd..78534922f6 100644 --- a/lightrun/pom.xml +++ b/lightrun/pom.xml @@ -18,9 +18,9 @@ - tasks-service - users-service - api-service + lightrun-tasks-service + lightrun-users-service + lightrun-api-service \ No newline at end of file diff --git a/lombok-modules/lombok/src/test/java/com/baeldung/lombok/builder/defaultvalue/BuilderWithDefaultValueUnitTest.java b/lombok-modules/lombok/src/test/java/com/baeldung/lombok/builder/defaultvalue/BuilderWithDefaultValueUnitTest.java index d9184f605c..a03b262828 100644 --- a/lombok-modules/lombok/src/test/java/com/baeldung/lombok/builder/defaultvalue/BuilderWithDefaultValueUnitTest.java +++ b/lombok-modules/lombok/src/test/java/com/baeldung/lombok/builder/defaultvalue/BuilderWithDefaultValueUnitTest.java @@ -14,7 +14,7 @@ public class BuilderWithDefaultValueUnitTest { } @Test - public void givenBuilderWithDefaultValue_NoArgsWorksAlso() { + public void givenBuilderWithDefaultValue_ThanNoArgsWorksAlso() { Pojo build = new Pojo().toBuilder() .build(); Pojo pojo = new Pojo(); diff --git a/maven-modules/jacoco-coverage-aggregation/aggregate-report/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml similarity index 95% rename from maven-modules/jacoco-coverage-aggregation/aggregate-report/pom.xml rename to maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml index 1a076cacae..627a9f3206 100644 --- a/maven-modules/jacoco-coverage-aggregation/aggregate-report/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.jacoco-coverage-aggregation - aggregate-report - aggregate-report + jacoco-coverage-aggregate-report + jacoco-coverage-aggregate-report pom diff --git a/maven-modules/jacoco-coverage-aggregation/controllers/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml similarity index 94% rename from maven-modules/jacoco-coverage-aggregation/controllers/pom.xml rename to maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml index 5aa54f042f..886e931224 100644 --- a/maven-modules/jacoco-coverage-aggregation/controllers/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.jacoco-coverage-aggregation - controllers - controllers + jacoco-coverage-controllers-example + jacoco-coverage-controllers-example jar diff --git a/maven-modules/jacoco-coverage-aggregation/controllers/src/main/java/com/baeldung/coverageaggregation/MyApplication.java b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/src/main/java/com/baeldung/coverageaggregation/MyApplication.java similarity index 100% rename from maven-modules/jacoco-coverage-aggregation/controllers/src/main/java/com/baeldung/coverageaggregation/MyApplication.java rename to maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/src/main/java/com/baeldung/coverageaggregation/MyApplication.java diff --git a/maven-modules/jacoco-coverage-aggregation/controllers/src/main/java/com/baeldung/coverageaggregation/MyController.java b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/src/main/java/com/baeldung/coverageaggregation/MyController.java similarity index 100% rename from maven-modules/jacoco-coverage-aggregation/controllers/src/main/java/com/baeldung/coverageaggregation/MyController.java rename to maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/src/main/java/com/baeldung/coverageaggregation/MyController.java diff --git a/maven-modules/jacoco-coverage-aggregation/controllers/src/test/java/com/baeldung/coverageaggregation/MyControllerIntegrationTest.java b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/src/test/java/com/baeldung/coverageaggregation/MyControllerIntegrationTest.java similarity index 100% rename from maven-modules/jacoco-coverage-aggregation/controllers/src/test/java/com/baeldung/coverageaggregation/MyControllerIntegrationTest.java rename to maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/src/test/java/com/baeldung/coverageaggregation/MyControllerIntegrationTest.java diff --git a/maven-modules/jacoco-coverage-aggregation/services/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml similarity index 93% rename from maven-modules/jacoco-coverage-aggregation/services/pom.xml rename to maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml index 50c8c87f54..2c06694b46 100644 --- a/maven-modules/jacoco-coverage-aggregation/services/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.jacoco-coverage-aggregation - services - services + jacoco-coverage-services-example + jacoco-coverage-services-example jar diff --git a/maven-modules/jacoco-coverage-aggregation/services/src/main/java/com/baeldung/coverageaggregation/MyService.java b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/src/main/java/com/baeldung/coverageaggregation/MyService.java similarity index 100% rename from maven-modules/jacoco-coverage-aggregation/services/src/main/java/com/baeldung/coverageaggregation/MyService.java rename to maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/src/main/java/com/baeldung/coverageaggregation/MyService.java diff --git a/maven-modules/jacoco-coverage-aggregation/services/src/test/java/com/baeldung/coverageaggregation/MyServiceUnitTest.java b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/src/test/java/com/baeldung/coverageaggregation/MyServiceUnitTest.java similarity index 100% rename from maven-modules/jacoco-coverage-aggregation/services/src/test/java/com/baeldung/coverageaggregation/MyServiceUnitTest.java rename to maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/src/test/java/com/baeldung/coverageaggregation/MyServiceUnitTest.java diff --git a/maven-modules/jacoco-coverage-aggregation/pom.xml b/maven-modules/jacoco-coverage-aggregation/pom.xml index d85f41968d..70243973e8 100644 --- a/maven-modules/jacoco-coverage-aggregation/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/pom.xml @@ -17,9 +17,9 @@ - services - controllers - aggregate-report + jacoco-coverage-services-example + jacoco-coverage-controllers-example + jacoco-coverage-aggregate-report diff --git a/maven-modules/maven-parent-pom-resolution/aggregator/module1/pom.xml b/maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/parent-pom-module1/pom.xml similarity index 83% rename from maven-modules/maven-parent-pom-resolution/aggregator/module1/pom.xml rename to maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/parent-pom-module1/pom.xml index 67e60fb386..94164b472c 100644 --- a/maven-modules/maven-parent-pom-resolution/aggregator/module1/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/parent-pom-module1/pom.xml @@ -3,12 +3,12 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - module1 + parent-pom-module1 pom com.baeldung.maven-parent-pom-resolution - aggregator + maven-parent-pom-aggregator 1.0.0-SNAPSHOT diff --git a/maven-modules/maven-parent-pom-resolution/aggregator/module2/module3/pom.xml b/maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/parent-pom-module2/parent-pom-module3/pom.xml similarity index 86% rename from maven-modules/maven-parent-pom-resolution/aggregator/module2/module3/pom.xml rename to maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/parent-pom-module2/parent-pom-module3/pom.xml index f4e3e81e7d..533157d621 100644 --- a/maven-modules/maven-parent-pom-resolution/aggregator/module2/module3/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/parent-pom-module2/parent-pom-module3/pom.xml @@ -3,12 +3,12 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - module3 + parent-pom-module3 pom com.baeldung.maven-parent-pom-resolution - aggregator + maven-parent-pom-aggregator 1.0.0-SNAPSHOT diff --git a/maven-modules/maven-parent-pom-resolution/aggregator/module2/pom.xml b/maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/parent-pom-module2/pom.xml similarity index 72% rename from maven-modules/maven-parent-pom-resolution/aggregator/module2/pom.xml rename to maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/parent-pom-module2/pom.xml index 9b36ef37fb..9cb4407125 100644 --- a/maven-modules/maven-parent-pom-resolution/aggregator/module2/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/parent-pom-module2/pom.xml @@ -3,19 +3,19 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - module2 + parent-pom-module2 pom com.baeldung.maven-parent-pom-resolution - module1 + parent-pom-module1 1.0.0-SNAPSHOT - ../module1/pom.xml + ../parent-pom-module1/pom.xml - module3 + parent-pom-module3 \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/aggregator/pom.xml b/maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/pom.xml similarity index 78% rename from maven-modules/maven-parent-pom-resolution/aggregator/pom.xml rename to maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/pom.xml index dde2c46370..8e3a922e76 100644 --- a/maven-modules/maven-parent-pom-resolution/aggregator/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/maven-parent-pom-aggregator/pom.xml @@ -4,19 +4,18 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.maven-parent-pom-resolution - aggregator + maven-parent-pom-aggregator pom com.baeldung maven-parent-pom-resolution 1.0.0-SNAPSHOT - - module1 - module2 + parent-pom-module1 + parent-pom-module2 \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/pom.xml b/maven-modules/maven-parent-pom-resolution/pom.xml index 288bf5f780..fa3ca3dc9a 100644 --- a/maven-modules/maven-parent-pom-resolution/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/pom.xml @@ -9,7 +9,7 @@ pom - aggregator + maven-parent-pom-aggregator disable-plugin-examples diff --git a/parent-spring-6/pom.xml b/parent-spring-6/pom.xml index 7b28afc9b1..7aaffb5483 100644 --- a/parent-spring-6/pom.xml +++ b/parent-spring-6/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 parent-spring-6 0.0.1-SNAPSHOT diff --git a/patterns-modules/design-patterns-creational-2/pom.xml b/patterns-modules/design-patterns-creational-2/pom.xml index fe79052a99..27c83c9eb7 100644 --- a/patterns-modules/design-patterns-creational-2/pom.xml +++ b/patterns-modules/design-patterns-creational-2/pom.xml @@ -12,4 +12,13 @@ 1.0.0-SNAPSHOT + + + org.mockito + mockito-inline + ${mockito.version} + test + + + \ No newline at end of file diff --git a/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/singleton/Logger.java b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/singleton/Logger.java new file mode 100644 index 0000000000..31729c29f4 --- /dev/null +++ b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/singleton/Logger.java @@ -0,0 +1,38 @@ +package com.baeldung.singleton; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.time.LocalDateTime; + +public class Logger { + private static volatile Logger instance; + + private PrintWriter fileWriter; + + public static Logger getInstance() { + if (instance == null) { + synchronized (Logger.class) { + if (instance == null) { + instance = new Logger(); + } + } + } + return instance; + } + + private Logger() { + try { + fileWriter = new PrintWriter(new FileWriter("app.log")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void log(String message) { + String log = String.format("[%s]- %s", LocalDateTime.now(), message); + fileWriter.println(log); + fileWriter.flush(); + } + +} \ No newline at end of file diff --git a/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/singleton/SingletonDemo.java b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/singleton/SingletonDemo.java new file mode 100644 index 0000000000..2ebd6c8ad4 --- /dev/null +++ b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/singleton/SingletonDemo.java @@ -0,0 +1,12 @@ +package com.baeldung.singleton; + +public class SingletonDemo { + + public int sum(int a, int b) { + int result = a + b; + Logger logger = Logger.getInstance(); + logger.log("The sum is " + result); + return result; + } + +} \ No newline at end of file diff --git a/patterns-modules/design-patterns-creational-2/src/test/java/com/baeldung/singleton/SingletonUnitTest.java b/patterns-modules/design-patterns-creational-2/src/test/java/com/baeldung/singleton/SingletonUnitTest.java new file mode 100644 index 0000000000..d4154d9396 --- /dev/null +++ b/patterns-modules/design-patterns-creational-2/src/test/java/com/baeldung/singleton/SingletonUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.singleton; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; + +class SingletonUnitTest { + + @Test + void givenTwoValues_whenSum_thenReturnCorrectResult() { + SingletonDemo singletonDemo = new SingletonDemo(); + int result = singletonDemo.sum(12, 4); + Assertions.assertEquals(16, result); + } + + @Test + void givenMockedLogger_whenSum_thenReturnCorrectResult() { + Logger logger = mock(Logger.class); + + try (MockedStatic loggerMockedStatic = mockStatic(Logger.class)) { + loggerMockedStatic.when(Logger::getInstance).thenReturn(logger); + doNothing().when(logger).log(any()); + + SingletonDemo singletonDemo = new SingletonDemo(); + int result = singletonDemo.sum(12, 4); + Assertions.assertEquals(16, result); + } + } + +} diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/bridge/BridgePatternDriver.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/bridge/BridgePatternDriver.java index 31d18a2347..78e20a15be 100644 --- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/bridge/BridgePatternDriver.java +++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/bridge/BridgePatternDriver.java @@ -1,14 +1,16 @@ package com.baeldung.bridge; +import static com.baeldung.util.LoggerUtil.LOG; + public class BridgePatternDriver { public static void main(String[] args) { //a square with red color Shape square = new Square(new Red()); - System.out.println(square.draw()); + LOG.info(square.draw()); //a triangle with blue color Shape triangle = new Triangle(new Blue()); - System.out.println(triangle.draw()); + LOG.info(triangle.draw()); } } diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/composite/FinancialDepartment.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/composite/FinancialDepartment.java index 173281f833..b8ec67afab 100644 --- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/composite/FinancialDepartment.java +++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/composite/FinancialDepartment.java @@ -1,5 +1,7 @@ package com.baeldung.composite; +import static com.baeldung.util.LoggerUtil.LOG; + /** * Created by Gebruiker on 5/1/2018. */ @@ -14,7 +16,7 @@ public class FinancialDepartment implements Department { } public void printDepartmentName() { - System.out.println(getClass().getSimpleName()); + LOG.info(getClass().getSimpleName()); } public Integer getId() { diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/composite/SalesDepartment.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/composite/SalesDepartment.java index 7f5e903100..fdc3076b53 100644 --- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/composite/SalesDepartment.java +++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/composite/SalesDepartment.java @@ -1,5 +1,7 @@ package com.baeldung.composite; +import static com.baeldung.util.LoggerUtil.LOG; + /** * Created by Gebruiker on 5/1/2018. */ @@ -14,7 +16,7 @@ public class SalesDepartment implements Department { } public void printDepartmentName() { - System.out.println(getClass().getSimpleName()); + LOG.info(getClass().getSimpleName()); } public Integer getId() { diff --git a/patterns-modules/design-patterns-structural/src/main/resources/log4jstructuraldp.properties b/patterns-modules/design-patterns-structural/src/main/resources/log4jstructuraldp.properties index 5bc2bfe4b9..d7bfb41d12 100644 --- a/patterns-modules/design-patterns-structural/src/main/resources/log4jstructuraldp.properties +++ b/patterns-modules/design-patterns-structural/src/main/resources/log4jstructuraldp.properties @@ -1,6 +1,6 @@ # Root logger -log4j.rootLogger=INFO, file, stdout +log4j.rootLogger=INFO, stdout # Write to console log4j.appender.stdout=org.apache.log4j.ConsoleAppender diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index f35b22a19d..a99a180390 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -35,7 +35,7 @@ hibernate-queries hibernate-enterprise influxdb - java-cassandra + java-cassandra java-cockroachdb java-jdbi java-jpa @@ -109,7 +109,6 @@ spring-mybatis spring-persistence-simple spring-data-yugabytedb - fauna spring-data-rest java-mongodb diff --git a/persistence-modules/spring-boot-persistence-h2/pom.xml b/persistence-modules/spring-boot-persistence-h2/pom.xml index f643db2260..3c4bf888b3 100644 --- a/persistence-modules/spring-boot-persistence-h2/pom.xml +++ b/persistence-modules/spring-boot-persistence-h2/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -44,12 +44,19 @@ db-util ${db-util.version} + + + + org.hibernate.orm + hibernate-core + 6.3.1.Final + com.baeldung.h2db.demo.server.SpringBootApp - 1.0.4 + 1.0.7 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java index e54e725fd0..e1ae3c7cf0 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java @@ -1,7 +1,7 @@ package com.baeldung.h2.exceptions.models; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; @Entity public class User { diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java index 7402312e1c..3416cba154 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java @@ -3,15 +3,15 @@ package com.baeldung.h2db.demo.client; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; -import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; +import jakarta.annotation.PostConstruct; + @SpringBootApplication @ComponentScan("com.baeldung.h2db.demo.client") public class ClientSpringBootApp { diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java index e75b42a934..2a1eb66b22 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java @@ -3,7 +3,7 @@ package com.baeldung.h2db.demo.server; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.h2.tools.Server; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java index 9d69e7eb58..e737722ad4 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/Document.java @@ -1,13 +1,14 @@ package com.baeldung.h2db.lazy_load_no_trans.entity; +import jakarta.persistence.Column; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.Immutable; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; @Entity @Getter @@ -22,5 +23,6 @@ public class Document { private String title; + @Column(name="user_id") private Long userId; } diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java index ae9cb9e4e8..b46903e589 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/entity/User.java @@ -8,10 +8,10 @@ import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.Immutable; -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.ArrayList; import java.util.List; diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/notnull/models/Item.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/notnull/models/Item.java index d2c4015b86..d36c763f0f 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/notnull/models/Item.java +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/notnull/models/Item.java @@ -1,9 +1,10 @@ package com.baeldung.h2db.notnull.models; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.validation.constraints.NotNull; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.validation.constraints.NotNull; + import java.math.BigDecimal; @Entity diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/springboot/models/Country.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/springboot/models/Country.java index d6edab9421..c8bec1e908 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/springboot/models/Country.java +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/springboot/models/Country.java @@ -1,9 +1,9 @@ package com.baeldung.h2db.springboot.models; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import java.util.Objects; @Table(name = "countries") diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql index 2b4aa92542..7031d3ac02 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql @@ -4,9 +4,9 @@ insert into "user" values (103, 'user3', 'comment3'); insert into "user" values (104, 'user4', 'comment4'); insert into "user" values (105, 'user5', 'comment5'); -insert into "document" values (1, 'doc1', 101); -insert into "document" values (2, 'doc2', 101); -insert into "document" values (3, 'doc3', 101); -insert into "document" values (4, 'doc4', 101); -insert into "document" values (5, 'doc5', 102); -insert into "document" values (6, 'doc6', 102); \ No newline at end of file +insert into "document" ("id","title","user_id") values (1, 'doc1', 101); +insert into "document" ("id","title","user_id") values (2, 'doc2', 101); +insert into "document" ("id","title","user_id") values (3, 'doc3', 101); +insert into "document" ("id","title","user_id") values (4, 'doc4', 101); +insert into "document" ("id","title","user_id") values (5, 'doc5', 102); +insert into "document" ("id","title","user_id") values (6, 'doc6', 102); \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2db/notnull/ItemIntegrationTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2db/notnull/ItemIntegrationTest.java index 0e2e5e3319..1213df4780 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2db/notnull/ItemIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2db/notnull/ItemIntegrationTest.java @@ -2,16 +2,17 @@ package com.baeldung.h2db.notnull; import com.baeldung.h2db.notnull.daos.ItemRepository; import com.baeldung.h2db.notnull.models.Item; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import javax.validation.ConstraintViolationException; - import static org.assertj.core.api.Assertions.assertThatThrownBy; +import jakarta.validation.ConstraintViolationException; + @RunWith(SpringRunner.class) @SpringBootTest(classes = NotNullVsNullableApplication.class) public class ItemIntegrationTest { @@ -21,8 +22,8 @@ public class ItemIntegrationTest { @Test public void shouldNotAllowToPersistNullItemsPrice() { - assertThatThrownBy(() -> itemRepository.save(new Item())) - .hasRootCauseInstanceOf(ConstraintViolationException.class) - .hasStackTraceContaining("must not be null"); + assertThatThrownBy(() -> itemRepository.save(new Item())).hasRootCauseInstanceOf(ConstraintViolationException.class) + .hasStackTraceContaining("propertyPath=price") + .hasStackTraceContaining("null"); } } diff --git a/persistence-modules/spring-data-elasticsearch/pom.xml b/persistence-modules/spring-data-elasticsearch/pom.xml index a353f60ad2..6535b9ac4b 100644 --- a/persistence-modules/spring-data-elasticsearch/pom.xml +++ b/persistence-modules/spring-data-elasticsearch/pom.xml @@ -19,18 +19,18 @@ spring-data-elasticsearch ${spring-data-elasticsearch.version} - - - - - - - - - - - + + + + + + + + + + + org.elasticsearch.client @@ -47,6 +47,7 @@ spring-boot-autoconfigure + @@ -55,6 +56,7 @@ + 5.1.2 8.9.0 diff --git a/persistence-modules/spring-data-jpa-query-2/pom.xml b/persistence-modules/spring-data-jpa-query-2/pom.xml index c74c35c37b..1282d1d8a0 100644 --- a/persistence-modules/spring-data-jpa-query-2/pom.xml +++ b/persistence-modules/spring-data-jpa-query-2/pom.xml @@ -1,16 +1,16 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-data-jpa-query-2 spring-data-jpa-query-2 com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -38,6 +38,7 @@ mysql mysql-connector-java + 3.1.12 com.google.guava @@ -50,12 +51,19 @@ ${tomcat-dbcp.version} - org.hibernate + org.hibernate.orm hibernate-core + 6.3.1.Final - org.hibernate + org.hibernate.orm hibernate-envers + 6.3.1.Final + + + org.apache.commons + commons-lang3 + 3.13.0 org.springframework diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index f4a9b8a678..70349a664d 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.fetching.model; -import javax.persistence.*; +import jakarta.persistence.*; import java.io.Serializable; import java.sql.Date; diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java index 9fda4c43bb..d273f942a5 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.fetching.model; -import javax.persistence.*; +import jakarta.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java index a78eaa4ac0..6d18b2517c 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.fetching.model; -import javax.persistence.*; +import jakarta.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java index 79bdd86658..d43ee46844 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java @@ -3,12 +3,12 @@ package com.baeldung.persistence.dao.common; import java.io.Serializable; import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; public class AbstractJpaDao extends AbstractDao implements IOperations { diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java index 0ceb2d5626..15a4fdb3ca 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java @@ -3,29 +3,29 @@ package com.baeldung.persistence.model; import com.google.common.collect.Sets; import org.hibernate.annotations.OrderBy; import org.hibernate.envers.Audited; -import org.jboss.logging.Logger; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EntityListeners; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.NamedQuery; -import javax.persistence.OneToMany; -import javax.persistence.PrePersist; -import javax.persistence.PreRemove; -import javax.persistence.PreUpdate; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.NamedQuery; +import jakarta.persistence.OneToMany; +import jakarta.persistence.PrePersist; +import jakarta.persistence.PreRemove; +import jakarta.persistence.PreUpdate; import java.io.Serializable; import java.util.Date; import java.util.Set; +import java.util.logging.Logger; @Entity @NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") @@ -33,7 +33,7 @@ import java.util.Set; @EntityListeners(AuditingEntityListener.class) public class Bar implements Serializable { - private static final Logger LOGGER = Logger.getLogger(Bar.class); + private static final Logger LOGGER = Logger.getLogger(Bar.class.toString()); public enum OPERATION { INSERT, UPDATE, DELETE; diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Child.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Child.java index 19cfb2e237..9a1f95c019 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Child.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Child.java @@ -2,10 +2,10 @@ package com.baeldung.persistence.model; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; @Entity public class Child implements Serializable { diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java index ac79653b2b..b7e8adba42 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java @@ -2,20 +2,20 @@ package com.baeldung.persistence.model; import java.io.Serializable; -import javax.persistence.CascadeType; -import javax.persistence.Column; -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 javax.persistence.NamedNativeQueries; -import javax.persistence.NamedNativeQuery; -import javax.persistence.NamedStoredProcedureQuery; -import javax.persistence.ParameterMode; -import javax.persistence.StoredProcedureParameter; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +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; +import jakarta.persistence.NamedNativeQueries; +import jakarta.persistence.NamedNativeQuery; +import jakarta.persistence.NamedStoredProcedureQuery; +import jakarta.persistence.ParameterMode; +import jakarta.persistence.StoredProcedureParameter; import org.hibernate.envers.Audited; diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Parent.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Parent.java index fa6948990b..4149a0b883 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Parent.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Parent.java @@ -2,12 +2,12 @@ package com.baeldung.persistence.model; import java.io.Serializable; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; @Entity public class Parent implements Serializable { diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Person.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Person.java index 6a95a7acf5..3766639975 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Person.java +++ b/persistence-modules/spring-data-jpa-query-2/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/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java index 179dbf2ae7..648b06cf5f 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java @@ -1,6 +1,6 @@ package com.baeldung.spring.data.jpa.query; -import javax.persistence.*; +import jakarta.persistence.*; import java.time.LocalDate; import java.util.List; import java.util.Objects; diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java index 033f61fdd3..54cea74e04 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java @@ -1,8 +1,8 @@ package com.baeldung.spring.data.jpa.query; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.criteria.*; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.criteria.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java index f591773cde..d9ab75af2c 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java @@ -4,8 +4,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; import org.junit.After; import org.junit.AfterClass; @@ -30,15 +30,15 @@ import com.baeldung.spring.config.PersistenceTestConfig; @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class JPABarAuditIntegrationTest { - private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class); + private static final Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class); @BeforeClass - public static void setUpBeforeClass() throws Exception { + public static void setUpBeforeClass() { logger.info("setUpBeforeClass()"); } @AfterClass - public static void tearDownAfterClass() throws Exception { + public static void tearDownAfterClass(){ logger.info("tearDownAfterClass()"); } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java index 0603067810..0d22562a93 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java @@ -3,8 +3,8 @@ package com.baeldung.persistence.audit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; import org.junit.After; import org.junit.AfterClass; @@ -29,7 +29,7 @@ import com.baeldung.spring.config.PersistenceTestConfig; @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class SpringDataJPABarAuditIntegrationTest { - private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); + private static final Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); @BeforeClass public static void setUpBeforeClass() throws Exception { @@ -37,7 +37,7 @@ public class SpringDataJPABarAuditIntegrationTest { } @AfterClass - public static void tearDownAfterClass() throws Exception { + public static void tearDownAfterClass(){ logger.info("tearDownAfterClass()"); } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java index a7763bb0f8..92a9d8e2ec 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java @@ -17,7 +17,7 @@ public class FooFixtures { private static final Logger LOGGER = LoggerFactory.getLogger(FooFixtures.class); - private SessionFactory sessionFactory; + private final SessionFactory sessionFactory; public FooFixtures(final SessionFactory sessionFactory) { super(); @@ -28,8 +28,8 @@ public class FooFixtures { // API public void createBars() { - Session session = null; - Transaction tx = null; + Session session; + Transaction tx; session = sessionFactory.openSession(); tx = session.getTransaction(); try { @@ -39,13 +39,13 @@ public class FooFixtures { bar.setName("Bar_" + i); final Foo foo = new Foo("Foo_" + (i + 120)); foo.setBar(bar); - session.save(foo); + session.persist(foo); final Foo foo2 = new Foo(null); if (i % 2 == 0) { foo2.setName("LuckyFoo" + (i + 120)); } foo2.setBar(bar); - session.save(foo2); + session.persist(foo2); bar.getFooSet().add(foo); bar.getFooSet().add(foo2); session.merge(bar); @@ -53,16 +53,12 @@ public class FooFixtures { tx.commit(); session.flush(); } catch (final HibernateException he) { - if (tx != null) { - tx.rollback(); - } + tx.rollback(); LOGGER.error("Not able to open session", he); } catch (final Exception e) { LOGGER.error(e.getLocalizedMessage(), e); } finally { - if (session != null) { - session.close(); - } + session.close(); } } @@ -86,23 +82,18 @@ public class FooFixtures { try { tx.begin(); for (final Foo foo : fooList) { - - session.save(foo.getBar()); - session.save(foo); + session.persist(foo.getBar()); + session.persist(foo); } tx.commit(); session.flush(); } catch (final HibernateException he) { - if (tx != null) { - tx.rollback(); - } + tx.rollback(); LOGGER.error("Not able to open session", he); } catch (final Exception e) { LOGGER.error(e.getLocalizedMessage(), e); } finally { - if (session != null) { - session.close(); - } + session.close(); } } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java index fd7bc4aabf..528eed9d8d 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java @@ -1,19 +1,19 @@ package com.baeldung.persistence.hibernate; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; import java.util.List; -import org.hibernate.Criteria; -import org.hibernate.Query; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; -import org.hibernate.criterion.Projections; +import org.hibernate.query.Query; +import org.hibernate.query.SelectionQuery; +import org.hibernate.query.criteria.HibernateCriteriaBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -28,6 +28,8 @@ import com.baeldung.persistence.service.IFooService; import com.baeldung.spring.config.PersistenceTestConfig; import com.google.common.collect.Lists; +import jakarta.persistence.criteria.CriteriaQuery; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooPaginationPersistenceIntegrationTest { @@ -40,8 +42,6 @@ public class FooPaginationPersistenceIntegrationTest { private Session session; - // tests - @Before public final void before() { final int minimalNumberOfEntities = 25; @@ -59,20 +59,17 @@ public class FooPaginationPersistenceIntegrationTest { session.close(); } - // tests - @Test public final void whenContextIsBootstrapped_thenNoExceptions() { // } - @SuppressWarnings("unchecked") @Test public final void whenRetrievingPaginatedEntities_thenCorrectSize() { final int pageNumber = 1; final int pageSize = 10; - final Query query = session.createQuery("From Foo"); + final Query query = session.createQuery("From Foo",Foo.class); query.setFirstResult((pageNumber - 1) * pageSize); query.setMaxResults(pageSize); final List fooList = query.list(); @@ -80,19 +77,18 @@ public class FooPaginationPersistenceIntegrationTest { assertThat(fooList, hasSize(pageSize)); } - @SuppressWarnings("unchecked") @Test public final void whenRetrievingAllPages_thenCorrect() { int pageNumber = 1; final int pageSize = 10; final String countQ = "Select count (f.id) from Foo f"; - final Query countQuery = session.createQuery(countQ); + final Query countQuery = session.createQuery(countQ, Long.class); final Long countResult = (Long) countQuery.uniqueResult(); final List fooList = Lists.newArrayList(); int totalEntities = 0; - final Query query = session.createQuery("From Foo"); + final Query query = session.createQuery("From Foo", Foo.class); while (totalEntities < countResult) { query.setFirstResult((pageNumber - 1) * pageSize); query.setMaxResults(pageSize); @@ -102,17 +98,16 @@ public class FooPaginationPersistenceIntegrationTest { } } - @SuppressWarnings("unchecked") @Test public final void whenRetrievingLastPage_thenCorrectSize() { final int pageSize = 10; final String countQ = "Select count (f.id) from Foo f"; - final Query countQuery = session.createQuery(countQ); - final Long countResults = (Long) countQuery.uniqueResult(); + final Query countQuery = session.createQuery(countQ, Long.class); + final Long countResults = countQuery.uniqueResult(); final int lastPageNumber = (int) (Math.ceil(countResults / pageSize)); - final Query selectQuery = session.createQuery("From Foo"); + final Query selectQuery = session.createQuery("From Foo",Foo.class); selectQuery.setFirstResult((lastPageNumber - 1) * pageSize); selectQuery.setMaxResults(pageSize); final List lastPage = selectQuery.list(); @@ -126,9 +121,9 @@ public class FooPaginationPersistenceIntegrationTest { public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() { final int pageSize = 10; final String hql = "FROM Foo f order by f.name"; - final Query query = session.createQuery(hql); + final Query query = session.createQuery(hql,Foo.class); - final ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY); + final ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY); // resultScroll.last(); // final int totalResults = resultScroll.getRowNumber() + 1; @@ -138,7 +133,7 @@ public class FooPaginationPersistenceIntegrationTest { final List fooPage = Lists.newArrayList(); int i = 0; while (pageSize > i++) { - fooPage.add((Foo) resultScroll.get(0)); + fooPage.add((Foo) resultScroll.get()); if (!resultScroll.next()) { break; } @@ -147,36 +142,42 @@ public class FooPaginationPersistenceIntegrationTest { assertThat(fooPage, hasSize(lessThan(10 + 1))); } - @SuppressWarnings("unchecked") @Test public final void givenUsingTheCriteriaApi_whenRetrievingFirstPage_thenCorrect() { final int pageSize = 10; - final Criteria criteria = session.createCriteria(Foo.class); - criteria.setFirstResult(0); - criteria.setMaxResults(pageSize); - final List firstPage = criteria.list(); + CriteriaQuery selectQuery = session.getCriteriaBuilder().createQuery(Foo.class); + selectQuery.from(Foo.class); + + SelectionQuery query = session.createQuery(selectQuery); + query.setFirstResult(0); + query.setMaxResults(pageSize); + final List firstPage = query.list(); assertThat(firstPage, hasSize(pageSize)); } - @SuppressWarnings("unchecked") @Test public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() { - final Criteria criteriaCount = session.createCriteria(Foo.class); - criteriaCount.setProjection(Projections.rowCount()); - final Long count = (Long) criteriaCount.uniqueResult(); + + HibernateCriteriaBuilder qb = session.getCriteriaBuilder(); + CriteriaQuery cq = qb.createQuery(Long.class); + cq.select(qb.count(cq.from(Foo.class))); + final Long count = session.createQuery(cq).getSingleResult(); int pageNumber = 1; final int pageSize = 10; final List fooList = Lists.newArrayList(); - final Criteria criteria = session.createCriteria(Foo.class); + CriteriaQuery selectQuery = session.getCriteriaBuilder().createQuery(Foo.class); + selectQuery.from(Foo.class); + SelectionQuery query = session.createQuery(selectQuery); + int totalEntities = 0; while (totalEntities < count.intValue()) { - criteria.setFirstResult((pageNumber - 1) * pageSize); - criteria.setMaxResults(pageSize); - fooList.addAll(criteria.list()); + query.setFirstResult((pageNumber - 1) * pageSize); + query.setMaxResults(pageSize); + fooList.addAll(query.list()); totalEntities = fooList.size(); pageNumber++; } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java index 6078eb3af0..7e2d23da96 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java @@ -2,15 +2,17 @@ package com.baeldung.persistence.hibernate; import static org.junit.Assert.assertNull; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Set; -import org.hibernate.Criteria; -import org.hibernate.NullPrecedence; -import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; -import org.hibernate.criterion.Order; +import org.hibernate.query.NullPrecedence; +import org.hibernate.query.Order; +import org.hibernate.query.Query; +import org.hibernate.query.SortDirection; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -26,6 +28,8 @@ import com.baeldung.persistence.model.Bar; import com.baeldung.persistence.model.Foo; import com.baeldung.spring.config.PersistenceTestConfig; +import jakarta.persistence.criteria.CriteriaQuery; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) @SuppressWarnings("unchecked") @@ -91,7 +95,7 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() { final String hql = "FROM Foo f ORDER BY f.name ASC"; - final Query query = session.createQuery(hql); + Query query = session.createQuery(hql, Foo.class); final List fooList = query.list(); for (final Foo foo : fooList) { LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); @@ -101,7 +105,7 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenHQlSortingByMultipleAttributes_thenSortedResults() { final String hql = "FROM Foo f ORDER BY f.name, f.id"; - final Query query = session.createQuery(hql); + Query query = session.createQuery(hql, Foo.class); final List fooList = query.list(); for (final Foo foo : fooList) { LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); @@ -111,7 +115,7 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() { final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC"; - final Query query = session.createQuery(hql); + Query query = session.createQuery(hql, Foo.class); final List fooList = query.list(); for (final Foo foo : fooList) { LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); @@ -120,9 +124,12 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() { - final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.asc("id")); - final List fooList = criteria.list(); + CriteriaQuery selectQuery = session.getCriteriaBuilder().createQuery(Foo.class); + selectQuery.from(Foo.class); + Query query = session.createQuery(selectQuery); + + query.setOrder(Collections.singletonList(Order.asc(Foo.class,"id"))); + final List fooList = query.list(); for (final Foo foo : fooList) { LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } @@ -130,10 +137,16 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() { - final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.asc("name")); - criteria.addOrder(Order.asc("id")); - final List fooList = criteria.list(); + + CriteriaQuery selectQuery = session.getCriteriaBuilder().createQuery(Foo.class); + selectQuery.from(Foo.class); + Query query = session.createQuery(selectQuery); + + List> orderBy = new ArrayList<>(2); + orderBy.add(Order.asc(Foo.class,"name")); + orderBy.add(Order.asc(Foo.class,"id")); + query.setOrder(orderBy); + final List fooList = query.list(); for (final Foo foo : fooList) { LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } @@ -141,9 +154,15 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() { - final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST)); - final List fooList = criteria.list(); + CriteriaQuery selectQuery = session.getCriteriaBuilder().createQuery(Foo.class); + selectQuery.from(Foo.class); + Query query = session.createQuery(selectQuery); + + List> orderBy = new ArrayList<>(2); + orderBy.add(Order.by(Foo.class,"name", SortDirection.ASCENDING, NullPrecedence.LAST)); + query.setOrder(orderBy); + + final List fooList = query.list(); assertNull(fooList.get(fooList.toArray().length - 1).getName()); for (final Foo foo : fooList) { LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); @@ -152,9 +171,15 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() { - final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST)); - final List fooList = criteria.list(); + CriteriaQuery selectQuery = session.getCriteriaBuilder().createQuery(Foo.class); + selectQuery.from(Foo.class); + Query query = session.createQuery(selectQuery); + + List> orderBy = new ArrayList<>(2); + orderBy.add(Order.by(Foo.class,"name", SortDirection.ASCENDING, NullPrecedence.FIRST)); + query.setOrder(orderBy); + + final List fooList = query.list(); assertNull(fooList.get(0).getName()); for (final Foo foo : fooList) { LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); @@ -164,7 +189,7 @@ public class FooSortingPersistenceIntegrationTest { @Test public final void whenSortingBars_thenBarsWithSortedFoos() { final String hql = "FROM Bar b ORDER BY b.id"; - final Query query = session.createQuery(hql); + final Query query = session.createQuery(hql, Bar.class); final List barList = query.list(); for (final Bar bar : barList) { final Set fooSet = bar.getFooSet(); diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java index f6dedfc6de..d8216fc072 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java @@ -5,14 +5,14 @@ import static org.junit.Assert.assertEquals; import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.StoredProcedureQuery; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.StoredProcedureQuery; -import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.exception.SQLGrammarException; +import org.hibernate.query.Query; import org.junit.After; import org.junit.Assume; import org.junit.Before; @@ -59,22 +59,22 @@ public class FooStoredProceduresLiveTest { private boolean getFoosByNameExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); + Query sqlQuery = session.createNativeQuery("CALL GetFoosByName()",Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { - LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e); + LOGGER.error("WARNING : GetFoosByName() Procedure may be missing ", e); return false; } } private boolean getAllFoosExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); + Query sqlQuery = session.createNativeQuery("CALL GetAllFoos()",Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { - LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e); + LOGGER.error("WARNING : GetAllFoos() Procedure may be missing ", e); return false; } } @@ -90,9 +90,9 @@ public class FooStoredProceduresLiveTest { fooService.create(new Foo(randomAlphabetic(6))); - // Stored procedure getAllFoos using createSQLQuery - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - @SuppressWarnings("unchecked") + // Stored procedure getAllFoos using createQuery + Query sqlQuery = session.createNativeQuery("CALL GetAllFoos()", Foo.class); + List allFoos = sqlQuery.list(); for (Foo foo : allFoos) { LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName()); @@ -100,8 +100,8 @@ public class FooStoredProceduresLiveTest { assertEquals(allFoos.size(), fooService.findAll().size()); // Stored procedure getAllFoos using a Named Query - Query namedQuery = session.getNamedQuery("callGetAllFoos"); - @SuppressWarnings("unchecked") + Query namedQuery = session.createNamedQuery("callGetAllFoos", Foo.class); + List allFoos2 = namedQuery.list(); for (Foo foo : allFoos2) { LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName()); @@ -110,6 +110,7 @@ public class FooStoredProceduresLiveTest { StoredProcedureQuery spQuery = entityManager.createNamedStoredProcedureQuery("GetAllFoos"); + @SuppressWarnings("unchecked") List allFoos3 = spQuery.getResultList(); for (Foo foo : allFoos3) { LOGGER.info("getAllFoos() StoredProcedureQuery result : {}", foo.getName()); @@ -124,16 +125,16 @@ public class FooStoredProceduresLiveTest { fooService.create(new Foo("NewFooName")); // Stored procedure getFoosByName using createSQLQuery() - Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); - @SuppressWarnings("unchecked") + Query sqlQuery = session.createNativeQuery("CALL GetFoosByName(:fooName)", Foo.class).setParameter("fooName", "NewFooName"); + List allFoosByName = sqlQuery.list(); for (Foo foo : allFoosByName) { LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); } // Stored procedure getFoosByName using getNamedQuery() - Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); - @SuppressWarnings("unchecked") + Query namedQuery = session.createQuery("callGetFoosByName", Foo.class).setParameter("fooName", "NewFooName"); + List allFoosByName2 = namedQuery.list(); for (Foo foo : allFoosByName2) { LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); @@ -142,6 +143,7 @@ public class FooStoredProceduresLiveTest { StoredProcedureQuery spQuery = entityManager. createNamedStoredProcedureQuery("GetFoosByName") .setParameter("fooName", "NewFooName"); + @SuppressWarnings("unchecked") List allFoosByName3 = spQuery.getResultList(); assertEquals(1, allFoosByName3.size()); for (Foo foo : allFoosByName3) { diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java index 04c0ad5e0a..724adc3aad 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java @@ -19,7 +19,7 @@ public class Library { private List addresses = new ArrayList<>(); @ElementCollection(targetClass = String.class, fetch = FetchType.EAGER) - @CollectionTable(name = "book", joinColumns = @JoinColumn(name = "library_id")) + @CollectionTable(name = "books", joinColumns = @JoinColumn(name = "library_id")) @Column(name = "book", nullable = false) private List books = new ArrayList<>(); 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 cd6dbe3994..37f37d548d 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,5 +1,5 @@ spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=none - +spring.jpa.generate-ddl=true 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/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java index 8f34e43e3f..9ea865c04f 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java @@ -21,13 +21,13 @@ public class BookPagingAndSortingRepositoryIntegrationTest { @Test public void givenDbContainsBooks_whenfindBooksByAuthor_thenReturnBooksByAuthor() { - Book book1 = new Book("Spring Data", "John Doe", "1234567890"); - Book book2 = new Book("Spring Data 2", "John Doe", "1234567891"); - Book book3 = new Book("Spring Data 3", "John Doe", "1234567892"); + Book book1 = new Book("Spring Data", "John Miller", "1234567890"); + Book book2 = new Book("Spring Data 2", "John Miller", "1234567891"); + Book book3 = new Book("Spring Data 3", "John Miller", "1234567892"); bookPagingAndSortingRepository.saveAll(Arrays.asList(book1, book2, book3)); Pageable pageable = PageRequest.of(0, 2, Sort.by("title").descending()); - List books = bookPagingAndSortingRepository.findBooksByAuthor("John Doe", pageable); + List books = bookPagingAndSortingRepository.findBooksByAuthor("John Miller", pageable); Assertions.assertEquals(2, books.size()); Assertions.assertEquals(book3.getId(), books.get(0).getId()); Assertions.assertEquals(book2.getId(), books.get(1).getId()); diff --git a/pom.xml b/pom.xml index 5d8358f05e..327d83017f 100644 --- a/pom.xml +++ b/pom.xml @@ -361,7 +361,6 @@ muleesb web-modules/java-lite - web-modules/restx persistence-modules/deltaspike persistence-modules/hibernate-ogm persistence-modules/spring-data-cassandra-reactive @@ -534,7 +533,6 @@ lombok-modules/lombok-custom muleesb web-modules/java-lite - web-modules/restx persistence-modules/deltaspike persistence-modules/hibernate-ogm persistence-modules/spring-data-cassandra-reactive @@ -694,6 +692,7 @@ + parent-boot-3 lombok-modules osgi spring-katharsis @@ -728,6 +727,7 @@ spring-cloud-modules/spring-cloud-data-flow spring-cloud-modules/spring-cloud-eureka spring-cloud-modules/spring-cloud-netflix-feign + spring-cloud-modules/spring-cloud-security spring-cloud-modules/spring-cloud-stream-starters spring-cloud-modules/spring-cloud-zuul-eureka-integration @@ -769,14 +769,6 @@ core-groovy-modules core-java-modules - - - - - - - - custom-pmd data-structures ddd-contexts @@ -941,7 +933,9 @@ language-interop gradle-modules/gradle/maven-to-gradle persistence-modules/spring-data-neo4j - parent-boot-3 + gcp-firebase + spring-di-4 + spring-kafka-2 @@ -976,6 +970,7 @@ + parent-boot-3 lombok-modules osgi spring-katharsis @@ -1011,6 +1006,7 @@ spring-cloud-modules/spring-cloud-data-flow spring-cloud-modules/spring-cloud-netflix-feign spring-cloud-modules/spring-cloud-stream-starters + spring-cloud-modules/spring-cloud-security spring-cloud-modules/spring-cloud-zuul-eureka-integration spring-exceptions @@ -1225,6 +1221,10 @@ gradle-modules/gradle/maven-to-gradle persistence-modules/spring-data-neo4j spring-actuator + gcp-firebase + spring-di-4 + spring-kafka-2 + @@ -1240,7 +1240,6 @@ parent-boot-1 parent-boot-2 - parent-boot-3 parent-spring-4 parent-spring-5 parent-spring-6 diff --git a/spring-4/src/test/resources/logback-test.xml b/spring-4/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..a273ab5d26 --- /dev/null +++ b/spring-4/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/model/User.java b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/model/User.java new file mode 100644 index 0000000000..37008bb061 --- /dev/null +++ b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/model/User.java @@ -0,0 +1,22 @@ +package com.baeldung.webflux.zipwhen.model; + +public class User { + + private final String id; + private final String email; + + public User(String id, String email) { + this.id = id; + this.email = email; + + } + + public String getId() { + return id; + } + + public String getEmail() { + return email; + } + +} diff --git a/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/service/DatabaseService.java b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/service/DatabaseService.java new file mode 100644 index 0000000000..d420646871 --- /dev/null +++ b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/service/DatabaseService.java @@ -0,0 +1,24 @@ +package com.baeldung.webflux.zipwhen.service; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.baeldung.webflux.zipwhen.model.User; + +import reactor.core.publisher.Mono; + +public class DatabaseService { + private Map dataStore = new ConcurrentHashMap<>(); + + public Mono saveUserData(User user) { + return Mono.create(sink -> { + try { + dataStore.put(user.getId(), user); + sink.success(true); + } catch (Exception e) { + sink.success(false); + } + }); + } +} + diff --git a/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/service/EmailService.java b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/service/EmailService.java new file mode 100644 index 0000000000..9c0340b7ee --- /dev/null +++ b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/service/EmailService.java @@ -0,0 +1,20 @@ +package com.baeldung.webflux.zipwhen.service; + +import reactor.core.publisher.Mono; + +public class EmailService { + private final UserService userService; + + public EmailService(UserService userService) { + this.userService = userService; + } + + public Mono sendEmail(String userId) { + return userService.getUser(userId) + .flatMap(user -> { + System.out.println("Sending email to: " + user.getEmail()); + return Mono.just(true); + }) + .defaultIfEmpty(false); + } +} diff --git a/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/service/UserService.java b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/service/UserService.java new file mode 100644 index 0000000000..fe602fbc33 --- /dev/null +++ b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/service/UserService.java @@ -0,0 +1,12 @@ +package com.baeldung.webflux.zipwhen.service; + +import com.baeldung.webflux.zipwhen.model.User; + +import reactor.core.publisher.Mono; + +public class UserService { + public Mono getUser(String userId) { + return Mono.just(new User(userId, "john Major")); + } +} + diff --git a/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/web/UserController.java b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/web/UserController.java new file mode 100644 index 0000000000..dbd89c45d3 --- /dev/null +++ b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/zipwhen/web/UserController.java @@ -0,0 +1,43 @@ +package com.baeldung.webflux.zipwhen.web; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +import com.baeldung.webflux.zipwhen.model.User; +import com.baeldung.webflux.zipwhen.service.DatabaseService; +import com.baeldung.webflux.zipwhen.service.EmailService; +import com.baeldung.webflux.zipwhen.service.UserService; + +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; +import reactor.util.function.Tuples; + +public class UserController { + private final UserService userService; + private final EmailService emailService; + private final DatabaseService databaseService; + + public UserController(UserService userService, EmailService emailService, DatabaseService databaseService) { + this.userService = userService; + this.emailService = emailService; + this.databaseService = databaseService; + } + + @GetMapping("/example/{userId}") + public Mono> combineAllDataFor(@PathVariable String userId) { + Mono userMono = userService.getUser(userId); + Mono emailSentMono = emailService.sendEmail(userId) + .subscribeOn(Schedulers.parallel()); + Mono databaseResultMono = userMono.flatMap(user -> databaseService.saveUserData(user) + .map(Object::toString)); + + return userMono.zipWhen(user -> emailSentMono, Tuples::of) + .zipWhen(tuple -> databaseResultMono, (tuple, databaseResult) -> { + User user = tuple.getT1(); + Boolean emailSent = tuple.getT2(); + return ResponseEntity.ok() + .body("Response: " + user + ", Email Sent: " + emailSent + ", Database Result: " + databaseResult); + }); + } +} diff --git a/spring-5-webflux-2/src/test/java/com/baeldung/webflux/zipwhen/UserControllerUnitTest.java b/spring-5-webflux-2/src/test/java/com/baeldung/webflux/zipwhen/UserControllerUnitTest.java new file mode 100644 index 0000000000..8ed4cfb6c6 --- /dev/null +++ b/spring-5-webflux-2/src/test/java/com/baeldung/webflux/zipwhen/UserControllerUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.webflux.zipwhen; + +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import com.baeldung.webflux.zipwhen.model.User; +import com.baeldung.webflux.zipwhen.service.DatabaseService; +import com.baeldung.webflux.zipwhen.service.EmailService; +import com.baeldung.webflux.zipwhen.service.UserService; +import com.baeldung.webflux.zipwhen.web.UserController; + +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +public class UserControllerUnitTest { + @Test + public void givenUserId_whenCombineAllData_thenReturnsMonoWithCombinedData() { + UserService userService = Mockito.mock(UserService.class); + EmailService emailService = Mockito.mock(EmailService.class); + DatabaseService databaseService = Mockito.mock(DatabaseService.class); + + String userId = "123"; + User user = new User(userId, "John Doe"); + + Mockito.when(userService.getUser(userId)) + .thenReturn(Mono.just(user)); + Mockito.when(emailService.sendEmail(userId)) + .thenReturn(Mono.just(true)); + Mockito.when(databaseService.saveUserData(user)) + .thenReturn(Mono.just(true)); + + UserController userController = new UserController(userService, emailService, databaseService); + + Mono> responseMono = userController.combineAllDataFor(userId); + + StepVerifier.create(responseMono) + .expectNextMatches(responseEntity -> responseEntity.getStatusCode() == HttpStatus.OK && responseEntity.getBody() + .equals("Response: " + user + ", Email Sent: true, Database Result: " + true)) + .verifyComplete(); + } +} diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 2b4a94a7a5..389dbf2d55 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -105,6 +105,7 @@ spring-boot-documentation spring-boot-3-url-matching spring-boot-graalvm-docker + spring-boot-validations diff --git a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/reuse/ReusableContainersLiveTest.java b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/reuse/ReusableContainersLiveTest.java new file mode 100644 index 0000000000..4a96160e32 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/reuse/ReusableContainersLiveTest.java @@ -0,0 +1,52 @@ +package com.baeldung.testcontainers.reuse; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.containers.MongoDBContainer; +import org.testcontainers.utility.DockerImageName; + +import com.baeldung.testcontainers.support.MiddleEarthCharacter; +import com.baeldung.testcontainers.support.MiddleEarthCharactersRepository; + +@SpringBootTest +class ReusableContainersLiveTest { + + static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10")) + .withReuse(true); + + @BeforeAll + static void beforeAll() { + mongoDBContainer.start(); + } + + @DynamicPropertySource + static void setProperties(DynamicPropertyRegistry registry) { + registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl); + } + + @Autowired + private MiddleEarthCharactersRepository repository; + + @Test + void whenRunningMultipleTimes_thenContainerShouldBeReused_andTestShouldFail() { + assertThat(repository.findAll()) + .isEmpty(); + + repository.saveAll(List.of( + new MiddleEarthCharacter("Frodo", "hobbit"), + new MiddleEarthCharacter("Samwise", "hobbit")) + ); + + assertThat(repository.findAll()) + .hasSize(2); + } + +} diff --git a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/DynamicPropertiesLiveTest.java b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/support/DynamicPropertiesLiveTest.java similarity index 98% rename from spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/DynamicPropertiesLiveTest.java rename to spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/support/DynamicPropertiesLiveTest.java index 2633f227d4..d2511286e3 100644 --- a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/DynamicPropertiesLiveTest.java +++ b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/support/DynamicPropertiesLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.testcontainers; +package com.baeldung.testcontainers.support; import static io.restassured.RestAssured.when; import static org.hamcrest.Matchers.hasItems; diff --git a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/LocalDevApplication.java b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/support/LocalDevApplication.java similarity index 95% rename from spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/LocalDevApplication.java rename to spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/support/LocalDevApplication.java index 1b6fe32c97..0b49fba26b 100644 --- a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/LocalDevApplication.java +++ b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/support/LocalDevApplication.java @@ -7,6 +7,7 @@ import org.springframework.boot.testcontainers.service.connection.ServiceConnect import org.springframework.context.annotation.Bean; import org.testcontainers.containers.MongoDBContainer; import org.testcontainers.utility.DockerImageName; +import com.baeldung.testcontainers.Application; // Testcontainers require a valid docker installation. diff --git a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/ServiceConnectionLiveTest.java b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/support/ServiceConnectionLiveTest.java similarity index 97% rename from spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/ServiceConnectionLiveTest.java rename to spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/support/ServiceConnectionLiveTest.java index 51b69c44b3..a93c136e1c 100644 --- a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/ServiceConnectionLiveTest.java +++ b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/support/ServiceConnectionLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.testcontainers; +package com.baeldung.testcontainers.support; import static io.restassured.RestAssured.when; import static org.hamcrest.Matchers.hasItems; diff --git a/spring-boot-modules/spring-boot-aws/pom.xml b/spring-boot-modules/spring-boot-aws/pom.xml index 460acae247..44cd38be3f 100644 --- a/spring-boot-modules/spring-boot-aws/pom.xml +++ b/spring-boot-modules/spring-boot-aws/pom.xml @@ -14,6 +14,7 @@ org.springframework.boot spring-boot-starter-parent 2.7.11 + diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index 13339c9de1..ebba1f7f67 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -11,9 +11,10 @@ This is a simple application demonstrating integration between Keycloak and Spring Boot. - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -105,7 +106,7 @@ com.baeldung.keycloak.SpringBootKeycloakApp 4.0.0 1.6.3 - 2.5.0 + 3.1.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java index 3293446b1d..b0aff5e724 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java @@ -1,9 +1,9 @@ package com.baeldung.keycloak; -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 Customer { diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakLogoutHandler.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakLogoutHandler.java index 06c41e9b1d..d04fff8378 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakLogoutHandler.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakLogoutHandler.java @@ -10,8 +10,8 @@ import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; @Component public class KeycloakLogoutHandler implements LogoutHandler { diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java index 3423f8eb2b..eb7767480f 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -12,6 +12,7 @@ import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity @@ -32,7 +33,7 @@ class SecurityConfig { @Bean public SecurityFilterChain clientFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests() - .antMatchers("/") + .requestMatchers(new AntPathRequestMatcher("/")) .permitAll() .anyRequest() .authenticated(); @@ -48,7 +49,7 @@ class SecurityConfig { @Bean public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests() - .antMatchers("/customers*") + .requestMatchers(new AntPathRequestMatcher("/customers*")) .hasRole("USER") .anyRequest() .authenticated(); diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java index bbd96c8135..8843aee25a 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java @@ -8,7 +8,7 @@ import java.security.Principal; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; @Controller public class WebController { diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/ProductsEndpoint.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/ProductsEndpoint.java index 58f7739af0..b072789078 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/ProductsEndpoint.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/ProductsEndpoint.java @@ -10,7 +10,7 @@ import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.RolesAllowed; import java.util.Map; @Endpoint diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java index 171c7bf330..508061396f 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java +++ b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; diff --git a/spring-boot-modules/spring-boot-springdoc-2/pom.xml b/spring-boot-modules/spring-boot-springdoc-2/pom.xml index 1ea52667c5..dace3d17ef 100644 --- a/spring-boot-modules/spring-boot-springdoc-2/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc-2/pom.xml @@ -112,7 +112,7 @@ - 2.1.0 + 2.2.0 1.4 diff --git a/spring-boot-modules/spring-boot-swagger-springfox/src/main/java/com/baeldung/springdoc/demo/controller/SwaggerController.java b/spring-boot-modules/spring-boot-swagger-springfox/src/main/java/com/baeldung/springdoc/demo/controller/SwaggerController.java index 79c35e025e..bffe0659a6 100644 --- a/spring-boot-modules/spring-boot-swagger-springfox/src/main/java/com/baeldung/springdoc/demo/controller/SwaggerController.java +++ b/spring-boot-modules/spring-boot-swagger-springfox/src/main/java/com/baeldung/springdoc/demo/controller/SwaggerController.java @@ -8,6 +8,6 @@ public class SwaggerController { @RequestMapping("/myproject") public String getRedirectUrl() { - return "redirect:swagger-ui.html"; + return "redirect:swagger-ui/"; } } \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-validations/README.md b/spring-boot-modules/spring-boot-validations/README.md new file mode 100644 index 0000000000..0d07204f3f --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Validate Boolean Type in Spring Boot](https://www.baeldung.com/spring-boot-validate-boolean-type) diff --git a/spring-boot-modules/spring-boot-validations/pom.xml b/spring-boot-modules/spring-boot-validations/pom.xml new file mode 100644 index 0000000000..13044471af --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/pom.xml @@ -0,0 +1,35 @@ + + 4.0.0 + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + + spring-boot-validations + spring-boot-validations + Demo of Validations in Spring Boot + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-validation + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..c0490d50c6 --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/Application.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/controller/ValidationController.java b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/controller/ValidationController.java new file mode 100644 index 0000000000..d4ea9a6336 --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/controller/ValidationController.java @@ -0,0 +1,33 @@ +package com.baeldung.controller; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.dto.BooleanObject; +import com.baeldung.service.ValidationService; + +@RestController +public class ValidationController { + + @Autowired + ValidationService service; + + @PostMapping("/validateBoolean") + public ResponseEntity processBooleanObject(@RequestBody @Valid BooleanObject booleanObj) { + return ResponseEntity.ok("BooleanObject is valid"); + } + + @PostMapping("/validateBooleanAtService") + public ResponseEntity processBooleanObjectAtService() { + BooleanObject boolObj = new BooleanObject(); + boolObj.setBoolField(Boolean.TRUE); + boolObj.setTrueField(Boolean.FALSE); + service.processBoolean(boolObj); + return ResponseEntity.ok("BooleanObject is valid"); + } +} diff --git a/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/controlleradvice/GlobalExceptionHandler.java b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/controlleradvice/GlobalExceptionHandler.java new file mode 100644 index 0000000000..82f0839acf --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/controlleradvice/GlobalExceptionHandler.java @@ -0,0 +1,37 @@ +package com.baeldung.controlleradvice; + +import java.util.stream.Collectors; + +import javax.validation.ConstraintViolationException; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + public String handleValidationException(MethodArgumentNotValidException ex) { + return ex.getBindingResult() + .getFieldErrors() + .stream() + .map(e -> e.getDefaultMessage()) + .collect(Collectors.joining(",")); + } + + @ExceptionHandler(IllegalArgumentException.class) + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + public String handleIllegalArugmentException(IllegalArgumentException ex) { + return ex.getMessage(); + } + + @ExceptionHandler(ConstraintViolationException.class) + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + public String handleConstraintViolationException(ConstraintViolationException ex) { + return ex.getMessage(); + } +} diff --git a/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/deserializer/BooleanDeserializer.java b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/deserializer/BooleanDeserializer.java new file mode 100644 index 0000000000..01a8e0eba0 --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/deserializer/BooleanDeserializer.java @@ -0,0 +1,21 @@ +package com.baeldung.deserializer; + +import java.io.IOException; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +public class BooleanDeserializer extends JsonDeserializer { + @Override + public Boolean deserialize(JsonParser parser, DeserializationContext context) throws IOException { + String value = parser.getText(); + if (value != null && value.equals("+")) { + return Boolean.TRUE; + } else if (value != null && value.equals("-")) { + return Boolean.FALSE; + } else { + throw new IllegalArgumentException("Only values accepted as Boolean are + and -"); + } + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/dto/BooleanObject.java b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/dto/BooleanObject.java new file mode 100644 index 0000000000..750b23fe11 --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/dto/BooleanObject.java @@ -0,0 +1,56 @@ +package com.baeldung.dto; + +import javax.validation.constraints.AssertFalse; +import javax.validation.constraints.AssertTrue; +import javax.validation.constraints.NotNull; + +import com.baeldung.deserializer.BooleanDeserializer; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +public class BooleanObject { + + @NotNull(message = "boolField cannot be null") + Boolean boolField; + + @AssertTrue(message = "trueField must have true value") + Boolean trueField; + + @NotNull(message = "falseField cannot be null") + @AssertFalse(message = "falseField must have false value") + Boolean falseField; + + @JsonDeserialize(using = BooleanDeserializer.class) + Boolean boolStringVar; + + public Boolean getBoolField() { + return boolField; + } + + public void setBoolField(Boolean boolField) { + this.boolField = boolField; + } + + public Boolean getTrueField() { + return trueField; + } + + public void setTrueField(Boolean trueField) { + this.trueField = trueField; + } + + public Boolean getFalseField() { + return falseField; + } + + public void setFalseField(Boolean falseField) { + this.falseField = falseField; + } + + public Boolean getBoolStringVar() { + return boolStringVar; + } + + public void setBoolStringVar(Boolean boolStringVar) { + this.boolStringVar = boolStringVar; + } +} diff --git a/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/service/ValidationService.java b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/service/ValidationService.java new file mode 100644 index 0000000000..3fc7160bd5 --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/service/ValidationService.java @@ -0,0 +1,17 @@ +package com.baeldung.service; + +import javax.validation.Valid; + +import org.springframework.stereotype.Service; +import org.springframework.validation.annotation.Validated; + +import com.baeldung.dto.BooleanObject; + +@Service +@Validated +public class ValidationService { + + public void processBoolean(@Valid BooleanObject booleanObj) { + // further processing + } +} diff --git a/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/controller/ValidationControllerUnitTest.java b/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/controller/ValidationControllerUnitTest.java new file mode 100644 index 0000000000..f05d76e3f1 --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/controller/ValidationControllerUnitTest.java @@ -0,0 +1,125 @@ +package com.baeldung.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.service.ValidationService; + +@ExtendWith(SpringExtension.class) +@WebMvcTest(controllers = ValidationController.class) +class ValidationControllerUnitTest { + + @Autowired + private MockMvc mockMvc; + + @TestConfiguration + static class EmployeeServiceImplTestContextConfiguration { + @Bean + public ValidationService validationService() { + return new ValidationService() { + }; + } + } + + @Autowired + ValidationService service; + + @Test + void whenNullInputForBooleanField_thenHttpBadRequestAsHttpResponse() throws Exception { + String postBody = "{\"boolField\":null,\"trueField\":true,\"falseField\":false,\"boolStringVar\":\"+\"}"; + + mockMvc.perform(post("/validateBoolean").contentType("application/json") + .content(postBody)) + .andExpect(status().isBadRequest()); + } + + @Test + void whenInvalidInputForTrueBooleanField_thenErrorResponse() throws Exception { + String postBody = "{\"boolField\":true,\"trueField\":false,\"falseField\":false,\"boolStringVar\":\"+\"}"; + + String output = mockMvc.perform(post("/validateBoolean").contentType("application/json") + .content(postBody)) + .andReturn() + .getResponse() + .getContentAsString(); + + assertEquals("trueField must have true value", output); + } + + @Test + void whenInvalidInputForFalseBooleanField_thenErrorResponse() throws Exception { + String postBody = "{\"boolField\":true,\"trueField\":true,\"falseField\":true,\"boolStringVar\":\"+\"}"; + + String output = mockMvc.perform(post("/validateBoolean").contentType("application/json") + .content(postBody)) + .andReturn() + .getResponse() + .getContentAsString(); + + assertEquals("falseField must have false value", output); + } + + @Test + void whenInvalidBooleanFromJson_thenErrorResponse() throws Exception { + String postBody = "{\"boolField\":true,\"trueField\":true,\"falseField\":false,\"boolStringVar\":\"plus\"}"; + + String output = mockMvc.perform(post("/validateBoolean").contentType("application/json") + .content(postBody)) + .andReturn() + .getResponse() + .getContentAsString(); + + assertEquals("Only values accepted as Boolean are + and -", output); + } + + @Test + void whenAllBooleanFieldsValid_thenCorrectResponse() throws Exception { + String postBody = "{\"boolField\":true,\"trueField\":true,\"falseField\":false,\"boolStringVar\":\"+\"}"; + + String output = mockMvc.perform(post("/validateBoolean").contentType("application/json") + .content(postBody)) + .andReturn() + .getResponse() + .getContentAsString(); + + assertEquals("BooleanObject is valid", output); + } + + @Test + void givenAllBooleanFieldsValid_whenServiceValidationFails_thenErrorResponse() throws Exception { + mockMvc.perform(post("/validateBooleanAtService").contentType("application/json")) + .andExpect(status().isInternalServerError()); + } + + @Test + void whenNullInputForTrueBooleanField_thenCorrectResponse() throws Exception { + String postBody = "{\"boolField\":true,\"trueField\":null,\"falseField\":false,\"boolStringVar\":\"+\"}"; + + mockMvc.perform(post("/validateBoolean").contentType("application/json") + .content(postBody)) + .andExpect(status().isOk()); + } + + @Test + void whenNullInputForFalseBooleanField_thenHttpBadRequestAsHttpResponse() throws Exception { + String postBody = "{\"boolField\":true,\"trueField\":true,\"falseField\":null,\"boolStringVar\":\"+\"}"; + + String output = mockMvc.perform(post("/validateBoolean").contentType("application/json") + .content(postBody)) + .andReturn() + .getResponse() + .getContentAsString(); + + assertEquals("falseField cannot be null", output); + } +} diff --git a/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/dto/BooleanUnitTest.java b/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/dto/BooleanUnitTest.java new file mode 100644 index 0000000000..9ab04794c6 --- /dev/null +++ b/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/dto/BooleanUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.dto; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class BooleanUnitTest { + + @Test + void givenInputAsString_whenStringToBoolean_thenValidBooleanConversion() { + assertEquals(Boolean.TRUE, Boolean.valueOf("TRUE")); + assertEquals(Boolean.FALSE, Boolean.valueOf("false")); + assertEquals(Boolean.TRUE, Boolean.parseBoolean("True")); + } + + @Test + void givenInputAsboolean_whenbooleanToBoolean_thenValidBooleanConversion() { + assertEquals(Boolean.TRUE, Boolean.valueOf(true)); + assertEquals(Boolean.FALSE, Boolean.valueOf(false)); + } +} diff --git a/spring-cloud-modules/pom.xml b/spring-cloud-modules/pom.xml index a098bc90a9..729dd8eaf1 100644 --- a/spring-cloud-modules/pom.xml +++ b/spring-cloud-modules/pom.xml @@ -39,7 +39,7 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault - spring-cloud-security + spring-cloud-task spring-cloud-zuul spring-cloud-zuul-fallback diff --git a/spring-cloud-modules/spring-cloud-bus/spring-cloud-bus-server/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-bus/spring-cloud-bus-server/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..6fc9dc1151 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-bus/spring-cloud-bus-server/src/test/resources/logback-test.xml @@ -0,0 +1,15 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + diff --git a/spring-cloud-modules/spring-cloud-functions/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-functions/src/test/resources/logback-test.xml index 8d4771e308..41283752a9 100644 --- a/spring-cloud-modules/spring-cloud-functions/src/test/resources/logback-test.xml +++ b/spring-cloud-modules/spring-cloud-functions/src/test/resources/logback-test.xml @@ -6,6 +6,8 @@ + + diff --git a/spring-cloud-modules/spring-cloud-security/auth-client/src/main/java/com/baeldung/filters/SimpleFilter.java b/spring-cloud-modules/spring-cloud-security/auth-client/src/main/java/com/baeldung/filters/SimpleFilter.java index 98e25ac9c4..4204588428 100644 --- a/spring-cloud-modules/spring-cloud-security/auth-client/src/main/java/com/baeldung/filters/SimpleFilter.java +++ b/spring-cloud-modules/spring-cloud-security/auth-client/src/main/java/com/baeldung/filters/SimpleFilter.java @@ -1,12 +1,13 @@ package com.baeldung.filters; import javax.servlet.http.HttpServletRequest; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.ZuulFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; + public class SimpleFilter extends ZuulFilter { private static Logger log = LoggerFactory.getLogger(SimpleFilter.class); @@ -31,7 +32,8 @@ public class SimpleFilter extends ZuulFilter { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); - log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString())); + log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL() + .toString())); return null; } diff --git a/spring-cloud-modules/spring-cloud-security/auth-resource/pom.xml b/spring-cloud-modules/spring-cloud-security/auth-resource/pom.xml index 9362a71931..b4e29fce49 100644 --- a/spring-cloud-modules/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud-modules/spring-cloud-security/auth-resource/pom.xml @@ -33,6 +33,21 @@ spring-security-jwt ${spring-jwt.version} + + com.sun.xml.bind + jaxb-core + ${jaxb-core.version} + + + javax.xml.bind + jaxb-api + ${jaxb-api.version} + + + com.sun.xml.bind + jaxb-impl + ${jaxb-impl.version} + diff --git a/spring-cloud-modules/spring-cloud-security/auth-server/pom.xml b/spring-cloud-modules/spring-cloud-security/auth-server/pom.xml index 234d9cde78..8c14b8fa74 100644 --- a/spring-cloud-modules/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud-modules/spring-cloud-security/auth-server/pom.xml @@ -35,6 +35,21 @@ org.springframework.security.oauth.boot spring-security-oauth2-autoconfigure + + com.sun.xml.bind + jaxb-core + ${jaxb-core.version} + + + javax.xml.bind + jaxb-api + ${jaxb-api.version} + + + com.sun.xml.bind + jaxb-impl + ${jaxb-impl.version} + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-security/pom.xml b/spring-cloud-modules/spring-cloud-security/pom.xml index ad6421384e..72d1d6cbfc 100644 --- a/spring-cloud-modules/spring-cloud-security/pom.xml +++ b/spring-cloud-modules/spring-cloud-security/pom.xml @@ -34,6 +34,9 @@ 2021.0.3 + 2.3.0.1 + 2.3.1 + 2.3.1 \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/Config.java b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/Config.java new file mode 100644 index 0000000000..ef182c04b6 --- /dev/null +++ b/spring-exceptions/src/main/java/com/baeldung/ex/beancreationexception/cause9/Config.java @@ -0,0 +1,19 @@ +package com.baeldung.ex.beancreationexception.cause9; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class Config { + + @Autowired + BeanFactory beanFactory; + + @Bean + public BeanB beanB() { + beanFactory.getBean("beanA"); + return new BeanB(); + } +} diff --git a/spring-kafka-2/src/main/resources/application.properties b/spring-kafka-2/src/main/resources/application.properties index 4725ace2d9..ed844cadf8 100644 --- a/spring-kafka-2/src/main/resources/application.properties +++ b/spring-kafka-2/src/main/resources/application.properties @@ -1,4 +1,4 @@ -spring.kafka.bootstrap-servers=localhost:9092 +spring.kafka.bootstrap-servers=localhost:9092,localhost:9093,localhost:9094 message.topic.name=baeldung long.message.topic.name=longMessage greeting.topic.name=greeting diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/multiplelisteners/KafkaMultipleListenersIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/multiplelisteners/KafkaMultipleListenersIntegrationTest.java index b6634ec7ed..9dfebb104e 100644 --- a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/multiplelisteners/KafkaMultipleListenersIntegrationTest.java +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/multiplelisteners/KafkaMultipleListenersIntegrationTest.java @@ -19,7 +19,7 @@ import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; import org.springframework.kafka.test.context.EmbeddedKafka; @SpringBootTest(classes = MultipleListenersApplicationKafkaApp.class) -@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" }) +@EmbeddedKafka(partitions = 1, controlledShutdown = true, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" }) class KafkaMultipleListenersIntegrationTest { @Autowired diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/retryable/KafkaRetryableIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/retryable/KafkaRetryableIntegrationTest.java index 52cda85f90..daec8232bf 100644 --- a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/retryable/KafkaRetryableIntegrationTest.java +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/retryable/KafkaRetryableIntegrationTest.java @@ -22,7 +22,7 @@ import com.baeldung.spring.kafka.retryable.RetryableApplicationKafkaApp; import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootTest(classes = RetryableApplicationKafkaApp.class) -@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" }) +@EmbeddedKafka(partitions = 1, controlledShutdown = true, brokerProperties = { "listeners=PLAINTEXT://localhost:9093", "port=9093" }) public class KafkaRetryableIntegrationTest { @ClassRule public static EmbeddedKafkaBroker embeddedKafka = new EmbeddedKafkaBroker(1, true, "multitype"); diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/topicsandpartitions/KafkaTopicsAndPartitionsIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/topicsandpartitions/KafkaTopicsAndPartitionsIntegrationTest.java index de720ef955..4413239c78 100644 --- a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/topicsandpartitions/KafkaTopicsAndPartitionsIntegrationTest.java +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/topicsandpartitions/KafkaTopicsAndPartitionsIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.kafka.test.EmbeddedKafkaBroker; import org.springframework.kafka.test.context.EmbeddedKafka; @SpringBootTest(classes = ThermostatApplicationKafkaApp.class) -@EmbeddedKafka(partitions = 2, brokerProperties = {"listeners=PLAINTEXT://localhost:9092", "port=9092"}) +@EmbeddedKafka(partitions = 2, controlledShutdown = true, brokerProperties = {"listeners=PLAINTEXT://localhost:9094", "port=9094"}) public class KafkaTopicsAndPartitionsIntegrationTest { @ClassRule public static EmbeddedKafkaBroker embeddedKafka = new EmbeddedKafkaBroker(1, true, "multitype"); diff --git a/spring-reactive-modules/pom.xml b/spring-reactive-modules/pom.xml index 06519d723a..61a3c3d17d 100644 --- a/spring-reactive-modules/pom.xml +++ b/spring-reactive-modules/pom.xml @@ -18,8 +18,6 @@ spring-reactive-data - spring-reactive-data-2 - spring-5-reactive spring-reactive-2 spring-reactive-3 spring-reactive-client @@ -27,7 +25,7 @@ spring-reactive-filters spring-reactive-oauth spring-reactive-security - spring-data-couchbase + spring-reactive-data-couchbase spring-reactive spring-reactive-exceptions spring-reactor @@ -64,7 +62,4 @@ - - - \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive/.gitignore b/spring-reactive-modules/spring-5-reactive/.gitignore deleted file mode 100644 index dec013dfa4..0000000000 --- a/spring-reactive-modules/spring-5-reactive/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -#folders# -.idea -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive/README.md b/spring-reactive-modules/spring-5-reactive/README.md deleted file mode 100644 index 3f44267234..0000000000 --- a/spring-reactive-modules/spring-5-reactive/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Spring 5 Reactive Project - -This module contains articles about reactive Spring Boot - -### The Course -The "REST With Spring" Classes: https://bit.ly/restwithspring - -### Relevant Articles - -- [Exploring the Spring 5 WebFlux URL Matching](https://www.baeldung.com/spring-5-mvc-url-matching) -- [Reactive WebSockets with Spring 5](https://www.baeldung.com/spring-5-reactive-websockets) -- [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header) -- [A Guide to Spring Session Reactive Support: WebSession](https://www.baeldung.com/spring-session-reactive) -- More articles: [[next -->]](../spring-5-reactive-2) \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive/pom.xml b/spring-reactive-modules/spring-5-reactive/pom.xml deleted file mode 100644 index da04f2c0ca..0000000000 --- a/spring-reactive-modules/spring-5-reactive/pom.xml +++ /dev/null @@ -1,165 +0,0 @@ - - 4.0.0 - spring-5-reactive - 0.0.1-SNAPSHOT - spring-5-reactive - jar - spring 5 sample project about new features - - - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-integration - - - org.springframework.boot - spring-boot-starter-websocket - - - javax.json.bind - javax.json.bind-api - - - org.projectlombok - lombok - compile - - - org.apache.geronimo.specs - geronimo-json_1.1_spec - ${geronimo-json_1.1_spec.version} - - - org.apache.johnzon - johnzon-jsonb - - - - org.apache.commons - commons-lang3 - - - - org.springframework.boot - spring-boot-devtools - runtime - - - org.springframework - spring-test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - io.projectreactor - reactor-test - test - - - - org.springframework.boot - spring-boot-starter-webflux - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.session - spring-session-core - - - org.springframework.session - spring-session-data-redis - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - test - - - io.reactivex.rxjava2 - rxjava - - - org.apache.httpcomponents - httpclient - - - io.netty - netty-all - - - - - - - maven-resources-plugin - ${maven-resources-plugin.version} - - - copy-resources - validate - - copy-resources - - - - - src/main/assets - true - - - ${basedir}/target/classes/assets - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.reactive.Spring5ReactiveApplication - JAR - - - - - - - 1.1.3 - 1.0 - 1.0 - 3.0.1 - - - \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive/src/main/assets/index.html b/spring-reactive-modules/spring-5-reactive/src/main/assets/index.html deleted file mode 100644 index 047514df1c..0000000000 --- a/spring-reactive-modules/spring-5-reactive/src/main/assets/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - Baeldung: Static Content in Spring WebFlux - - -Example Spring Web Flux and web resources configuration - - \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java b/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java deleted file mode 100644 index 61927e47ab..0000000000 --- a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.websession.configuration; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; -import org.springframework.security.config.web.server.ServerHttpSecurity; -import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.server.SecurityWebFilterChain; -import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository; - -@Configuration -@EnableWebFluxSecurity -public class WebFluxSecurityConfig { - - @Bean - public MapReactiveUserDetailsService userDetailsService() { - UserDetails admin = User - .withUsername("admin") - .password(encoder().encode("password")) - .roles("ADMIN") - .build(); - - UserDetails user = User - .withUsername("user") - .password(encoder().encode("password")) - .roles("USER") - .build(); - - return new MapReactiveUserDetailsService(admin, user); - } - - @Bean - public SecurityWebFilterChain webSessionSpringSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange().authenticated() - .and() - .httpBasic() - .securityContextRepository(new WebSessionServerSecurityContextRepository()) - .and() - .formLogin(); - - http.csrf().disable(); - - return http.build(); - - } - - @Bean - public PasswordEncoder encoder() { - return new BCryptPasswordEncoder(); - } -} diff --git a/spring-reactive-modules/spring-5-reactive/src/main/resources/application.properties b/spring-reactive-modules/spring-5-reactive/src/main/resources/application.properties deleted file mode 100644 index dfe4a4d994..0000000000 --- a/spring-reactive-modules/spring-5-reactive/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -logging.level.root=INFO -server.tomcat.max-keep-alive-requests=1 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-2/README.md b/spring-reactive-modules/spring-reactive-2/README.md index a5df5187bf..dbaebc370e 100644 --- a/spring-reactive-modules/spring-reactive-2/README.md +++ b/spring-reactive-modules/spring-reactive-2/README.md @@ -7,4 +7,6 @@ This module contains articles about reactive Spring Boot. - [Static Content in Spring WebFlux](https://www.baeldung.com/spring-webflux-static-content) - [Server-Sent Events in Spring](https://www.baeldung.com/spring-server-sent-events) - [Backpressure Mechanism in Spring WebFlux](https://www.baeldung.com/spring-webflux-backpressure) -- More articles: [[<-- prev]](../spring-5-reactive) [[next -->]](../spring-5-reactive-3) +- [Exploring the Spring 5 WebFlux URL Matching](https://www.baeldung.com/spring-5-mvc-url-matching) +- [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header) +- More articles: [[<-- prev]](../spring-reactive) [[next -->]](../spring-reactive-3) diff --git a/spring-reactive-modules/spring-reactive-2/pom.xml b/spring-reactive-modules/spring-reactive-2/pom.xml index ba40f3b48a..13970851cd 100644 --- a/spring-reactive-modules/spring-reactive-2/pom.xml +++ b/spring-reactive-modules/spring-reactive-2/pom.xml @@ -59,6 +59,10 @@ spring-security-test test + + org.springframework.boot + spring-boot-starter-tomcat + diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/FooReactiveController.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/controller/FooReactiveController.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/FooReactiveController.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/controller/FooReactiveController.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/PathPatternController.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/controller/PathPatternController.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/PathPatternController.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/controller/PathPatternController.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Foo.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/model/Foo.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Foo.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/model/Foo.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/controllers/ResponseHeaderController.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/responseheaders/controllers/ResponseHeaderController.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/controllers/ResponseHeaderController.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/responseheaders/controllers/ResponseHeaderController.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/filter/AddResponseHeaderWebFilter.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/responseheaders/filter/AddResponseHeaderWebFilter.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/filter/AddResponseHeaderWebFilter.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/responseheaders/filter/AddResponseHeaderWebFilter.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/handlers/ResponseHeaderHandler.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/responseheaders/functional/handlers/ResponseHeaderHandler.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/handlers/ResponseHeaderHandler.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/responseheaders/functional/handlers/ResponseHeaderHandler.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/routers/ResponseHeadersRouterFunctions.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/responseheaders/functional/routers/ResponseHeadersRouterFunctions.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/routers/ResponseHeadersRouterFunctions.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/responseheaders/functional/routers/ResponseHeadersRouterFunctions.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/Actor.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/Actor.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/Actor.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/Actor.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java similarity index 98% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java index b7bb53600e..6007597220 100644 --- a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java @@ -32,7 +32,7 @@ public class ExploreSpring5URLPatternUsingRouterFunctions { .and(RouterFunctions.resources("/resources/**", new ClassPathResource("resources/"))); } - WebServer start() throws Exception { + WebServer start() { WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) .filter(new IndexRewriteFilter()) diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/resources/files/hello.txt b/spring-reactive-modules/spring-reactive-2/src/main/resources/files/hello.txt similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/resources/files/hello.txt rename to spring-reactive-modules/spring-reactive-2/src/main/resources/files/hello.txt diff --git a/spring-reactive-modules/spring-5-reactive/src/main/resources/files/test/test.txt b/spring-reactive-modules/spring-reactive-2/src/main/resources/files/test/test.txt similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/resources/files/test/test.txt rename to spring-reactive-modules/spring-reactive-2/src/main/resources/files/test/test.txt diff --git a/spring-reactive-modules/spring-5-reactive/src/main/resources/resources/test/test.txt b/spring-reactive-modules/spring-reactive-2/src/main/resources/resources/test/test.txt similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/resources/resources/test/test.txt rename to spring-reactive-modules/spring-reactive-2/src/main/resources/resources/test/test.txt diff --git a/spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/FluxUnitTest.java b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/FluxUnitTest.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/FluxUnitTest.java rename to spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/FluxUnitTest.java diff --git a/spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java rename to spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java diff --git a/spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java rename to spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java diff --git a/spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java rename to spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java diff --git a/spring-reactive-modules/spring-reactive-3/README.md b/spring-reactive-modules/spring-reactive-3/README.md index 640a60d63d..4dbaa93226 100644 --- a/spring-reactive-modules/spring-reactive-3/README.md +++ b/spring-reactive-modules/spring-reactive-3/README.md @@ -5,4 +5,7 @@ This module contains articles about reactive Spring Boot. - [Logging a Reactive Sequence](https://www.baeldung.com/spring-reactive-sequence-logging) - [Reading Flux Into a Single InputStream Using Spring Reactive WebClient](https://www.baeldung.com/spring-reactive-read-flux-into-inputstream) - [Cancel an Ongoing Flux in Spring WebFlux](https://www.baeldung.com/spring-webflux-cancel-flux) -- More articles: [[<-- prev]](../spring-5-reactive-2) +- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators) +- [Reactive WebSockets with Spring 5](https://www.baeldung.com/spring-5-reactive-websockets) +- [A Guide to Spring Session Reactive Support: WebSession](https://www.baeldung.com/spring-session-reactive) +- More articles: [[<-- prev]](../spring-reactive-2) diff --git a/spring-reactive-modules/spring-reactive-3/pom.xml b/spring-reactive-modules/spring-reactive-3/pom.xml index 7672fa29f3..96f23f1339 100644 --- a/spring-reactive-modules/spring-reactive-3/pom.xml +++ b/spring-reactive-modules/spring-reactive-3/pom.xml @@ -47,6 +47,22 @@ org.projectlombok lombok + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-websocket + + + org.springframework.session + spring-session-core + + + org.springframework.session + spring-session-data-redis + diff --git a/spring-reactive-modules/spring-5-reactive/src/main/WEB-INF/web.xml b/spring-reactive-modules/spring-reactive-3/src/main/WEB-INF/web.xml similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/WEB-INF/web.xml rename to spring-reactive-modules/spring-reactive-3/src/main/WEB-INF/web.xml diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/Actor.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/Actor.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/Actor.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/Actor.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/FormHandler.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/FormHandler.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/FunctionalWebApplication.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/FunctionalWebApplication.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/IndexRewriteFilter.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/IndexRewriteFilter.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/IndexRewriteFilter.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/IndexRewriteFilter.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/RootServlet.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/functional/RootServlet.java diff --git a/spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java similarity index 100% rename from spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java diff --git a/spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java similarity index 100% rename from spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java diff --git a/spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java similarity index 100% rename from spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java diff --git a/spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java similarity index 73% rename from spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java index 600bff5948..19b83ee651 100644 --- a/spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java +++ b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java @@ -2,8 +2,10 @@ package com.baeldung.reactive.actuator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; @SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.reactive.actuator") public class Spring5ReactiveApplication { public static void main(String[] args) { diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/Application.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/Application.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/Application.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/Application.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/RedisConfig.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/configuration/RedisConfig.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/RedisConfig.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/configuration/RedisConfig.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/SessionConfig.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/configuration/SessionConfig.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/SessionConfig.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/configuration/SessionConfig.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxConfig.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/configuration/WebFluxConfig.java similarity index 89% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxConfig.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/configuration/WebFluxConfig.java index 964b544916..041c37e7fc 100644 --- a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxConfig.java +++ b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/configuration/WebFluxConfig.java @@ -4,7 +4,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.config.EnableWebFlux; -import org.springframework.web.reactive.config.ResourceHandlerRegistry; import org.springframework.web.reactive.config.WebFluxConfigurer; @Configuration diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/controller/SessionController.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/controller/SessionController.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/controller/SessionController.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/controller/SessionController.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/transfer/CustomResponse.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/transfer/CustomResponse.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websession/transfer/CustomResponse.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websession/transfer/CustomResponse.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/Event.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/Event.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/Event.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/Event.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/WebSocketController.java b/spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/WebSocketController.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/websocket/WebSocketController.java rename to spring-reactive-modules/spring-reactive-3/src/main/java/com/baeldung/websocket/WebSocketController.java diff --git a/spring-reactive-modules/spring-reactive-3/src/main/resources/application.properties b/spring-reactive-modules/spring-reactive-3/src/main/resources/application.properties index 815cc2b76d..767f8106dd 100644 --- a/spring-reactive-modules/spring-reactive-3/src/main/resources/application.properties +++ b/spring-reactive-modules/spring-reactive-3/src/main/resources/application.properties @@ -1 +1,13 @@ -# application properties \ No newline at end of file +# application properties +management.endpoints.web.exposure.include=* + +info.app.name=Spring Boot 2 actuator Application +management.endpoint.health.group.custom.include=diskSpace,ping +management.endpoint.health.group.custom.show-components=always +management.endpoint.health.group.custom.show-details=always +management.endpoint.health.group.custom.status.http-mapping.up=207 + +spring.main.allow-bean-definition-overriding=true + +logging.level.root=INFO +server.tomcat.max-keep-alive-requests=1 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-3/src/main/resources/files/hello.txt b/spring-reactive-modules/spring-reactive-3/src/main/resources/files/hello.txt new file mode 100644 index 0000000000..b6fc4c620b --- /dev/null +++ b/spring-reactive-modules/spring-reactive-3/src/main/resources/files/hello.txt @@ -0,0 +1 @@ +hello \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive/src/main/resources/logback.xml b/spring-reactive-modules/spring-reactive-3/src/main/resources/logback.xml similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/resources/logback.xml rename to spring-reactive-modules/spring-reactive-3/src/main/resources/logback.xml diff --git a/spring-reactive-modules/spring-5-reactive/src/main/resources/static/client-websocket.html b/spring-reactive-modules/spring-reactive-3/src/main/resources/static/client-websocket.html similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/resources/static/client-websocket.html rename to spring-reactive-modules/spring-reactive-3/src/main/resources/static/client-websocket.html diff --git a/spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/SpringContextTest.java b/spring-reactive-modules/spring-reactive-3/src/test/java/com/baeldung/SpringContextTest.java similarity index 75% rename from spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/SpringContextTest.java rename to spring-reactive-modules/spring-reactive-3/src/test/java/com/baeldung/SpringContextTest.java index bedb30fcaa..2dbd45349f 100644 --- a/spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-reactive-modules/spring-reactive-3/src/test/java/com/baeldung/SpringContextTest.java @@ -5,10 +5,10 @@ import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.functional.FunctionalWebApplication; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5ReactiveApplication.class) +@SpringBootTest(classes = FunctionalWebApplication.class) public class SpringContextTest { @Test diff --git a/spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-reactive-modules/spring-reactive-3/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java rename to spring-reactive-modules/spring-reactive-3/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java diff --git a/spring-reactive-modules/spring-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java b/spring-reactive-modules/spring-reactive-3/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java similarity index 87% rename from spring-reactive-modules/spring-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java rename to spring-reactive-modules/spring-reactive-3/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java index 94979a18ca..79c694e6b9 100644 --- a/spring-reactive-modules/spring-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java +++ b/spring-reactive-modules/spring-reactive-3/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java @@ -9,8 +9,6 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import java.io.IOException; - import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @@ -21,13 +19,13 @@ public class ActuatorInfoIntegrationTest { private TestRestTemplate restTemplate; @Test - public void whenGetInfo_thenReturns200() throws IOException { + public void whenGetInfo_thenReturns200() { final ResponseEntity responseEntity = this.restTemplate.getForEntity("/actuator/info", String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); } @Test - public void whenFeatures_thenReturns200() throws IOException { + public void whenFeatures_thenReturns200() { final ResponseEntity responseEntity = this.restTemplate.getForEntity("/actuator/features", String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); } diff --git a/spring-reactive-modules/spring-5-reactive/src/test/resources/baeldung-weekly.png b/spring-reactive-modules/spring-reactive-3/src/test/resources/baeldung-weekly.png similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/test/resources/baeldung-weekly.png rename to spring-reactive-modules/spring-reactive-3/src/test/resources/baeldung-weekly.png diff --git a/spring-reactive-modules/spring-reactive-client-2/README.md b/spring-reactive-modules/spring-reactive-client-2/README.md index 04fe3c8f42..6b6a480f46 100644 --- a/spring-reactive-modules/spring-reactive-client-2/README.md +++ b/spring-reactive-modules/spring-reactive-client-2/README.md @@ -8,4 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - [Limiting the Requests per Second With WebClient](https://www.baeldung.com/spring-webclient-limit-requests-per-second) - [Stream Large Byte[] to File With WebClient](https://www.baeldung.com/webclient-stream-large-byte-array-to-file) -- More articles: [[<-- prev]](../spring-5-reactive-client) +- More articles: [[<-- prev]](../spring-reactive-client) diff --git a/spring-reactive-modules/spring-reactive-client/README.md b/spring-reactive-modules/spring-reactive-client/README.md index fc67a4f16e..ae72dc0e4a 100644 --- a/spring-reactive-modules/spring-reactive-client/README.md +++ b/spring-reactive-modules/spring-reactive-client/README.md @@ -13,4 +13,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Upload a File with WebClient](https://www.baeldung.com/spring-webclient-upload-file) - [How to Get Response Body When Testing the Status Code in WebFlux WebClient](https://www.baeldung.com/spring-webclient-get-response-body) - [Spring Boot FeignClient vs. WebClient](https://www.baeldung.com/spring-boot-feignclient-vs-webclient) -- More articles: [[next -->]](../spring-5-reactive-client-2) +- More articles: [[next -->]](../spring-reactive-client-2) diff --git a/spring-reactive-modules/spring-reactive-data-2/README.md b/spring-reactive-modules/spring-reactive-data-2/README.md deleted file mode 100644 index c13171cbc6..0000000000 --- a/spring-reactive-modules/spring-reactive-data-2/README.md +++ /dev/null @@ -1,10 +0,0 @@ -## Spring Data Reactive Project - -This module contains articles about reactive Spring Boot Data - -### The Course - -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles -- [Pagination in Spring Webflux and Spring Data Reactive](https://www.baeldung.com/spring-data-webflux-pagination) diff --git a/spring-reactive-modules/spring-reactive-data-2/pom.xml b/spring-reactive-modules/spring-reactive-data-2/pom.xml deleted file mode 100644 index 47662a2c2e..0000000000 --- a/spring-reactive-modules/spring-reactive-data-2/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - spring-reactive-data-2 - spring-reactive-data-2 - jar - - - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-webflux - - - org.springframework.boot - spring-boot-starter-data-r2dbc - - - org.springframework - spring-webflux - - - org.springframework.boot - spring-boot-starter-test - test - - - com.h2database - h2 - runtime - - - io.r2dbc - r2dbc-h2 - runtime - - - org.projectlombok - lombok - true - - - io.projectreactor - reactor-test - test - - - javax.validation - validation-api - ${validation-api.version} - - - - - - 2.0.1.Final - UTF-8 - - - \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-data-2/src/main/resources/application.properties b/spring-reactive-modules/spring-reactive-data-2/src/main/resources/application.properties deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-reactive-modules/spring-data-couchbase/README.md b/spring-reactive-modules/spring-reactive-data-couchbase/README.md similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/README.md rename to spring-reactive-modules/spring-reactive-data-couchbase/README.md diff --git a/spring-reactive-modules/spring-data-couchbase/pom.xml b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml similarity index 98% rename from spring-reactive-modules/spring-data-couchbase/pom.xml rename to spring-reactive-modules/spring-reactive-data-couchbase/pom.xml index d7b36f97fa..52b10f39d9 100644 --- a/spring-reactive-modules/spring-data-couchbase/pom.xml +++ b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml @@ -3,7 +3,7 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-data-couchbase + spring-reactive-data-couchbase spring-data-couchbase jar diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/ReactiveCouchbaseApplication.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/ReactiveCouchbaseApplication.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/ReactiveCouchbaseApplication.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/ReactiveCouchbaseApplication.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/CouchbaseProperties.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/CouchbaseProperties.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/CouchbaseProperties.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/CouchbaseProperties.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/N1QLReactiveCouchbaseConfiguration.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/N1QLReactiveCouchbaseConfiguration.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/N1QLReactiveCouchbaseConfiguration.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/N1QLReactiveCouchbaseConfiguration.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/ReactiveCouchbaseConfiguration.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/ReactiveCouchbaseConfiguration.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/ReactiveCouchbaseConfiguration.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/ReactiveCouchbaseConfiguration.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/ViewReactiveCouchbaseConfiguration.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/ViewReactiveCouchbaseConfiguration.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/ViewReactiveCouchbaseConfiguration.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/configuration/ViewReactiveCouchbaseConfiguration.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/domain/Person.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/domain/Person.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/domain/Person.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/domain/Person.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepository.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepository.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepository.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepository.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepository.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepository.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepository.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepository.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepository.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepository.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepository.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepository.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/resources/couchbase.properties b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/resources/couchbase.properties similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/resources/couchbase.properties rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/resources/couchbase.properties diff --git a/spring-reactive-modules/spring-data-couchbase/src/main/resources/logback.xml b/spring-reactive-modules/spring-reactive-data-couchbase/src/main/resources/logback.xml similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/main/resources/logback.xml rename to spring-reactive-modules/spring-reactive-data-couchbase/src/main/resources/logback.xml diff --git a/spring-reactive-modules/spring-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/CouchbaseMockConfiguration.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/CouchbaseMockConfiguration.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/CouchbaseMockConfiguration.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/CouchbaseMockConfiguration.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepositoryLiveTest.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepositoryLiveTest.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepositoryLiveTest.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepositoryLiveTest.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepositoryLiveTest.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepositoryLiveTest.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepositoryLiveTest.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepositoryLiveTest.java diff --git a/spring-reactive-modules/spring-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepositoryIntegrationTest.java b/spring-reactive-modules/spring-reactive-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepositoryIntegrationTest.java similarity index 100% rename from spring-reactive-modules/spring-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepositoryIntegrationTest.java rename to spring-reactive-modules/spring-reactive-data-couchbase/src/test/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepositoryIntegrationTest.java diff --git a/spring-reactive-modules/spring-reactive-data/README.md b/spring-reactive-modules/spring-reactive-data/README.md index cafd0c502f..259ab0be62 100644 --- a/spring-reactive-modules/spring-reactive-data/README.md +++ b/spring-reactive-modules/spring-reactive-data/README.md @@ -3,7 +3,9 @@ This module contains articles about reactive Spring Boot Data ### The Course + The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles -- [A Quick Look at R2DBC with Spring Data](https://www.baeldung.com/spring-data-r2dbc) \ No newline at end of file +- [A Quick Look at R2DBC with Spring Data](https://www.baeldung.com/spring-data-r2dbc) +- [Pagination in Spring Webflux and Spring Data Reactive](https://www.baeldung.com/spring-data-webflux-pagination) diff --git a/spring-reactive-modules/spring-reactive-data/pom.xml b/spring-reactive-modules/spring-reactive-data/pom.xml index 91c4dca6e8..03ea440b4f 100644 --- a/spring-reactive-modules/spring-reactive-data/pom.xml +++ b/spring-reactive-modules/spring-reactive-data/pom.xml @@ -1,10 +1,10 @@ - 4.0.0 spring-reactive-data - spring-reactive-data + spring-reactive-data-2 jar @@ -13,17 +13,9 @@ 1.0.0-SNAPSHOT - - - - org.apache.logging.log4j - log4j-bom - ${log4j2.version} - import - pom - - - + + UTF-8 + @@ -31,13 +23,16 @@ spring-boot-starter-web - org.projectlombok - lombok + org.springframework.boot + spring-boot-starter-webflux - io.projectreactor - reactor-test - test + org.springframework.boot + spring-boot-starter-data-r2dbc + + + org.springframework + spring-webflux org.springframework.boot @@ -45,12 +40,29 @@ test - org.springframework.boot - spring-boot-starter-webflux + com.h2database + h2 + runtime - org.springframework.data - spring-data-r2dbc + io.r2dbc + r2dbc-h2 + runtime + + + org.projectlombok + lombok + true + + + io.projectreactor + reactor-test + test + + + javax.validation + validation-api + 2.0.1.Final io.r2dbc @@ -58,17 +70,4 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - 2.17.1 - - \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/PaginationApplication.java b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/PaginationApplication.java similarity index 100% rename from spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/PaginationApplication.java rename to spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/PaginationApplication.java diff --git a/spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/config/CustomWebMvcConfigurationSupport.java b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/config/CustomWebMvcConfigurationSupport.java similarity index 100% rename from spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/config/CustomWebMvcConfigurationSupport.java rename to spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/config/CustomWebMvcConfigurationSupport.java diff --git a/spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/config/DatabaseConfig.java b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/config/DatabaseConfig.java similarity index 100% rename from spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/config/DatabaseConfig.java rename to spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/config/DatabaseConfig.java diff --git a/spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/controller/ProductPaginationController.java b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/controller/ProductPaginationController.java similarity index 100% rename from spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/controller/ProductPaginationController.java rename to spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/controller/ProductPaginationController.java diff --git a/spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/model/Product.java b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/model/Product.java similarity index 100% rename from spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/model/Product.java rename to spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/model/Product.java diff --git a/spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/repository/ProductRepository.java b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/repository/ProductRepository.java similarity index 100% rename from spring-reactive-modules/spring-reactive-data-2/src/main/java/com/baeldung/pagination/repository/ProductRepository.java rename to spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/repository/ProductRepository.java diff --git a/spring-reactive-modules/spring-reactive-data-2/src/main/resources/init.sql b/spring-reactive-modules/spring-reactive-data/src/main/resources/init.sql similarity index 100% rename from spring-reactive-modules/spring-reactive-data-2/src/main/resources/init.sql rename to spring-reactive-modules/spring-reactive-data/src/main/resources/init.sql diff --git a/spring-reactive-modules/spring-reactive-data-2/src/test/java/com/baeldung/pagination/controller/ProductPaginationControllerIntegrationTest.java b/spring-reactive-modules/spring-reactive-data/src/test/java/com/baeldung/pagination/controller/ProductPaginationControllerIntegrationTest.java similarity index 100% rename from spring-reactive-modules/spring-reactive-data-2/src/test/java/com/baeldung/pagination/controller/ProductPaginationControllerIntegrationTest.java rename to spring-reactive-modules/spring-reactive-data/src/test/java/com/baeldung/pagination/controller/ProductPaginationControllerIntegrationTest.java diff --git a/spring-reactive-modules/spring-reactive-data/src/test/java/com/baeldung/SpringContextTest.java b/spring-reactive-modules/spring-reactive-data/src/test/java/com/baeldung/r2dbc/SpringContextTest.java similarity index 85% rename from spring-reactive-modules/spring-reactive-data/src/test/java/com/baeldung/SpringContextTest.java rename to spring-reactive-modules/spring-reactive-data/src/test/java/com/baeldung/r2dbc/SpringContextTest.java index dc7bcd1e37..facefd3144 100644 --- a/spring-reactive-modules/spring-reactive-data/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-reactive-modules/spring-reactive-data/src/test/java/com/baeldung/r2dbc/SpringContextTest.java @@ -1,12 +1,10 @@ -package com.baeldung; +package com.baeldung.r2dbc; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.r2dbc.R2dbcApplication; - @RunWith(SpringRunner.class) @SpringBootTest(classes = R2dbcApplication.class) public class SpringContextTest { diff --git a/spring-reactive-modules/spring-reactive-security/README.md b/spring-reactive-modules/spring-reactive-security/README.md index 37f999648c..a25fa3728b 100644 --- a/spring-reactive-modules/spring-reactive-security/README.md +++ b/spring-reactive-modules/spring-reactive-security/README.md @@ -7,6 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles -- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators) - [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) - [Spring Webflux and CORS](https://www.baeldung.com/spring-webflux-cors) diff --git a/spring-reactive-modules/spring-reactive-security/pom.xml b/spring-reactive-modules/spring-reactive-security/pom.xml index 956153b49a..cf34b21083 100644 --- a/spring-reactive-modules/spring-reactive-security/pom.xml +++ b/spring-reactive-modules/spring-reactive-security/pom.xml @@ -37,10 +37,6 @@ javax.json.bind javax.json.bind-api - - org.springframework.boot - spring-boot-starter-actuator - org.projectlombok lombok diff --git a/spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java b/spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java deleted file mode 100644 index 384e26ac8c..0000000000 --- a/spring-reactive-modules/spring-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.reactive.actuator; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; -import org.springframework.security.config.web.server.ServerHttpSecurity; -import org.springframework.security.web.server.SecurityWebFilterChain; - -@Configuration -@EnableWebFluxSecurity -public class WebSecurityConfig { - - @Bean - public SecurityWebFilterChain securitygWebFilterChain( - ServerHttpSecurity http) { - - return http.authorizeExchange() - .pathMatchers("/actuator/**").permitAll() - .anyExchange().authenticated() - .and().build(); - } - -} diff --git a/spring-reactive-modules/spring-reactive-security/src/test/java/com/baeldung/SpringContextTest.java b/spring-reactive-modules/spring-reactive-security/src/test/java/com/baeldung/SpringContextTest.java index e6123de118..a0a7d9264a 100644 --- a/spring-reactive-modules/spring-reactive-security/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-reactive-modules/spring-reactive-security/src/test/java/com/baeldung/SpringContextTest.java @@ -1,13 +1,14 @@ package com.baeldung; -import com.baeldung.reactive.actuator.Spring5ReactiveApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.webflux.EmployeeWebSocketClient; + @RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5ReactiveApplication.class) +@SpringBootTest(classes = EmployeeWebSocketClient.class) public class SpringContextTest { @Test diff --git a/spring-scheduling/pom.xml b/spring-scheduling/pom.xml index 9010338fee..e374b2b890 100644 --- a/spring-scheduling/pom.xml +++ b/spring-scheduling/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -33,21 +33,19 @@ org.springframework.boot spring-boot-starter-web - - javax.annotation - javax.annotation-api - ${annotation-api.version} - org.springframework spring-test test + + org.apache.commons + commons-lang3 + - 2.0.0 - 1.3.2 + 2.0.3 \ No newline at end of file diff --git a/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/DynamicSchedulingConfig.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/DynamicSchedulingConfig.java index b29f9ab0ce..7b7c18f507 100644 --- a/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/DynamicSchedulingConfig.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/DynamicSchedulingConfig.java @@ -37,7 +37,7 @@ public class DynamicSchedulingConfig implements SchedulingConfigurer { Instant nextExecutionTime = lastCompletionTime.orElseGet(Date::new).toInstant() .plusMillis(tickService.getDelay()); - return Date.from(nextExecutionTime); + return Date.from(nextExecutionTime).toInstant(); } ); } diff --git a/spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java b/spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java index c0c6f37507..163be62591 100644 --- a/spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java +++ b/spring-scheduling/src/main/java/com/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java @@ -2,7 +2,7 @@ package com.baeldung.taskscheduler; import java.util.Date; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; diff --git a/spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java index a15ca31980..62b1ae908b 100644 --- a/spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,5 @@ package com.baeldung; -import com.baeldung.SampleLDAPApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-oauth2-testing/pom.xml b/spring-security-modules/spring-security-oauth2-testing/pom.xml index 93348cb48c..45fcf9bcce 100644 --- a/spring-security-modules/spring-security-oauth2-testing/pom.xml +++ b/spring-security-modules/spring-security-oauth2-testing/pom.xml @@ -14,7 +14,7 @@ ../../parent-boot-3 - 6.1.0 + 7.1.10 diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/java/com/baeldung/ReactiveResourceServerApplication.java b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/java/com/baeldung/ReactiveResourceServerApplication.java index 500d876bc4..716900ea51 100644 --- a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/java/com/baeldung/ReactiveResourceServerApplication.java +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/java/com/baeldung/ReactiveResourceServerApplication.java @@ -1,7 +1,8 @@ package com.baeldung; +import static org.springframework.security.config.Customizer.withDefaults; + import java.nio.charset.Charset; -import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; @@ -27,6 +28,7 @@ import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.oauth2.core.oidc.StandardClaimNames; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverter; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository; import org.springframework.stereotype.Service; @@ -34,6 +36,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @SpringBootApplication @@ -46,68 +49,66 @@ public class ReactiveResourceServerApplication { @Configuration @EnableWebFluxSecurity @EnableReactiveMethodSecurity - public class SecurityConfig { + static class SecurityConfig { @Bean - SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, Converter>> authoritiesConverter) { - http.oauth2ResourceServer() - .jwt() - .jwtAuthenticationConverter(jwt -> authoritiesConverter.convert(jwt) - .map(authorities -> new JwtAuthenticationToken(jwt, authorities))); - http.securityContextRepository(NoOpServerSecurityContextRepository.getInstance()) - .csrf() - .disable(); - http.exceptionHandling() - .accessDeniedHandler((var exchange, var ex) -> exchange.getPrincipal() - .flatMap(principal -> { + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http.oauth2ResourceServer(resourceServer -> resourceServer.jwt(withDefaults())); + http.securityContextRepository(NoOpServerSecurityContextRepository.getInstance()); + http.csrf(csrf -> csrf.disable()); + http.exceptionHandling(eh -> eh + .accessDeniedHandler((var exchange, var ex) -> exchange.getPrincipal().flatMap(principal -> { final var response = exchange.getResponse(); - response.setStatusCode(principal instanceof AnonymousAuthenticationToken ? HttpStatus.UNAUTHORIZED : HttpStatus.FORBIDDEN); - response.getHeaders() - .setContentType(MediaType.TEXT_PLAIN); + response.setStatusCode( + principal instanceof AnonymousAuthenticationToken ? HttpStatus.UNAUTHORIZED + : HttpStatus.FORBIDDEN); + response.getHeaders().setContentType(MediaType.TEXT_PLAIN); final var dataBufferFactory = response.bufferFactory(); - final var buffer = dataBufferFactory.wrap(ex.getMessage() - .getBytes(Charset.defaultCharset())); + final var buffer = dataBufferFactory.wrap(ex.getMessage().getBytes(Charset.defaultCharset())); return response.writeWith(Mono.just(buffer)) - .doOnError(error -> DataBufferUtils.release(buffer)); - })); + .doOnError(error -> DataBufferUtils.release(buffer)); + }))); - http.authorizeExchange() - .pathMatchers("/secured-route") - .hasRole("AUTHORIZED_PERSONNEL") - .anyExchange() - .authenticated(); + // @formatter:off + http.authorizeExchange(req -> req + .pathMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL").anyExchange() + .authenticated()); + // @formatter:on return http.build(); } - static interface AuthoritiesConverter extends Converter>> { + static interface ReactiveJwtAuthoritiesConverter extends Converter> { } @Bean - AuthoritiesConverter realmRoles2AuthoritiesConverter() { + ReactiveJwtAuthoritiesConverter realmRoles2AuthoritiesConverter() { return (Jwt jwt) -> { - final var realmRoles = Optional.of(jwt.getClaimAsMap("realm_access")) - .orElse(Map.of()); + final var realmRoles = Optional.of(jwt.getClaimAsMap("realm_access")).orElse(Map.of()); @SuppressWarnings("unchecked") final var roles = (List) realmRoles.getOrDefault("roles", List.of()); - return Mono.just(roles.stream() - .map(SimpleGrantedAuthority::new) - .map(GrantedAuthority.class::cast) - .toList()); + return Flux.fromStream(roles.stream()).map(SimpleGrantedAuthority::new) + .map(GrantedAuthority.class::cast); }; } + + @Bean + ReactiveJwtAuthenticationConverter authenticationConverter( + Converter> authoritiesConverter) { + final var authenticationConverter = new ReactiveJwtAuthenticationConverter(); + authenticationConverter.setPrincipalClaimName(StandardClaimNames.PREFERRED_USERNAME); + authenticationConverter.setJwtGrantedAuthoritiesConverter(authoritiesConverter); + return authenticationConverter; + } } @Service public static class MessageService { public Mono greet() { - return ReactiveSecurityContextHolder.getContext() - .map(ctx -> { - final var who = (JwtAuthenticationToken) ctx.getAuthentication(); - final var claims = who.getTokenAttributes(); - return "Hello %s! You are granted with %s.".formatted(claims.getOrDefault(StandardClaimNames.PREFERRED_USERNAME, claims.get(StandardClaimNames.SUB)), who.getAuthorities()); - }) - .switchIfEmpty(Mono.error(new AuthenticationCredentialsNotFoundException("Security context is empty"))); + return ReactiveSecurityContextHolder.getContext().map(ctx -> { + final var who = (JwtAuthenticationToken) ctx.getAuthentication(); + return "Hello %s! You are granted with %s.".formatted(who.getName(), who.getAuthorities()); + }).switchIfEmpty(Mono.error(new AuthenticationCredentialsNotFoundException("Security context is empty"))); } @PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')") @@ -118,26 +119,23 @@ public class ReactiveResourceServerApplication { @RestController @RequiredArgsConstructor - public class GreetingController { + public static class GreetingController { private final MessageService messageService; @GetMapping("/greet") public Mono> greet() { - return messageService.greet() - .map(ResponseEntity::ok); + return messageService.greet().map(ResponseEntity::ok); } @GetMapping("/secured-route") public Mono> securedRoute() { - return messageService.getSecret() - .map(ResponseEntity::ok); + return messageService.getSecret().map(ResponseEntity::ok); } @GetMapping("/secured-method") @PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')") public Mono> securedMethod() { - return messageService.getSecret() - .map(ResponseEntity::ok); + return messageService.getSecret().map(ResponseEntity::ok); } } diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java index 97893bc1fb..c13a20ca38 100644 --- a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java @@ -3,28 +3,49 @@ package com.baeldung; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.util.stream.Stream; + import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; -import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.core.oidc.StandardClaimNames; +import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.baeldung.ReactiveResourceServerApplication.MessageService; -import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; -import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; +import com.baeldung.ReactiveResourceServerApplication.SecurityConfig; +import com.c4_soft.springaddons.security.oauth2.test.AuthenticationFactoriesTestConf; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; +import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; -@Import({ MessageService.class }) +@Import({ MessageService.class, SecurityConfig.class }) +@ImportAutoConfiguration(AuthenticationFactoriesTestConf.class) @ExtendWith(SpringExtension.class) -@EnableReactiveMethodSecurity +@TestInstance(Lifecycle.PER_CLASS) class MessageServiceUnitTest { @Autowired MessageService messageService; + @Autowired + WithJwt.AuthenticationFactory authFactory; + + @MockBean + ReactiveJwtDecoder jwtDecoder; + /*----------------------------------------------------------------------------*/ /* greet() */ /* Expects a JwtAuthenticationToken to be retrieved from the security-context */ @@ -43,10 +64,12 @@ class MessageServiceUnitTest { .block()); } - @Test - @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) - void givenSecurityContextIsPopulatedWithJwtAuthenticationToken_whenGreet_thenReturnGreetingWithPreferredUsernameAndAuthorities() { - assertEquals("Hello ch4mpy! You are granted with [admin, ROLE_AUTHORIZED_PERSONNEL].", messageService.greet() + @ParameterizedTest + @MethodSource("allIdentities") + void givenUserIsAuthenticated_whenGreet_thenReturnGreetingWithPreferredUsernameAndAuthorities(@ParameterizedAuthentication Authentication auth) { + final var jwt = (JwtAuthenticationToken) auth; + final var expected = "Hello %s! You are granted with %s.".formatted(jwt.getTokenAttributes().get(StandardClaimNames.PREFERRED_USERNAME), auth.getAuthorities()); + assertEquals(expected, messageService.greet() .block()); } @@ -70,17 +93,25 @@ class MessageServiceUnitTest { } @Test - @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) - void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenReturnSecret() { + @WithJwt("ch4mpy.json") + void givenUserIsCh4mpy_whenGetSecret_thenReturnSecret() { assertEquals("Only authorized personnel can read that", messageService.getSecret() .block()); } @Test - @WithMockJwtAuth(authorities = { "admin" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) - void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenThrowsAccessDeniedException() { + @WithJwt("tonton-pirate.json") + void givenUserIsTontonPirate_whenGetSecret_thenThrowsAccessDeniedException() { assertThrows(AccessDeniedException.class, () -> messageService.getSecret() .block()); } + /*--------------------------------------------*/ + /* methodSource returning all test identities */ + /*--------------------------------------------*/ + private Stream allIdentities() { + final var authentications = authFactory.authenticationsFrom("ch4mpy.json", "tonton-pirate.json").toList(); + return authentications.stream(); + } + } diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/ReactiveResourceServerApplicationIntegrationTest.java b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/ReactiveResourceServerApplicationIntegrationTest.java index 1ee6fc7e87..d6bfbf4e2d 100644 --- a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/ReactiveResourceServerApplicationIntegrationTest.java +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/ReactiveResourceServerApplicationIntegrationTest.java @@ -8,8 +8,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.test.web.reactive.server.WebTestClient; -import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; -import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureWebTestClient @@ -33,7 +33,7 @@ class ReactiveResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + @WithJwt("ch4mpy.json") void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { api.get() .uri("/greet") @@ -60,7 +60,7 @@ class ReactiveResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + @WithMockAuthentication("ROLE_AUTHORIZED_PERSONNEL") void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { api.get() .uri("/secured-route") @@ -72,7 +72,7 @@ class ReactiveResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth("admin") + @WithMockAuthentication("admin") void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { api.get() .uri("/secured-route") @@ -97,7 +97,7 @@ class ReactiveResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + @WithMockAuthentication("ROLE_AUTHORIZED_PERSONNEL") void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { api.get() .uri("/secured-method") @@ -109,7 +109,7 @@ class ReactiveResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth("admin") + @WithMockAuthentication("admin") void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { api.get() .uri("/secured-method") diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java index 6f55f287d8..f31bbe3ae8 100644 --- a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java @@ -5,16 +5,19 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.core.Authentication; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.test.web.reactive.server.WebTestClient; import com.baeldung.ReactiveResourceServerApplication.GreetingController; import com.baeldung.ReactiveResourceServerApplication.MessageService; -import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; -import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; +import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.AuthenticationSource; +import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import reactor.core.publisher.Mono; @@ -28,115 +31,88 @@ class SpringAddonsGreetingControllerUnitTest { WebTestClient api; /*-----------------------------------------------------------------------------*/ - /* /greet */ - /* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */ + /* /greet */ + /* + * This end-point secured with ".anyRequest().authenticated()" in SecurityConf + */ /*-----------------------------------------------------------------------------*/ @Test @WithAnonymousUser void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { - api.get() - .uri("/greet") - .exchange() - .expectStatus() - .isUnauthorized(); + api.get().uri("/greet").exchange().expectStatus().isUnauthorized(); } - @Test - @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) - void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + @ParameterizedTest + @AuthenticationSource({ + @WithMockAuthentication(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, name = "ch4mpy"), + @WithMockAuthentication(authorities = { "uncle", "PIRATE" }, name = "tonton-pirate") }) + void givenUserIsAuthenticated_whenGetGreet_thenOk(@ParameterizedAuthentication Authentication auth) throws Exception { final var greeting = "Whatever the service returns"; when(messageService.greet()).thenReturn(Mono.just(greeting)); - api.get() - .uri("/greet") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo(greeting); + api.get().uri("/greet").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo(greeting); verify(messageService, times(1)).greet(); } /*---------------------------------------------------------------------------------------------------------------------*/ - /* /secured-route */ - /* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */ + /* /secured-route */ + /* + * This end-point is secured with + * ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in + * SecurityConf + */ /*---------------------------------------------------------------------------------------------------------------------*/ @Test @WithAnonymousUser void givenRequestIsAnonymous_whenGetSecuredRoute_thenUnauthorized() throws Exception { - api.get() - .uri("/secured-route") - .exchange() - .expectStatus() - .isUnauthorized(); + api.get().uri("/secured-route").exchange().expectStatus().isUnauthorized(); } @Test - @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + @WithMockAuthentication("ROLE_AUTHORIZED_PERSONNEL") void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { final var secret = "Secret!"; when(messageService.getSecret()).thenReturn(Mono.just(secret)); - api.get() - .uri("/secured-route") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo(secret); + api.get().uri("/secured-route").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo(secret); } @Test - @WithMockJwtAuth("admin") + @WithMockAuthentication("admin") void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { - api.get() - .uri("/secured-route") - .exchange() - .expectStatus() - .isForbidden(); + api.get().uri("/secured-route").exchange().expectStatus().isForbidden(); } /*---------------------------------------------------------------------------------------------------------*/ - /* /secured-method */ - /* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */ + /* /secured-method */ + /* + * This end-point is secured with + * "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method + */ /*---------------------------------------------------------------------------------------------------------*/ @Test @WithAnonymousUser void givenRequestIsAnonymous_whenGetSecuredMethod_thenUnauthorized() throws Exception { - api.get() - .uri("/secured-method") - .exchange() - .expectStatus() - .isUnauthorized(); + api.get().uri("/secured-method").exchange().expectStatus().isUnauthorized(); } @Test - @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + @WithMockAuthentication("ROLE_AUTHORIZED_PERSONNEL") void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { final var secret = "Secret!"; when(messageService.getSecret()).thenReturn(Mono.just(secret)); - api.get() - .uri("/secured-method") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo(secret); + api.get().uri("/secured-method").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo(secret); } @Test - @WithMockJwtAuth("admin") + @WithMockAuthentication("admin") void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { - api.get() - .uri("/secured-method") - .exchange() - .expectStatus() - .isForbidden(); + api.get().uri("/secured-method").exchange().expectStatus().isForbidden(); } } diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/resources/ch4mpy.json b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/resources/ch4mpy.json new file mode 100644 index 0000000000..22f7bb2cea --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/resources/ch4mpy.json @@ -0,0 +1,15 @@ +{ + "iss": "https://localhost:8443/realms/master", + "sub": "281c4558-550c-413b-9972-2d2e5bde6b9b", + "iat": 1695992542, + "exp": 1695992642, + "preferred_username": "ch4mpy", + "realm_access": { + "roles": [ + "admin", + "ROLE_AUTHORIZED_PERSONNEL" + ] + }, + "email": "ch4mp@c4-soft.com", + "scope": "openid email" +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/resources/tonton-pirate.json b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/resources/tonton-pirate.json new file mode 100644 index 0000000000..13a422f6fd --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/resources/tonton-pirate.json @@ -0,0 +1,15 @@ +{ + "iss": "https://localhost:8443/realms/master", + "sub": "2d2e5bde6b9b-550c-413b-9972-281c4558", + "iat": 1695992551, + "exp": 1695992651, + "preferred_username": "tonton-pirate", + "realm_access": { + "roles": [ + "uncle", + "PIRATE" + ] + }, + "email": "tonton-pirate@c4-soft.com", + "scope": "openid email" +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/java/com/baeldung/ServletResourceServerApplication.java b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/java/com/baeldung/ServletResourceServerApplication.java index a30c60eab0..8258955afe 100644 --- a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/java/com/baeldung/ServletResourceServerApplication.java +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/java/com/baeldung/ServletResourceServerApplication.java @@ -1,5 +1,7 @@ package com.baeldung; +import static org.springframework.security.config.Customizer.withDefaults; + import java.util.Collection; import java.util.List; import java.util.Map; @@ -23,8 +25,10 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.core.oidc.StandardClaimNames; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -43,56 +47,52 @@ public class ServletResourceServerApplication { @EnableWebSecurity static class SecurityConf { @Bean - SecurityFilterChain filterChain(HttpSecurity http, Converter> authoritiesConverter) throws Exception { - http.oauth2ResourceServer() - .jwt() - .jwtAuthenticationConverter(jwt -> new JwtAuthenticationToken(jwt, authoritiesConverter.convert(jwt))); - http.sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS) - .and() - .csrf() - .disable(); - http.exceptionHandling() - .authenticationEntryPoint((request, response, authException) -> { - response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Restricted Content\""); - response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()); - }); + SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.oauth2ResourceServer(resourceServer -> resourceServer.jwt(withDefaults())); + http.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + http.csrf(csrf -> csrf.disable()); + http.exceptionHandling(eh -> eh.authenticationEntryPoint((request, response, authException) -> { + response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer realm=\"Restricted Content\""); + response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()); + })); - http.authorizeHttpRequests() - .requestMatchers("/secured-route") - .hasRole("AUTHORIZED_PERSONNEL") - .anyRequest() - .authenticated(); + // @formatter:off + http.authorizeHttpRequests(req -> req + .requestMatchers(new AntPathRequestMatcher("/secured-route")).hasRole("AUTHORIZED_PERSONNEL") + .anyRequest().authenticated()); + // @formatter:on return http.build(); } - static interface AuthoritiesConverter extends Converter> { + static interface JwtAuthoritiesConverter extends Converter> { } @Bean - AuthoritiesConverter realmRoles2AuthoritiesConverter() { + JwtAuthoritiesConverter realmRoles2AuthoritiesConverter() { return (Jwt jwt) -> { - final var realmRoles = Optional.of(jwt.getClaimAsMap("realm_access")) - .orElse(Map.of()); + final var realmRoles = Optional.of(jwt.getClaimAsMap("realm_access")).orElse(Map.of()); @SuppressWarnings("unchecked") final var roles = (List) realmRoles.getOrDefault("roles", List.of()); - return roles.stream() - .map(SimpleGrantedAuthority::new) - .map(GrantedAuthority.class::cast) - .toList(); + return roles.stream().map(SimpleGrantedAuthority::new).map(GrantedAuthority.class::cast).toList(); }; } + + @Bean + JwtAuthenticationConverter authenticationConverter(Converter> authoritiesConverter) { + final var authenticationConverter = new JwtAuthenticationConverter(); + authenticationConverter.setPrincipalClaimName(StandardClaimNames.PREFERRED_USERNAME); + authenticationConverter.setJwtGrantedAuthoritiesConverter(authoritiesConverter); + return authenticationConverter; + } } @Service public static class MessageService { public String greet() { - final var who = (JwtAuthenticationToken) SecurityContextHolder.getContext() - .getAuthentication(); - final var claims = who.getTokenAttributes(); - return "Hello %s! You are granted with %s.".formatted(claims.getOrDefault(StandardClaimNames.PREFERRED_USERNAME, claims.get(StandardClaimNames.SUB)), who.getAuthorities()); + final var who = (JwtAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); + return "Hello %s! You are granted with %s.".formatted(who.getName(), who.getAuthorities()); } @PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')") diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java index 3c608d226e..ca237fb888 100644 --- a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java @@ -3,28 +3,49 @@ package com.baeldung; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.util.stream.Stream; + import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; -import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.core.oidc.StandardClaimNames; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.baeldung.ServletResourceServerApplication.MessageService; -import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; -import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; +import com.baeldung.ServletResourceServerApplication.SecurityConf; +import com.c4_soft.springaddons.security.oauth2.test.AuthenticationFactoriesTestConf; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; +import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; -@Import({ MessageService.class }) +@Import({ MessageService.class, SecurityConf.class }) +@ImportAutoConfiguration(AuthenticationFactoriesTestConf.class) @ExtendWith(SpringExtension.class) -@EnableMethodSecurity +@TestInstance(Lifecycle.PER_CLASS) class MessageServiceUnitTest { @Autowired MessageService messageService; + @Autowired + WithJwt.AuthenticationFactory authFactory; + + @MockBean + JwtDecoder jwtDecoder; + /*----------------------------------------------------------------------------*/ /* greet() */ /* Expects a JwtAuthenticationToken to be retrieved from the security-context */ @@ -41,10 +62,12 @@ class MessageServiceUnitTest { assertThrows(AccessDeniedException.class, () -> messageService.getSecret()); } - @Test - @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) - void givenSecurityContextIsPopulatedWithJwtAuthenticationToken_whenGreet_thenReturnGreetingWithPreferredUsernameAndAuthorities() { - assertEquals("Hello ch4mpy! You are granted with [admin, ROLE_AUTHORIZED_PERSONNEL].", messageService.greet()); + @ParameterizedTest + @MethodSource("allIdentities") + void givenUserIsAuthenticated_whenGreet_thenReturnGreetingWithPreferredUsernameAndAuthorities(@ParameterizedAuthentication Authentication auth) { + final var jwt = (JwtAuthenticationToken) auth; + final var expected = "Hello %s! You are granted with %s.".formatted(jwt.getTokenAttributes().get(StandardClaimNames.PREFERRED_USERNAME), auth.getAuthorities()); + assertEquals(expected, messageService.greet()); } @Test @@ -65,15 +88,22 @@ class MessageServiceUnitTest { } @Test - @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) - void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenReturnSecret() { + @WithJwt("ch4mpy.json") + void givenUserIsCh4mpy_whenGetSecret_thenReturnSecret() { assertEquals("Only authorized personnel can read that", messageService.getSecret()); } @Test - @WithMockJwtAuth(authorities = { "admin" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) - void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenThrowsAccessDeniedException() { + @WithJwt("tonton-pirate.json") + void givenUserIsTontonPirate_whenGetSecret_thenThrowsAccessDeniedException() { assertThrows(AccessDeniedException.class, () -> messageService.getSecret()); } + /*--------------------------------------------*/ + /* methodSource returning all test identities */ + /*--------------------------------------------*/ + private Stream allIdentities() { + final var authentications = authFactory.authenticationsFrom("ch4mpy.json", "tonton-pirate.json").toList(); + return authentications.stream(); + } } diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/ServletResourceServerApplicationIntegrationTest.java b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/ServletResourceServerApplicationIntegrationTest.java index 5bb539741f..4f2fe51787 100644 --- a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/ServletResourceServerApplicationIntegrationTest.java +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/ServletResourceServerApplicationIntegrationTest.java @@ -12,8 +12,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.test.web.servlet.MockMvc; -import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; -import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @@ -34,7 +34,7 @@ class ServletResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + @WithJwt("ch4mpy.json") void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { api.perform(get("/greet")) .andExpect(status().isOk()) @@ -54,7 +54,7 @@ class ServletResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + @WithMockAuthentication("ROLE_AUTHORIZED_PERSONNEL") void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { api.perform(get("/secured-route")) .andExpect(status().isOk()) @@ -62,7 +62,7 @@ class ServletResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth("admin") + @WithMockAuthentication("admin") void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { api.perform(get("/secured-route")) .andExpect(status().isForbidden()); @@ -81,7 +81,7 @@ class ServletResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + @WithMockAuthentication("ROLE_AUTHORIZED_PERSONNEL") void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { api.perform(get("/secured-method")) .andExpect(status().isOk()) @@ -89,7 +89,7 @@ class ServletResourceServerApplicationIntegrationTest { } @Test - @WithMockJwtAuth("admin") + @WithMockAuthentication("admin") void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { api.perform(get("/secured-method")) .andExpect(status().isForbidden()); diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java index 9162768930..2534d9919a 100644 --- a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java @@ -8,16 +8,19 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.core.Authentication; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.ServletResourceServerApplication.GreetingController; import com.baeldung.ServletResourceServerApplication.MessageService; -import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; -import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; +import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.AuthenticationSource; +import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; @WebMvcTest(controllers = GreetingController.class, properties = { "server.ssl.enabled=false" }) class SpringAddonsGreetingControllerUnitTest { @@ -40,9 +43,11 @@ class SpringAddonsGreetingControllerUnitTest { .andExpect(status().isUnauthorized()); } - @Test - @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) - void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + @ParameterizedTest + @AuthenticationSource({ + @WithMockAuthentication(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, name = "ch4mpy"), + @WithMockAuthentication(authorities = { "uncle", "PIRATE" }, name = "tonton-pirate") }) + void givenUserIsAuthenticated_whenGetGreet_thenOk(@ParameterizedAuthentication Authentication auth) throws Exception { final var greeting = "Whatever the service returns"; when(messageService.greet()).thenReturn(greeting); @@ -66,7 +71,7 @@ class SpringAddonsGreetingControllerUnitTest { } @Test - @WithMockJwtAuth({ "admin", "ROLE_AUTHORIZED_PERSONNEL" }) + @WithMockAuthentication({ "admin", "ROLE_AUTHORIZED_PERSONNEL" }) void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { final var secret = "Secret!"; when(messageService.getSecret()).thenReturn(secret); @@ -77,7 +82,7 @@ class SpringAddonsGreetingControllerUnitTest { } @Test - @WithMockJwtAuth({ "admin" }) + @WithMockAuthentication({ "admin" }) void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { api.perform(get("/secured-route")) .andExpect(status().isForbidden()); @@ -96,7 +101,7 @@ class SpringAddonsGreetingControllerUnitTest { } @Test - @WithMockJwtAuth({ "admin", "ROLE_AUTHORIZED_PERSONNEL" }) + @WithMockAuthentication({ "admin", "ROLE_AUTHORIZED_PERSONNEL" }) void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { final var secret = "Secret!"; when(messageService.getSecret()).thenReturn(secret); @@ -107,7 +112,7 @@ class SpringAddonsGreetingControllerUnitTest { } @Test - @WithMockJwtAuth(authorities = { "admin" }) + @WithMockAuthentication({ "admin" }) void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { api.perform(get("/secured-method")) .andExpect(status().isForbidden()); diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/resources/ch4mpy.json b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/resources/ch4mpy.json new file mode 100644 index 0000000000..22f7bb2cea --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/resources/ch4mpy.json @@ -0,0 +1,15 @@ +{ + "iss": "https://localhost:8443/realms/master", + "sub": "281c4558-550c-413b-9972-2d2e5bde6b9b", + "iat": 1695992542, + "exp": 1695992642, + "preferred_username": "ch4mpy", + "realm_access": { + "roles": [ + "admin", + "ROLE_AUTHORIZED_PERSONNEL" + ] + }, + "email": "ch4mp@c4-soft.com", + "scope": "openid email" +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/resources/tonton-pirate.json b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/resources/tonton-pirate.json new file mode 100644 index 0000000000..13a422f6fd --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/resources/tonton-pirate.json @@ -0,0 +1,15 @@ +{ + "iss": "https://localhost:8443/realms/master", + "sub": "2d2e5bde6b9b-550c-413b-9972-281c4558", + "iat": 1695992551, + "exp": 1695992651, + "preferred_username": "tonton-pirate", + "realm_access": { + "roles": [ + "uncle", + "PIRATE" + ] + }, + "email": "tonton-pirate@c4-soft.com", + "scope": "openid email" +} \ No newline at end of file diff --git a/spring-web-modules/pom.xml b/spring-web-modules/pom.xml index d513822ea3..9f03b83392 100644 --- a/spring-web-modules/pom.xml +++ b/spring-web-modules/pom.xml @@ -52,6 +52,7 @@ spring-thymeleaf-4 spring-thymeleaf-5 spring-web-url + spring-thymeleaf-attributes \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-5/pom.xml b/spring-web-modules/spring-mvc-basics-5/pom.xml index c957d669bd..e0d603e303 100644 --- a/spring-web-modules/spring-mvc-basics-5/pom.xml +++ b/spring-web-modules/spring-mvc-basics-5/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -30,8 +30,14 @@ tomcat-embed-jasper - javax.servlet - jstl + jakarta.servlet.jsp.jstl + jakarta.servlet.jsp.jstl-api + ${jakarta.servlet.jsp.jstl} + + + org.glassfish.web + jakarta.servlet.jsp.jstl + ${jakarta.servlet.jsp.jstl} org.springframework.boot @@ -53,6 +59,11 @@ jaxb-runtime ${jaxb-runtime.version} + + io.rest-assured + rest-assured + ${io.rest-assured.version} + @@ -73,6 +84,8 @@ 1.3.2 2.7.0 2.3.5 + 2.0.0 + 3.0.0 \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/JsonArgumentResolver.java b/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/JsonArgumentResolver.java index 3cb01dae32..94b8d12107 100644 --- a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/JsonArgumentResolver.java +++ b/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/JsonArgumentResolver.java @@ -3,7 +3,7 @@ package com.baeldung.jsonargs; import java.io.IOException; import java.util.Objects; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.springframework.core.MethodParameter; diff --git a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/modelattribute/Employee.java b/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/modelattribute/Employee.java index 0ec3c5c374..2dacfe87d9 100644 --- a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/modelattribute/Employee.java +++ b/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/modelattribute/Employee.java @@ -1,6 +1,6 @@ package com.baeldung.modelattribute; -import javax.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Employee { diff --git a/testing-modules/junit5-annotations/pom.xml b/testing-modules/junit5-annotations/pom.xml index 847baa827c..3a7ab1aa87 100644 --- a/testing-modules/junit5-annotations/pom.xml +++ b/testing-modules/junit5-annotations/pom.xml @@ -45,6 +45,8 @@ + 1.10.0 + 5.10.0 2.19.0 diff --git a/testing-modules/testing-libraries-2/pom.xml b/testing-modules/testing-libraries-2/pom.xml index 4cc3ea8428..717ccac2b2 100644 --- a/testing-modules/testing-libraries-2/pom.xml +++ b/testing-modules/testing-libraries-2/pom.xml @@ -53,6 +53,30 @@ ${system-stubs.version} test + + uk.org.webcompere + system-stubs-testng + ${system-stubs.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.junit-pioneer + junit-pioneer + ${junit.pioneer.version} + test + + + org.testng + testng + ${testng.version} + test + @@ -127,6 +151,9 @@ --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED + + YES + @@ -142,7 +169,10 @@ 0.8.6 1.19.0 1.0.0 - 1.1.0 + 2.1.3 + 7.8.0 + 3.24.2 + 2.1.0 \ No newline at end of file diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesByAbstractionUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesByAbstractionUnitTest.java new file mode 100644 index 0000000000..0ac0603c64 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesByAbstractionUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.environmentvariablesfortest; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class EnvironmentVariablesByAbstractionUnitTest { + + @FunctionalInterface + interface GetEnv { + String get(String name); + } + + static class ReadsEnvironment { + private GetEnv getEnv; + + public ReadsEnvironment(GetEnv getEnv) { + this.getEnv = getEnv; + } + + public String whatOs() { + return getEnv.get("OS"); + } + } + + @Test + void givenFakeOs_thenCanReadIt() { + Map fakeEnv = new HashMap<>(); + fakeEnv.put("OS", "MacDowsNix"); + + ReadsEnvironment reader = new ReadsEnvironment(fakeEnv::get); + assertThat(reader.whatOs()).isEqualTo("MacDowsNix"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSetByJUnitPioneerUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSetByJUnitPioneerUnitTest.java new file mode 100644 index 0000000000..02081a6598 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSetByJUnitPioneerUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.environmentvariablesfortest; + +import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.ClearEnvironmentVariable; +import org.junitpioneer.jupiter.SetEnvironmentVariable; + +import static org.assertj.core.api.Assertions.assertThat; + +@SetEnvironmentVariable(key = "pioneer", value = "is pioneering") +class EnvironmentVariablesSetByJUnitPioneerUnitTest { + + @Test + void givenEnvironmentVariableIsSetForClass_thenVariableCanBeRead() { + assertThat(System.getenv("pioneer")).isEqualTo("is pioneering"); + } + + @ClearEnvironmentVariable(key = "pioneer") + @Test + void givenEnvironmentVariableIsClear_thenItIsNotSet() { + assertThat(System.getenv("pioneer")).isNull(); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSetDirectlyUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSetDirectlyUnitTest.java new file mode 100644 index 0000000000..61a3ca3c2e --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSetDirectlyUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.environmentvariablesfortest; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; + +import java.lang.reflect.Field; +import java.util.Map; +import static org.assertj.core.api.Assertions.assertThat; + +@EnabledForJreRange(min = JRE.JAVA_8, max = JRE.JAVA_16) +class EnvironmentVariablesSetDirectlyUnitTest { + @BeforeAll + static void beforeAll() throws Exception { + Class classOfMap = System.getenv().getClass(); + Field field = classOfMap.getDeclaredField("m"); + field.setAccessible(true); + Map writeableEnvironmentVariables = (Map)field.get(System.getenv()); + + writeableEnvironmentVariables.put("baeldung", "has set an environment variable"); + } + + @Test + void givenEnvironmentVariableWasSet_thenCanReadIt() { + assertThat(System.getenv("baeldung")).isEqualTo("has set an environment variable"); + } + + @Test + void givenEnvironmentVariableSetBySurefire_thenCanReadIt() { + assertThat(System.getenv("SET_BY_SUREFIRE")).isEqualTo("YES"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemLambdaUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemLambdaUnitTest.java new file mode 100644 index 0000000000..050bebddfd --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemLambdaUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.environmentvariablesfortest; + +import org.junit.jupiter.api.Test; + +import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable; + +import static org.assertj.core.api.Assertions.assertThat; + +class EnvironmentVariablesSystemLambdaUnitTest { + + @Test + void givenSetEnvironmentVariablesInTest_thenCanBeRead() throws Exception { + withEnvironmentVariable("system lambda", "in test") + .execute(() -> { + assertThat(System.getenv("system lambda")).isEqualTo("in test"); + }); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemRulesUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemRulesUnitTest.java new file mode 100644 index 0000000000..44ebb1be71 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemRulesUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.environmentvariablesfortest; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.contrib.java.lang.system.EnvironmentVariables; + +import static org.assertj.core.api.Assertions.assertThat; + +public class EnvironmentVariablesSystemRulesUnitTest { + @Rule + public EnvironmentVariables environmentVariablesRule = new EnvironmentVariables(); + + @Before + public void before() { + environmentVariablesRule.set("system rules", "works"); + } + + @Test + public void givenEnvironmentVariable_thenCanReadIt() { + assertThat(System.getenv("system rules")).isEqualTo("works"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsJUnit4UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsJUnit4UnitTest.java new file mode 100644 index 0000000000..efb0ba5598 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsJUnit4UnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.environmentvariablesfortest; + +import org.junit.Rule; +import org.junit.Test; +import uk.org.webcompere.systemstubs.rules.EnvironmentVariablesRule; + +import static org.assertj.core.api.Assertions.assertThat; + +public class EnvironmentVariablesSystemStubsJUnit4UnitTest { + @Rule + public EnvironmentVariablesRule environmentVariablesRule = + new EnvironmentVariablesRule("system stubs", "initializes variable"); + + @Test + public void givenEnvironmentSetUpInObject_thenCanReadIt() { + assertThat(System.getenv("system stubs")).isEqualTo("initializes variable"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsJUnit5UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsJUnit5UnitTest.java new file mode 100644 index 0000000000..1304e4921a --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsJUnit5UnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.environmentvariablesfortest; + + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import uk.org.webcompere.systemstubs.environment.EnvironmentVariables; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(SystemStubsExtension.class) +class EnvironmentVariablesSystemStubsJUnit5UnitTest { + + @SystemStub + private EnvironmentVariables environmentVariables; + + @BeforeEach + void beforeEach() { + environmentVariables.set("systemstubs", "creates stub objects"); + } + + @Test + void givenEnvironmentVariableHasBeenSet_thenCanReadIt() { + assertThat(System.getenv("systemstubs")).isEqualTo("creates stub objects"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsNoFrameworkClassScopeEnvironmentUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsNoFrameworkClassScopeEnvironmentUnitTest.java new file mode 100644 index 0000000000..9e9421c3f1 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsNoFrameworkClassScopeEnvironmentUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.environmentvariablesfortest; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import uk.org.webcompere.systemstubs.environment.EnvironmentVariables; + +import static org.assertj.core.api.Assertions.assertThat; + +class EnvironmentVariablesSystemStubsNoFrameworkClassScopeEnvironmentUnitTest { + private static EnvironmentVariables environmentVariables = new EnvironmentVariables(); + + @BeforeAll + static void beforeAll() throws Exception { + environmentVariables.set("system stubs", "in test"); + environmentVariables.setup(); + } + + @AfterAll + static void afterAll() throws Exception { + environmentVariables.teardown(); + } + + @Test + void givenSetEnvironmentVariablesBeforeAll_thenCanBeRead() throws Exception { + assertThat(System.getenv("system stubs")).isEqualTo("in test"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsNoFrameworkUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsNoFrameworkUnitTest.java new file mode 100644 index 0000000000..2e7a92b85f --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsNoFrameworkUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.environmentvariablesfortest; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.org.webcompere.systemstubs.SystemStubs.withEnvironmentVariables; + +class EnvironmentVariablesSystemStubsNoFrameworkUnitTest { + + @Test + void givenSetEnvironmentVariablesInTest_thenCanBeRead() throws Exception { + withEnvironmentVariables("system stubs", "in test") + .execute(() -> { + assertThat(System.getenv("system stubs")).isEqualTo("in test"); + }); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsTestNGUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsTestNGUnitTest.java new file mode 100644 index 0000000000..61ca76a8b0 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/environmentvariablesfortest/EnvironmentVariablesSystemStubsTestNGUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.environmentvariablesfortest; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Listeners; +import org.testng.annotations.Test; +import uk.org.webcompere.systemstubs.environment.EnvironmentVariables; +import uk.org.webcompere.systemstubs.testng.SystemStub; +import uk.org.webcompere.systemstubs.testng.SystemStubsListener; +import static org.assertj.core.api.Assertions.assertThat; + +@Listeners(SystemStubsListener.class) +public class EnvironmentVariablesSystemStubsTestNGUnitTest { + @SystemStub + private EnvironmentVariables setEnvironment; + + @BeforeClass + public void beforeAll() { + setEnvironment.set("testng", "has environment variables"); + } + + @Test + public void givenEnvironmentVariableWasSet_thenItCanBeRead() { + assertThat(System.getenv("testng")).isEqualTo("has environment variables"); + } + +} diff --git a/web-modules/pom.xml b/web-modules/pom.xml index 2dcec681ad..684283b546 100644 --- a/web-modules/pom.xml +++ b/web-modules/pom.xml @@ -31,7 +31,7 @@ ratpack resteasy - + restx spark-java struts-2 vraptor diff --git a/web-modules/restx/md.restx.json b/web-modules/restx/md.restx.json index c87244001c..54a1b4e9f8 100644 --- a/web-modules/restx/md.restx.json +++ b/web-modules/restx/md.restx.json @@ -3,8 +3,8 @@ "packaging": "war", "properties": { - "java.version": "1.8", - "restx.version": "0.35-rc4" + "java.version": "17", + "restx.version": "1.0.0-rc3" }, "fragments": { "maven": [ @@ -24,7 +24,7 @@ "io.restx:restx-i18n-admin:${restx.version}", "io.restx:restx-stats-admin:${restx.version}", "io.restx:restx-servlet:${restx.version}", - "io.restx:restx-server-jetty8:${restx.version}!optional", + "io.restx:restx-server-jetty11:${restx.version}!optional", "io.restx:restx-apidocs:${restx.version}", "io.restx:restx-specs-admin:${restx.version}", "io.restx:restx-admin:${restx.version}", diff --git a/web-modules/restx/pom.xml b/web-modules/restx/pom.xml index 0e6cb3fa78..f75292a4a4 100644 --- a/web-modules/restx/pom.xml +++ b/web-modules/restx/pom.xml @@ -77,7 +77,7 @@ io.restx - restx-server-jetty8 + restx-server-jetty11 ${restx.version} true @@ -137,8 +137,7 @@ - 0.35-rc4 - 1.6.0 + 1.0.0-rc3 \ No newline at end of file diff --git a/web-modules/restx/src/main/java/restx/demo/AppModule.java b/web-modules/restx/src/main/java/restx/demo/AppModule.java index 26bc681481..b47f8b9aa8 100644 --- a/web-modules/restx/src/main/java/restx/demo/AppModule.java +++ b/web-modules/restx/src/main/java/restx/demo/AppModule.java @@ -3,13 +3,13 @@ package restx.demo; import restx.config.ConfigLoader; import restx.config.ConfigSupplier; import restx.factory.Provides; +import restx.security.*; +import restx.factory.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableSet; -import restx.security.*; -import restx.factory.Module; -import restx.factory.Provides; + import javax.inject.Named; import java.nio.file.Paths; @@ -30,7 +30,7 @@ public class AppModule { @Provides public ConfigSupplier appConfigSupplier(ConfigLoader configLoader) { // Load settings.properties in restx.demo package as a set of config entries - return configLoader.fromResource("restx/demo/settings"); + return configLoader.fromResource("web-modules/restx/demo/settings"); } @Provides diff --git a/web-modules/restx/src/main/java/restx/demo/AppServer.java b/web-modules/restx/src/main/java/restx/demo/AppServer.java index d66aadac68..089a22c9ae 100644 --- a/web-modules/restx/src/main/java/restx/demo/AppServer.java +++ b/web-modules/restx/src/main/java/restx/demo/AppServer.java @@ -2,7 +2,7 @@ package restx.demo; import com.google.common.base.Optional; import restx.server.WebServer; -import restx.server.Jetty8WebServer; +import restx.server.Jetty11WebServer; /** * This class can be used to run the app. @@ -17,7 +17,7 @@ public class AppServer { public static void main(String[] args) throws Exception { int port = Integer.valueOf(Optional.fromNullable(System.getenv("PORT")).or("8080")); - WebServer server = new Jetty8WebServer(WEB_INF_LOCATION, WEB_APP_LOCATION, port, "0.0.0.0"); + WebServer server = new Jetty11WebServer(WEB_INF_LOCATION, WEB_APP_LOCATION, port, "0.0.0.0"); /* * load mode from system property if defined, or default to dev