Merge branch 'eugenp:master' into PR-7135
This commit is contained in:
commit
f8bad9e049
@ -4,4 +4,5 @@
|
|||||||
- [Find the N Most Frequent Elements in a Java Array](https://www.baeldung.com/java-n-most-frequent-elements-array)
|
- [Find the N Most Frequent Elements in a Java Array](https://www.baeldung.com/java-n-most-frequent-elements-array)
|
||||||
- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
|
- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
|
||||||
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
|
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
|
||||||
|
- [Rotate Arrays in Java](https://www.baeldung.com/java-rotate-arrays)
|
||||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>apache-poi-3</artifactId>
|
<artifactId>apache-poi-3</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
@ -1,43 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<artifactId>aws-s3-update-object</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>aws-s3-update-object</name>
|
|
||||||
<description>Project demonstrating overwriting of S3 objects</description>
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-boot-2</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<relativePath>../../parent-boot-2</relativePath>
|
|
||||||
</parent>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>aws-java-sdk</artifactId>
|
|
||||||
<version>${aws-java-sdk-version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
<properties>
|
|
||||||
<aws-java-sdk-version>1.12.523</aws-java-sdk-version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
@ -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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
@ -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<String, String> 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
aws.s3bucket=baeldung-documents;
|
|
@ -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));
|
|
||||||
}
|
|
||||||
}
|
|
@ -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"));
|
|
||||||
}
|
|
||||||
}
|
|
@ -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)
|
- [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)
|
- [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)
|
- [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)
|
||||||
|
@ -45,6 +45,13 @@ public class S3Application {
|
|||||||
new File("/Users/user/Document/hello.txt")
|
new File("/Users/user/Document/hello.txt")
|
||||||
);
|
);
|
||||||
|
|
||||||
|
s3Service.updateObject(
|
||||||
|
AWS_BUCKET,
|
||||||
|
"Document/hello2.txt",
|
||||||
|
new File("/Users/user/Document/hello2.txt")
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
//listing objects
|
//listing objects
|
||||||
s3Service.listObjects(AWS_BUCKET);
|
s3Service.listObjects(AWS_BUCKET);
|
||||||
|
|
||||||
|
@ -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.GetObjectResponse;
|
||||||
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
|
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
|
||||||
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
|
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.ListBucketsResponse;
|
||||||
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
|
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
|
||||||
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
|
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
|
||||||
@ -99,7 +100,13 @@ class S3Service {
|
|||||||
.key(key)
|
.key(key)
|
||||||
.build();
|
.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
|
//listing objects
|
||||||
@ -110,6 +117,7 @@ class S3Service {
|
|||||||
ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request);
|
ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request);
|
||||||
|
|
||||||
for(S3Object os : listObjectsV2Response.contents()) {
|
for(S3Object os : listObjectsV2Response.contents()) {
|
||||||
|
|
||||||
System.out.println(os.key());
|
System.out.println(os.key());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,6 +11,8 @@ import org.mockito.Mock;
|
|||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.mockito.MockitoAnnotations;
|
import org.mockito.MockitoAnnotations;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.nio.file.Path;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
|
||||||
import software.amazon.awssdk.services.s3.S3Client;
|
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.ListBucketsResponse;
|
||||||
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
|
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
|
||||||
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
|
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
|
||||||
|
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||||
|
|
||||||
class S3ServiceIntegrationTest {
|
class S3ServiceIntegrationTest {
|
||||||
|
|
||||||
@ -38,6 +41,8 @@ class S3ServiceIntegrationTest {
|
|||||||
|
|
||||||
private final String AWS_BUCKET = "baeldung-tutorial-s3";
|
private final String AWS_BUCKET = "baeldung-tutorial-s3";
|
||||||
|
|
||||||
|
private File file = new File("/Users/user/Document/hello2.txt");
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
public void setup() {
|
public void setup() {
|
||||||
MockitoAnnotations.openMocks(this);
|
MockitoAnnotations.openMocks(this);
|
||||||
@ -75,6 +80,17 @@ class S3ServiceIntegrationTest {
|
|||||||
verify(s3Client).createBucket(bucketRequest);
|
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
|
@Test
|
||||||
void whenVerifyingListBuckets_thenCorrect() {
|
void whenVerifyingListBuckets_thenCorrect() {
|
||||||
when(s3Client.listBuckets()).thenReturn(ListBucketsResponse.builder().buckets(Collections.emptyList()).build());
|
when(s3Client.listBuckets()).thenReturn(ListBucketsResponse.builder().buckets(Collections.emptyList()).build());
|
||||||
|
@ -28,7 +28,6 @@
|
|||||||
<module>aws-miscellaneous</module>
|
<module>aws-miscellaneous</module>
|
||||||
<module>aws-reactive</module>
|
<module>aws-reactive</module>
|
||||||
<module>aws-s3</module>
|
<module>aws-s3</module>
|
||||||
<module>aws-s3-update-object</module>
|
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
@ -8,3 +8,4 @@
|
|||||||
- [Sealed Classes and Interfaces in Java](https://www.baeldung.com/java-sealed-classes-interfaces)
|
- [Sealed Classes and Interfaces in Java](https://www.baeldung.com/java-sealed-classes-interfaces)
|
||||||
- [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17)
|
- [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17)
|
||||||
- [Format Multiple ‘or’ Conditions in an If Statement in Java](https://www.baeldung.com/java-multiple-or-conditions-if-statement)
|
- [Format Multiple ‘or’ Conditions in an If Statement in Java](https://www.baeldung.com/java-multiple-or-conditions-if-statement)
|
||||||
|
- [Get All Record Fields and Its Values via Reflection](https://www.baeldung.com/java-reflection-record-fields-values)
|
||||||
|
@ -0,0 +1,2 @@
|
|||||||
|
## Relevant Articles
|
||||||
|
- [Deprecate Finalization in Java 18](https://www.baeldung.com/java-18-deprecate-finalization)
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-21</artifactId>
|
<artifactId>core-java-21</artifactId>
|
||||||
<name>core-java-21</name>
|
<name>core-java-21</name>
|
||||||
@ -12,12 +12,6 @@
|
|||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<maven.compiler.source.version>21</maven.compiler.source.version>
|
|
||||||
<maven.compiler.target.version>21</maven.compiler.target.version>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
@ -44,4 +38,10 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source.version>21</maven.compiler.source.version>
|
||||||
|
<maven.compiler.target.version>21</maven.compiler.target.version>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-arrays-operations-advanced-2</artifactId>
|
<artifactId>core-java-arrays-operations-advanced-2</artifactId>
|
||||||
<name>core-java-arrays-operations-advanced-2</name>
|
<name>core-java-arrays-operations-advanced-2</name>
|
||||||
|
@ -0,0 +1,60 @@
|
|||||||
|
package com.baeldung.removequeueelements;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.Queue;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
public class RemoveQueueElementsUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenQueueWithEvenAndOddNumbers_whenRemovingEvenNumbers_thenOddNumbersRemain() {
|
||||||
|
Queue<Integer> queue = new LinkedList<>();
|
||||||
|
Queue<Integer> evenElementsQueue = new LinkedList<>();
|
||||||
|
queue.add(1);
|
||||||
|
queue.add(2);
|
||||||
|
queue.add(3);
|
||||||
|
queue.add(4);
|
||||||
|
queue.add(5);
|
||||||
|
|
||||||
|
while (queue.peek() != null) {
|
||||||
|
int element = queue.remove();
|
||||||
|
if (element % 2 != 0) {
|
||||||
|
evenElementsQueue.add(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(3, evenElementsQueue.size());
|
||||||
|
assertTrue(evenElementsQueue.contains(1));
|
||||||
|
assertTrue(evenElementsQueue.contains(3));
|
||||||
|
assertTrue(evenElementsQueue.contains(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringQueue_whenRemovingStringsThatStartWithA_thenStringElementsRemain() {
|
||||||
|
Queue<String> queue = new LinkedList<>();
|
||||||
|
Queue<String> stringElementsQueue = new LinkedList<>();
|
||||||
|
queue.add("Apple");
|
||||||
|
queue.add("Banana");
|
||||||
|
queue.add("Orange");
|
||||||
|
queue.add("Grape");
|
||||||
|
queue.add("Mango");
|
||||||
|
|
||||||
|
|
||||||
|
while (queue.peek() != null) {
|
||||||
|
String element = queue.remove();
|
||||||
|
if (!element.startsWith("A")) {
|
||||||
|
stringElementsQueue.add(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(4, stringElementsQueue.size());
|
||||||
|
assertTrue(stringElementsQueue.contains("Banana"));
|
||||||
|
assertTrue(stringElementsQueue.contains("Orange"));
|
||||||
|
assertTrue(stringElementsQueue.contains("Grape"));
|
||||||
|
assertTrue(stringElementsQueue.contains("Mango"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,17 +1,17 @@
|
|||||||
<project
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-collections-array-list-2</artifactId>
|
<artifactId>core-java-collections-array-list-2</artifactId>
|
||||||
<name>core-java-collections-array-list-2</name>
|
<name>core-java-collections-array-list-2</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.core-java-modules</groupId>
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
<artifactId>core-java-modules</artifactId>
|
<artifactId>core-java-modules</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
@ -24,7 +24,7 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven-compiler-plugin.source>17</maven-compiler-plugin.source>
|
<maven-compiler-plugin.source>17</maven-compiler-plugin.source>
|
||||||
<maven-compiler-plugin.target>17</maven-compiler-plugin.target>
|
<maven-compiler-plugin.target>17</maven-compiler-plugin.target>
|
||||||
|
@ -4,3 +4,4 @@ This module contains articles about conversions among Collection types in Java.
|
|||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Converting HashMap Values to an ArrayList in Java](https://www.baeldung.com/java-hashmap-arraylist)
|
- [Converting HashMap Values to an ArrayList in Java](https://www.baeldung.com/java-hashmap-arraylist)
|
||||||
|
- [Joining a List<String> in Java With Commas and “and”](https://www.baeldung.com/java-string-concatenation-natural-language)
|
||||||
|
@ -71,4 +71,15 @@ public class ListOfListsUnitTest {
|
|||||||
assertThat(listOfLists.get(2)).containsExactly("Slack", "Zoom", "Microsoft Teams", "Telegram");
|
assertThat(listOfLists.get(2)).containsExactly("Slack", "Zoom", "Microsoft Teams", "Telegram");
|
||||||
printListOfLists(listOfLists);
|
printListOfLists(listOfLists);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
@Test
|
||||||
|
void givenListOfLists_whenGettingSizeOfSubListsAndSizeOfElements_thenGetExpectedResults() throws URISyntaxException, IOException {
|
||||||
|
List<List<String>> 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);
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-collections-list-6</artifactId>
|
<artifactId>core-java-collections-list-6</artifactId>
|
||||||
<name>core-java-collections-list-6</name>
|
<name>core-java-collections-list-6</name>
|
||||||
@ -12,4 +12,5 @@
|
|||||||
<artifactId>core-java-modules</artifactId>
|
<artifactId>core-java-modules</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -9,3 +9,4 @@
|
|||||||
- [Converting String or String Array to Map in Java](https://www.baeldung.com/java-convert-string-to-map)
|
- [Converting String or String Array to Map in Java](https://www.baeldung.com/java-convert-string-to-map)
|
||||||
- [Remove Duplicate Values From HashMap in Java](https://www.baeldung.com/java-hashmap-delete-duplicates)
|
- [Remove Duplicate Values From HashMap in Java](https://www.baeldung.com/java-hashmap-delete-duplicates)
|
||||||
- [Sorting Java Map in Descending Order](https://www.baeldung.com/java-sort-map-descending)
|
- [Sorting Java Map in Descending Order](https://www.baeldung.com/java-sort-map-descending)
|
||||||
|
- [Convert HashMap.toString() to HashMap in Java](https://www.baeldung.com/hashmap-from-tostring)
|
||||||
|
@ -1 +1,2 @@
|
|||||||
## Relevant Articles
|
## Relevant Articles
|
||||||
|
- [Difference Between putIfAbsent() and computeIfAbsent() in Java’s Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent)
|
||||||
|
@ -73,6 +73,11 @@
|
|||||||
<version>4.13.1</version>
|
<version>4.13.1</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-csv</artifactId>
|
||||||
|
<version>1.5</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -10,18 +10,26 @@ import java.nio.file.Paths;
|
|||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
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.Assert.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
public class WriteHashmaptoCVSFileUnitTest {
|
public class WriteHashmaptoCVSFileUnitTest {
|
||||||
|
public Map<String, String> employeeData;
|
||||||
|
|
||||||
@Test
|
public WriteHashmaptoCVSFileUnitTest() {
|
||||||
public void givenEmployeeData_whenWriteToCSV_thenCSVFileIsCreated() {
|
employeeData = new HashMap<>();
|
||||||
Map<String, String> employeeData = new HashMap<>();
|
|
||||||
employeeData.put("Name", "John Doe");
|
employeeData.put("Name", "John Doe");
|
||||||
employeeData.put("Title", "Software Engineer");
|
employeeData.put("Title", "Software Engineer");
|
||||||
employeeData.put("Department", "Engineering");
|
employeeData.put("Department", "Engineering");
|
||||||
employeeData.put("Salary", "75000");
|
employeeData.put("Salary", "75000");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmployeeData_whenWriteToCSVUsingFileWriter_thenCSVFileIsCreated() {
|
||||||
|
|
||||||
try (FileWriter csvWriter = new FileWriter("employee_data.csv")) {
|
try (FileWriter csvWriter = new FileWriter("employee_data.csv")) {
|
||||||
// Write header row
|
// Write header row
|
||||||
csvWriter.append("Name,Title,Department,Salary\n");
|
csvWriter.append("Name,Title,Department,Salary\n");
|
||||||
@ -40,23 +48,19 @@ public class WriteHashmaptoCVSFileUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCSVFile_whenRead_thenContentsMatchExpected() {
|
public void givenCSVFile_whenWriteToCSVUsingApacheCommons_thenContentsMatchExpected() {
|
||||||
// Read the actual content of the CSV file
|
|
||||||
StringBuilder actualCsvContent = new StringBuilder();
|
|
||||||
try {
|
|
||||||
Files.lines(Paths.get("employee_data.csv"))
|
|
||||||
.forEach(line -> actualCsvContent.append(line).append("\n"));
|
|
||||||
|
|
||||||
// Define the expected CSV content
|
try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter("employee_data2.csv"), CSVFormat.DEFAULT)) {
|
||||||
String expectedCsvContent = "Name,Title,Department,Salary\n" +
|
// Write header row
|
||||||
"John Doe,Software Engineer,Engineering,75000\n";
|
csvPrinter.printRecord("Name", "Title", "Department", "Salary");
|
||||||
|
|
||||||
// Compare the actual content with the expected content
|
// Write data row
|
||||||
assertEquals(expectedCsvContent, actualCsvContent.toString());
|
csvPrinter.printRecord(employeeData.get("Name"), employeeData.get("Title"), employeeData.get("Department"), employeeData.get("Salary"));
|
||||||
|
|
||||||
System.out.println("CSV file created successfully.");
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ensure the CSV file exists
|
||||||
|
assertTrue(new File("employee_data2.csv").exists());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,8 +20,9 @@ public class Main {
|
|||||||
System.out.println("General exception");
|
System.out.println("General exception");
|
||||||
}
|
}
|
||||||
|
|
||||||
checkedException();
|
checkedExceptionWithTryCatch();
|
||||||
checkedExceptionWithThrows();
|
checkedExceptionWithThrows();
|
||||||
|
divideByZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void checkedExceptionWithThrows() throws FileNotFoundException {
|
private static void checkedExceptionWithThrows() throws FileNotFoundException {
|
||||||
@ -29,7 +30,7 @@ public class Main {
|
|||||||
FileInputStream stream = new FileInputStream(file);
|
FileInputStream stream = new FileInputStream(file);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void checkedException() {
|
private static void checkedExceptionWithTryCatch() {
|
||||||
File file = new File("not_existing_file.txt");
|
File file = new File("not_existing_file.txt");
|
||||||
try {
|
try {
|
||||||
FileInputStream stream = new FileInputStream(file);
|
FileInputStream stream = new FileInputStream(file);
|
||||||
@ -37,5 +38,11 @@ public class Main {
|
|||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void divideByZero() {
|
||||||
|
int numerator = 1;
|
||||||
|
int denominator = 0;
|
||||||
|
int result = numerator / denominator;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.exceptions.throwvsthrows;
|
||||||
|
|
||||||
|
public class NullOrEmptyException extends RuntimeException {
|
||||||
|
|
||||||
|
public NullOrEmptyException(String errorMessage) {
|
||||||
|
super(errorMessage);
|
||||||
|
}
|
||||||
|
}
|
@ -4,5 +4,6 @@ This module contains articles about core Java input and output (IO)
|
|||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Get File Extension From MIME Type in Java](https://www.baeldung.com/java-mime-type-file-extension)
|
- [Get File Extension From MIME Type in Java](https://www.baeldung.com/java-mime-type-file-extension)
|
||||||
|
- [How to Remove Line Breaks From a File in Java](https://www.baeldung.com/java-file-remove-line-breaks)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-io-4)
|
- [[<-- Prev]](/core-java-modules/core-java-io-4)
|
||||||
|
|
||||||
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -3,7 +3,10 @@ package com.baeldung.size;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.URL;
|
||||||
import java.nio.channels.FileChannel;
|
import java.nio.channels.FileChannel;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
@ -62,4 +65,24 @@ public class JavaFileSizeUnitTest {
|
|||||||
final long length = file.length();
|
final long length = file.length();
|
||||||
return 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
@ -8,3 +8,4 @@ This module contains articles about core features in the Java language
|
|||||||
- [What Is the Maximum Depth of the Java Call Stack?](https://www.baeldung.com/java-call-stack-max-depth)
|
- [What Is the Maximum Depth of the Java Call Stack?](https://www.baeldung.com/java-call-stack-max-depth)
|
||||||
- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample)
|
- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample)
|
||||||
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
|
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
|
||||||
|
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
|
||||||
|
@ -12,4 +12,5 @@
|
|||||||
- [Java Program to Print Pascal’s Triangle](https://www.baeldung.com/java-pascal-triangle)
|
- [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)
|
- [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)
|
- [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)
|
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)
|
||||||
|
@ -1,7 +1,5 @@
|
|||||||
package com.baeldung.magicsquare;
|
package com.baeldung.magicsquare;
|
||||||
|
|
||||||
import org.junit.platform.commons.util.StringUtils;
|
|
||||||
|
|
||||||
import java.util.stream.IntStream;
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
public class MagicSquare {
|
public class MagicSquare {
|
||||||
|
@ -1,2 +0,0 @@
|
|||||||
## Relevant Articles
|
|
||||||
- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square)
|
|
@ -9,3 +9,4 @@ This module contains articles about Object Oriented Programming (OOP) in Java
|
|||||||
- [Check If All the Variables of an Object Are Null](https://www.baeldung.com/java-check-all-variables-object-null)
|
- [Check If All the Variables of an Object Are Null](https://www.baeldung.com/java-check-all-variables-object-null)
|
||||||
- [Law of Demeter in Java](https://www.baeldung.com/java-demeter-law)
|
- [Law of Demeter in Java](https://www.baeldung.com/java-demeter-law)
|
||||||
- [Java Interface Naming Conventions](https://www.baeldung.com/java-interface-naming-conventions)
|
- [Java Interface Naming Conventions](https://www.baeldung.com/java-interface-naming-conventions)
|
||||||
|
- [Difference Between Information Hiding and Encapsulation](https://www.baeldung.com/java-information-hiding-vs-encapsulation)
|
||||||
|
@ -6,4 +6,5 @@
|
|||||||
- [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits)
|
- [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits)
|
||||||
- [Java Double vs. BigDecimal](https://www.baeldung.com/java-double-vs-bigdecimal)
|
- [Java Double vs. BigDecimal](https://www.baeldung.com/java-double-vs-bigdecimal)
|
||||||
- [Finding the Square Root of a BigInteger in Java](https://www.baeldung.com/java-find-square-root-biginteger)
|
- [Finding the Square Root of a BigInteger in Java](https://www.baeldung.com/java-find-square-root-biginteger)
|
||||||
|
- [Truncate a Double to Two Decimal Places in Java](https://www.baeldung.com/java-double-round-two-decimal-places)
|
||||||
- More articles: [[<-- prev]](../core-java-numbers-5)
|
- More articles: [[<-- prev]](../core-java-numbers-5)
|
||||||
|
@ -2,3 +2,5 @@
|
|||||||
- [Convert a Number to a Letter in Java](https://www.baeldung.com/java-convert-number-to-letter)
|
- [Convert a Number to a Letter in Java](https://www.baeldung.com/java-convert-number-to-letter)
|
||||||
- [Convert Long to BigDecimal in Java](https://www.baeldung.com/java-convert-long-bigdecimal)
|
- [Convert Long to BigDecimal in Java](https://www.baeldung.com/java-convert-long-bigdecimal)
|
||||||
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
|
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
|
||||||
|
- [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float)
|
||||||
|
- [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal)
|
||||||
|
@ -3,5 +3,5 @@
|
|||||||
This module contains articles about working with the operating system (OS) in Java
|
This module contains articles about working with the operating system (OS) in Java
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
- [How to Detect the Username Using Java](https://www.baeldung.com/java-get-username)
|
||||||
|
|
||||||
|
@ -14,6 +14,5 @@ This module contains articles about working with the operating system (OS) in Ja
|
|||||||
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
|
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
|
||||||
- [Taking Screenshots Using Java](https://www.baeldung.com/java-taking-screenshots)
|
- [Taking Screenshots Using Java](https://www.baeldung.com/java-taking-screenshots)
|
||||||
- [Java Sound API – Capturing Microphone](https://www.baeldung.com/java-sound-api-capture-mic)
|
- [Java Sound API – Capturing Microphone](https://www.baeldung.com/java-sound-api-capture-mic)
|
||||||
- [How to Detect the Username Using Java](https://www.baeldung.com/java-get-username)
|
|
||||||
|
|
||||||
This module uses Java 9, so make sure to have the JDK 9 installed to run it.
|
This module uses Java 9, so make sure to have the JDK 9 installed to run it.
|
||||||
|
@ -1,2 +1,2 @@
|
|||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Is Java Reflection Bad Practice?](https://www.baeldung.com/java-reflection-bad-practice)
|
- [Is Java Reflection Bad Practice?](https://www.baeldung.com/java-reflection-benefits-drawbacks)
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-security-4</artifactId>
|
<artifactId>core-java-security-4</artifactId>
|
||||||
<name>core-java-security-4</name>
|
<name>core-java-security-4</name>
|
||||||
|
@ -6,19 +6,23 @@ import java.util.function.BinaryOperator;
|
|||||||
import java.util.stream.Collector;
|
import java.util.stream.Collector;
|
||||||
|
|
||||||
class SkippingCollector {
|
class SkippingCollector {
|
||||||
|
|
||||||
private static final BinaryOperator<SkippingCollector> IGNORE_COMBINE = (a, b) -> a;
|
private static final BinaryOperator<SkippingCollector> IGNORE_COMBINE = (a, b) -> a;
|
||||||
private final int skip;
|
private final int skip;
|
||||||
private final List<String> list = new ArrayList<>();
|
private final List<String> list = new ArrayList<>();
|
||||||
private int currentIndex = 0;
|
private int currentIndex = 0;
|
||||||
|
|
||||||
private SkippingCollector(int skip) {
|
private SkippingCollector(int skip) {
|
||||||
this.skip = skip;
|
this.skip = skip;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void accept(String item) {
|
private void accept(String item) {
|
||||||
final int index = ++currentIndex % skip;
|
final int index = ++currentIndex % skip;
|
||||||
if (index == 0)
|
if (index == 0) {
|
||||||
list.add(item);
|
list.add(item);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<String> getResult() {
|
private List<String> getResult() {
|
||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
|
@ -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<String> skipNthElementInListWithFilter(List<String> sourceList, int n) {
|
|
||||||
return IntStream.range(0, sourceList.size())
|
|
||||||
.filter(s -> (s + 1) % n == 0)
|
|
||||||
.mapToObj(sourceList::get)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
|
||||||
|
|
||||||
public static List<String> skipNthElementInListWithIterate(List<String> 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<String> skipNthElementInListWithSublist(List<String> 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<String> skipNthElementInListWithFor(List<String> sourceList, int n) {
|
|
||||||
List<String> result = new ArrayList<>();
|
|
||||||
for (int i = n - 1; i < sourceList.size(); i += n) {
|
|
||||||
result.add(sourceList.get(i));
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static List<String> skipNthElementInListWithIterator(Stream<String> sourceStream, int n) {
|
|
||||||
List<String> result = new ArrayList<>();
|
|
||||||
final Iterator<String> 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<String> skipNthElementInStreamWithCollector(Stream<String> sourceStream, int n) {
|
|
||||||
return sourceStream.collect(SkippingCollector.collector(n));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -3,7 +3,11 @@ package com.baeldung.skippingelements;
|
|||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
import org.junit.jupiter.params.ParameterizedTest;
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
import org.junit.jupiter.params.provider.Arguments;
|
import org.junit.jupiter.params.provider.Arguments;
|
||||||
@ -14,21 +18,22 @@ class SkippingElementsUnitTest {
|
|||||||
private static Stream<Arguments> testSource() {
|
private static Stream<Arguments> testSource() {
|
||||||
return Stream.of(
|
return Stream.of(
|
||||||
Arguments.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",
|
"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",
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
"Thirty One", "Thirty Two", "Thirty Three"),
|
"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),
|
3),
|
||||||
Arguments.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",
|
"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",
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
"Thirty One", "Thirty Two", "Thirty Three"),
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
List.of("Five", "Ten", "Fifteen", "Twenty", "Twenty Five", "Thirty"),
|
List.of("Five", "Ten", "Fifteen", "Twenty", "Twenty Five", "Thirty"),
|
||||||
5),
|
5),
|
||||||
Arguments.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",
|
"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",
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
"Thirty One", "Thirty Two", "Thirty Three"),
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
@ -38,29 +43,29 @@ class SkippingElementsUnitTest {
|
|||||||
"Thirty One", "Thirty Two", "Thirty Three"),
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
1),
|
1),
|
||||||
Arguments.of(
|
Arguments.of(
|
||||||
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
Stream.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
List.of("Wednesday", "Saturday"),
|
List.of("Wednesday", "Saturday"),
|
||||||
3),
|
3),
|
||||||
Arguments.of(
|
Arguments.of(
|
||||||
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
Stream.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
List.of("Friday"),
|
List.of("Friday"),
|
||||||
5),
|
5),
|
||||||
Arguments.of(
|
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"),
|
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
1),
|
1),
|
||||||
Arguments.of(
|
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"),
|
"December"),
|
||||||
List.of("March", "June", "September", "December"),
|
List.of("March", "June", "September", "December"),
|
||||||
3),
|
3),
|
||||||
Arguments.of(
|
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"),
|
"December"),
|
||||||
List.of("May", "October"),
|
List.of("May", "October"),
|
||||||
5),
|
5),
|
||||||
Arguments.of(
|
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"),
|
"December"),
|
||||||
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
||||||
"December"),
|
"December"),
|
||||||
@ -70,45 +75,73 @@ class SkippingElementsUnitTest {
|
|||||||
|
|
||||||
@ParameterizedTest
|
@ParameterizedTest
|
||||||
@MethodSource("testSource")
|
@MethodSource("testSource")
|
||||||
void givenListSkipNthElementInListWithFilterTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
void givenListSkipNthElementInListWithFilterTestShouldFilterNthElement(Stream<String> input, List<String> expected, int n) {
|
||||||
final List<String> actual = SkippingElements.skipNthElementInListWithFilter(input, n);
|
final List<String> sourceList = input.collect(Collectors.toList());
|
||||||
|
final List<String> actual = IntStream.range(0, sourceList.size())
|
||||||
|
.filter(s -> (s + 1) % n == 0)
|
||||||
|
.mapToObj(sourceList::get)
|
||||||
|
.collect(Collectors.toList());
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ParameterizedTest
|
@ParameterizedTest
|
||||||
@MethodSource("testSource")
|
@MethodSource("testSource")
|
||||||
void givenListSkipNthElementInListWithIterateTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
void givenListSkipNthElementInListWithIterateTestShouldFilterNthElement(Stream<String> input, List<String> expected, int n) {
|
||||||
final List<String> actual = SkippingElements.skipNthElementInListWithIterate(input, n);
|
final List<String> sourceList = input.collect(Collectors.toList());
|
||||||
|
int limit = sourceList.size() / n;
|
||||||
|
final List<String> actual = IntStream.iterate(n - 1, i -> (i + n))
|
||||||
|
.limit(limit)
|
||||||
|
.mapToObj(sourceList::get)
|
||||||
|
.collect(Collectors.toList());
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ParameterizedTest
|
@ParameterizedTest
|
||||||
@MethodSource("testSource")
|
@MethodSource("testSource")
|
||||||
void givenListSkipNthElementInListWithSublistTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
void givenListSkipNthElementInListWithSublistTestShouldFilterNthElement(Stream<String> input, List<String> expected, int n) {
|
||||||
final List<String> actual = SkippingElements.skipNthElementInListWithSublist(input, n);
|
final List<String> sourceList = input.collect(Collectors.toList());
|
||||||
|
int limit = sourceList.size() / n;
|
||||||
|
final List<String> actual = Stream.iterate(sourceList, s -> s.subList(n, s.size()))
|
||||||
|
.limit(limit)
|
||||||
|
.map(s -> s.get(n - 1))
|
||||||
|
.collect(Collectors.toList());
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ParameterizedTest
|
@ParameterizedTest
|
||||||
@MethodSource("testSource")
|
@MethodSource("testSource")
|
||||||
void givenListSkipNthElementInListWithForTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
void givenListSkipNthElementInListWithForTestShouldFilterNthElement(Stream<String> input, List<String> expected, int n) {
|
||||||
final List<String> actual = SkippingElements.skipNthElementInListWithFor(input, n);
|
final List<String> sourceList = input.collect(Collectors.toList());
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
for (int i = n - 1; i < sourceList.size(); i += n) {
|
||||||
|
result.add(sourceList.get(i));
|
||||||
|
}
|
||||||
|
final List<String> actual = result;
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ParameterizedTest
|
@ParameterizedTest
|
||||||
@MethodSource("testSource")
|
@MethodSource("testSource")
|
||||||
void givenListSkipNthElementInStreamWithIteratorTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
void givenListSkipNthElementInStreamWithIteratorTestShouldFilterNthElement(Stream<String> input, List<String> expected, int n) {
|
||||||
final Stream<String> inputStream = input.stream();
|
List<String> result = new ArrayList<>();
|
||||||
final List<String> actual = SkippingElements.skipNthElementInListWithIterator(inputStream, n);
|
final Iterator<String> iterator = input.iterator();
|
||||||
|
int count = 0;
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
if (count % n == n - 1) {
|
||||||
|
result.add(iterator.next());
|
||||||
|
} else {
|
||||||
|
iterator.next();
|
||||||
|
}
|
||||||
|
++count;
|
||||||
|
}
|
||||||
|
final List<String> actual = result;
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ParameterizedTest
|
@ParameterizedTest
|
||||||
@MethodSource("testSource")
|
@MethodSource("testSource")
|
||||||
void givenListSkipNthElementInStreamWithCollectorShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
void givenListSkipNthElementInStreamWithCollectorShouldFilterNthElement(Stream<String> input, List<String> expected, int n) {
|
||||||
final Stream<String> inputStream = input.stream();
|
final List<String> actual = input.collect(SkippingCollector.collector(n));
|
||||||
final List<String> actual = SkippingElements.skipNthElementInStreamWithCollector(inputStream, n);
|
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -2,6 +2,10 @@
|
|||||||
|
|
||||||
This module contains articles about Streams that are part of the Java Streams Ebook.
|
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
|
### Relevant Articles
|
||||||
|
|
||||||
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
|
- [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)
|
- [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)
|
- [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 Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
||||||
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
||||||
|
@ -28,6 +28,11 @@
|
|||||||
<artifactId>emoji-java</artifactId>
|
<artifactId>emoji-java</artifactId>
|
||||||
<version>${emoji-java.version}</version>
|
<version>${emoji-java.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-text</artifactId>
|
||||||
|
<version>${apache-commons-text.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -58,6 +63,7 @@
|
|||||||
<validator.version>1.7</validator.version>
|
<validator.version>1.7</validator.version>
|
||||||
<apache-commons-lang3.version>3.12.0</apache-commons-lang3.version>
|
<apache-commons-lang3.version>3.12.0</apache-commons-lang3.version>
|
||||||
<emoji-java.version>5.1.1</emoji-java.version>
|
<emoji-java.version>5.1.1</emoji-java.version>
|
||||||
|
<apache-commons-text.version>1.10.0</apache-commons-text.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -2,3 +2,4 @@
|
|||||||
- [Object.toString() vs String.valueOf()](https://www.baeldung.com/java-object-tostring-vs-string-valueof)
|
- [Object.toString() vs String.valueOf()](https://www.baeldung.com/java-object-tostring-vs-string-valueof)
|
||||||
- [Convert String to Int Using Encapsulation](https://www.baeldung.com/java-encapsulation-convert-string-to-int)
|
- [Convert String to Int Using Encapsulation](https://www.baeldung.com/java-encapsulation-convert-string-to-int)
|
||||||
- [HashMap with Multiple Values for the Same Key](https://www.baeldung.com/java-hashmap-multiple-values-per-key)
|
- [HashMap with Multiple Values for the Same Key](https://www.baeldung.com/java-hashmap-multiple-values-per-key)
|
||||||
|
- [Split Java String Into Key-Value Pairs](https://www.baeldung.com/java-split-string-map)
|
||||||
|
@ -23,4 +23,12 @@
|
|||||||
</resources>
|
</resources>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
</project>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
||||||
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
@ -3,6 +3,7 @@ package com.baeldung.centertext;
|
|||||||
import liquibase.repackaged.org.apache.commons.lang3.StringUtils;
|
import liquibase.repackaged.org.apache.commons.lang3.StringUtils;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class CenteringTextUnitTest {
|
public class CenteringTextUnitTest {
|
||||||
@ -10,17 +11,16 @@ public class CenteringTextUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenTextAndTotalWidth_whenUsingStringFormat_thenTextIsCentered() {
|
public void givenTextAndTotalWidth_whenUsingStringFormat_thenTextIsCentered() {
|
||||||
String text = "Centered Text";
|
String text = "Centered Text";
|
||||||
int totalWidth = 20;
|
int totalWidth = 15;
|
||||||
int padding = (totalWidth - text.length()) / 2;
|
int padding = (totalWidth - text.length()) / 2;
|
||||||
String centeredText = String.format("%" + padding + "s%s%" + padding + "s", "", text, "");
|
String centeredText = String.format("%" + padding + "s%s%" + padding + "s", "", text, "");
|
||||||
String expectedCenteredText = " Centered Text ";
|
Assert.assertEquals(" Centered Text ", centeredText);
|
||||||
Assert.assertEquals("Centered Text", expectedCenteredText, centeredText);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTextAndTotalWidth_whenCenterUsingStringBuilder_thenTextIsCentered() {
|
public void givenTextAndTotalWidth_whenCenterUsingStringBuilder_thenTextIsCentered() {
|
||||||
String text = "Centered Text";
|
String text = "Centered Text";
|
||||||
int width = 20;
|
int width = 15;
|
||||||
int padding = (width - text.length()) / 2;
|
int padding = (width - text.length()) / 2;
|
||||||
StringBuilder centeredText = new StringBuilder();
|
StringBuilder centeredText = new StringBuilder();
|
||||||
for (int i = 0; i < padding; i++) {
|
for (int i = 0; i < padding; i++) {
|
||||||
@ -31,17 +31,15 @@ public class CenteringTextUnitTest {
|
|||||||
centeredText.append(" ");
|
centeredText.append(" ");
|
||||||
}
|
}
|
||||||
String centeredTextString = centeredText.toString();
|
String centeredTextString = centeredText.toString();
|
||||||
String expectedCenteredText = " Centered Text ";
|
Assert.assertEquals(" Centered Text ", centeredTextString);
|
||||||
Assert.assertEquals("Centered Text", expectedCenteredText, centeredTextString);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTextAndTotalWidth_whenUsingStringUtilsCenterMethod_thenTextIsCentered() {
|
public void givenTextAndTotalWidth_whenUsingStringUtilsCenterMethod_thenTextIsCentered() {
|
||||||
String text = "Centered Text";
|
String text = "Centered Text";
|
||||||
int width = 20;
|
int width = 15;
|
||||||
String centeredText = StringUtils.center(text, width);
|
String centeredText = StringUtils.center(text, width);
|
||||||
String expectedCenteredText = StringUtils.center("Centered Text", width);
|
assertEquals(" Centered Text ", centeredText);
|
||||||
assertEquals("Centered Text", expectedCenteredText, centeredText);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -27,6 +27,11 @@
|
|||||||
<!--<module>core-java-security</module> -->
|
<!--<module>core-java-security</module> -->
|
||||||
<!--<module>core-java-streams-2</module> -->
|
<!--<module>core-java-streams-2</module> -->
|
||||||
<!--<module>core-java-sun</module> -->
|
<!--<module>core-java-sun</module> -->
|
||||||
|
<!-- <module>core-java-modules/core-java-9-new-features</module> --> <!-- JAVA-26056 -->
|
||||||
|
<!-- <module>core-java-modules/core-java-14</module> --> <!-- JAVA-26056 -->
|
||||||
|
<!-- <module>core-java-modules/core-java-16</module> --> <!-- JAVA-26056 -->
|
||||||
|
<!-- <module>core-java-modules/core-java-17</module> --> <!-- JAVA-26056 -->
|
||||||
|
<!-- <module>core-java-modules/core-java-19</module> --> <!-- JAVA-26056 -->
|
||||||
<module>core-java-9-improvements</module>
|
<module>core-java-9-improvements</module>
|
||||||
<module>core-java-9-streams</module>
|
<module>core-java-9-streams</module>
|
||||||
<module>core-java-9</module>
|
<module>core-java-9</module>
|
||||||
@ -188,6 +193,11 @@
|
|||||||
<module>core-java-collections-maps-6</module>
|
<module>core-java-collections-maps-6</module>
|
||||||
<module>core-java-records</module>
|
<module>core-java-records</module>
|
||||||
<module>core-java-9-jigsaw</module>
|
<module>core-java-9-jigsaw</module>
|
||||||
|
<!--<module>core-java-20</module>--> <!--JAVA-25373-->
|
||||||
|
<module>core-java-collections-set</module>
|
||||||
|
<module>core-java-date-operations-1</module>
|
||||||
|
<!--<module>core-java-datetime-conversion</module>--> <!--JAVA-25433-->
|
||||||
|
<module>core-java-httpclient</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
|
@ -8,8 +8,10 @@ buildscript {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
apply plugin: 'java'
|
plugins {
|
||||||
apply plugin: 'com.github.johnrengelman.shadow'
|
id 'com.github.johnrengelman.shadow' version '7.1.2'
|
||||||
|
id 'java'
|
||||||
|
}
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
@ -30,7 +32,7 @@ task customFatJar(type: Jar) {
|
|||||||
manifest {
|
manifest {
|
||||||
attributes 'Main-Class': 'com.baeldung.fatjar.Application'
|
attributes 'Main-Class': 'com.baeldung.fatjar.Application'
|
||||||
}
|
}
|
||||||
baseName = 'all-in-one-jar'
|
archiveBaseName = 'all-in-one-jar'
|
||||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||||
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
|
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
|
||||||
with jar
|
with jar
|
||||||
|
@ -33,7 +33,7 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<jackson.version>2.14.2</jackson.version>
|
<jackson.version>2.15.2</jackson.version>
|
||||||
<java.version>17</java.version>
|
<java.version>17</java.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -11,3 +11,4 @@ This module contains articles about Jersey.
|
|||||||
- [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters)
|
- [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters)
|
||||||
- [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers)
|
- [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers)
|
||||||
- [Exception Handling With Jersey](https://www.baeldung.com/java-exception-handling-jersey)
|
- [Exception Handling With Jersey](https://www.baeldung.com/java-exception-handling-jersey)
|
||||||
|
- [@FormDataParam vs. @FormParam in Jersey](https://www.baeldung.com/jersey-formdataparam-vs-formparam)
|
||||||
|
@ -4,4 +4,5 @@ This module contains articles about Apache Commons libraries.
|
|||||||
|
|
||||||
### Relevant articles
|
### Relevant articles
|
||||||
- [Extracting a Tar File in Java](https://www.baeldung.com/java-extract-tar-file)
|
- [Extracting a Tar File in Java](https://www.baeldung.com/java-extract-tar-file)
|
||||||
|
- [Convert a String with Unicode Encoding to a String of Letters](https://www.baeldung.com/java-convert-string-unicode-encoding)
|
||||||
- More articles: [[<--prev]](../libraries-apache-commons)
|
- More articles: [[<--prev]](../libraries-apache-commons)
|
||||||
|
@ -14,7 +14,7 @@ public class BuilderWithDefaultValueUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenBuilderWithDefaultValue_NoArgsWorksAlso() {
|
public void givenBuilderWithDefaultValue_ThanNoArgsWorksAlso() {
|
||||||
Pojo build = new Pojo().toBuilder()
|
Pojo build = new Pojo().toBuilder()
|
||||||
.build();
|
.build();
|
||||||
Pojo pojo = new Pojo();
|
Pojo pojo = new Pojo();
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>parent-spring-6</artifactId>
|
<artifactId>parent-spring-6</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
@ -1,2 +1,3 @@
|
|||||||
## Relevant Articles
|
## Relevant Articles
|
||||||
- [The Factory Design Pattern in Java](https://www.baeldung.com/java-factory-pattern)
|
- [The Factory Design Pattern in Java](https://www.baeldung.com/java-factory-pattern)
|
||||||
|
- [Drawbacks of the Singleton Design Pattern](https://www.baeldung.com/java-patterns-singleton-cons)
|
||||||
|
@ -12,4 +12,13 @@
|
|||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-inline</artifactId>
|
||||||
|
<version>${mockito.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<Logger> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -35,7 +35,7 @@
|
|||||||
<module>hibernate-queries</module>
|
<module>hibernate-queries</module>
|
||||||
<module>hibernate-enterprise</module>
|
<module>hibernate-enterprise</module>
|
||||||
<module>influxdb</module>
|
<module>influxdb</module>
|
||||||
<module>java-cassandra</module>
|
<module>java-cassandra</module>
|
||||||
<module>java-cockroachdb</module>
|
<module>java-cockroachdb</module>
|
||||||
<module>java-jdbi</module>
|
<module>java-jdbi</module>
|
||||||
<module>java-jpa</module> <!-- long running -->
|
<module>java-jpa</module> <!-- long running -->
|
||||||
@ -110,7 +110,6 @@
|
|||||||
<module>spring-mybatis</module>
|
<module>spring-mybatis</module>
|
||||||
<module>spring-persistence-simple</module>
|
<module>spring-persistence-simple</module>
|
||||||
<module>spring-data-yugabytedb</module>
|
<module>spring-data-yugabytedb</module>
|
||||||
|
|
||||||
<module>fauna</module>
|
<module>fauna</module>
|
||||||
<module>spring-data-rest</module>
|
<module>spring-data-rest</module>
|
||||||
<module>java-mongodb</module>
|
<module>java-mongodb</module>
|
||||||
|
@ -11,9 +11,9 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-boot-2</artifactId>
|
<artifactId>parent-boot-3</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-boot-2</relativePath>
|
<relativePath>../../parent-boot-3</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -44,12 +44,19 @@
|
|||||||
<artifactId>db-util</artifactId>
|
<artifactId>db-util</artifactId>
|
||||||
<version>${db-util.version}</version>
|
<version>${db-util.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!-- fixes https://hibernate.atlassian.net/browse/HHH-16593-->
|
||||||
|
<!-- and https://discourse.hibernate.org/t/bootstrap-failed-with-hibernate-6-3-0-final/8200 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate.orm</groupId>
|
||||||
|
<artifactId>hibernate-core</artifactId>
|
||||||
|
<version>6.3.1.Final</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- The main class to start by executing java -jar -->
|
<!-- The main class to start by executing java -jar -->
|
||||||
<start-class>com.baeldung.h2db.demo.server.SpringBootApp</start-class>
|
<start-class>com.baeldung.h2db.demo.server.SpringBootApp</start-class>
|
||||||
<db-util.version>1.0.4</db-util.version>
|
<db-util.version>1.0.7</db-util.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,7 +1,7 @@
|
|||||||
package com.baeldung.h2.exceptions.models;
|
package com.baeldung.h2.exceptions.models;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class User {
|
public class User {
|
||||||
|
@ -3,15 +3,15 @@ package com.baeldung.h2db.demo.client;
|
|||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import javax.annotation.PostConstruct;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
import org.springframework.context.annotation.PropertySource;
|
|
||||||
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
import org.springframework.jdbc.core.RowMapper;
|
import org.springframework.jdbc.core.RowMapper;
|
||||||
|
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@ComponentScan("com.baeldung.h2db.demo.client")
|
@ComponentScan("com.baeldung.h2db.demo.client")
|
||||||
public class ClientSpringBootApp {
|
public class ClientSpringBootApp {
|
||||||
|
@ -3,7 +3,7 @@ package com.baeldung.h2db.demo.server;
|
|||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import javax.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import org.h2.tools.Server;
|
import org.h2.tools.Server;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
|
@ -1,13 +1,14 @@
|
|||||||
package com.baeldung.h2db.lazy_load_no_trans.entity;
|
package com.baeldung.h2db.lazy_load_no_trans.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.Column;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.hibernate.annotations.Immutable;
|
import org.hibernate.annotations.Immutable;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Getter
|
@Getter
|
||||||
@ -22,5 +23,6 @@ public class Document {
|
|||||||
|
|
||||||
private String title;
|
private String title;
|
||||||
|
|
||||||
|
@Column(name="user_id")
|
||||||
private Long userId;
|
private Long userId;
|
||||||
}
|
}
|
||||||
|
@ -8,10 +8,10 @@ import org.hibernate.annotations.Fetch;
|
|||||||
import org.hibernate.annotations.FetchMode;
|
import org.hibernate.annotations.FetchMode;
|
||||||
import org.hibernate.annotations.Immutable;
|
import org.hibernate.annotations.Immutable;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.OneToMany;
|
import jakarta.persistence.OneToMany;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
@ -1,9 +1,10 @@
|
|||||||
package com.baeldung.h2db.notnull.models;
|
package com.baeldung.h2db.notnull.models;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
package com.baeldung.h2db.springboot.models;
|
package com.baeldung.h2db.springboot.models;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
@Table(name = "countries")
|
@Table(name = "countries")
|
||||||
|
@ -4,9 +4,9 @@ insert into "user" values (103, 'user3', 'comment3');
|
|||||||
insert into "user" values (104, 'user4', 'comment4');
|
insert into "user" values (104, 'user4', 'comment4');
|
||||||
insert into "user" values (105, 'user5', 'comment5');
|
insert into "user" values (105, 'user5', 'comment5');
|
||||||
|
|
||||||
insert into "document" values (1, 'doc1', 101);
|
insert into "document" ("id","title","user_id") values (1, 'doc1', 101);
|
||||||
insert into "document" values (2, 'doc2', 101);
|
insert into "document" ("id","title","user_id") values (2, 'doc2', 101);
|
||||||
insert into "document" values (3, 'doc3', 101);
|
insert into "document" ("id","title","user_id") values (3, 'doc3', 101);
|
||||||
insert into "document" values (4, 'doc4', 101);
|
insert into "document" ("id","title","user_id") values (4, 'doc4', 101);
|
||||||
insert into "document" values (5, 'doc5', 102);
|
insert into "document" ("id","title","user_id") values (5, 'doc5', 102);
|
||||||
insert into "document" values (6, 'doc6', 102);
|
insert into "document" ("id","title","user_id") values (6, 'doc6', 102);
|
@ -2,16 +2,17 @@ package com.baeldung.h2db.notnull;
|
|||||||
|
|
||||||
import com.baeldung.h2db.notnull.daos.ItemRepository;
|
import com.baeldung.h2db.notnull.daos.ItemRepository;
|
||||||
import com.baeldung.h2db.notnull.models.Item;
|
import com.baeldung.h2db.notnull.models.Item;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
import javax.validation.ConstraintViolationException;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import jakarta.validation.ConstraintViolationException;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest(classes = NotNullVsNullableApplication.class)
|
@SpringBootTest(classes = NotNullVsNullableApplication.class)
|
||||||
public class ItemIntegrationTest {
|
public class ItemIntegrationTest {
|
||||||
@ -21,8 +22,8 @@ public class ItemIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldNotAllowToPersistNullItemsPrice() {
|
public void shouldNotAllowToPersistNullItemsPrice() {
|
||||||
assertThatThrownBy(() -> itemRepository.save(new Item()))
|
assertThatThrownBy(() -> itemRepository.save(new Item())).hasRootCauseInstanceOf(ConstraintViolationException.class)
|
||||||
.hasRootCauseInstanceOf(ConstraintViolationException.class)
|
.hasStackTraceContaining("propertyPath=price")
|
||||||
.hasStackTraceContaining("must not be null");
|
.hasStackTraceContaining("null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -19,18 +19,18 @@
|
|||||||
<artifactId>spring-data-elasticsearch</artifactId>
|
<artifactId>spring-data-elasticsearch</artifactId>
|
||||||
<version>${spring-data-elasticsearch.version}</version>
|
<version>${spring-data-elasticsearch.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!--These two dependencies are inherited from spring-data-elasticsearch. Overriding to the newer version
|
<!--These two dependencies are inherited from spring-data-elasticsearch. Overriding to the newer version
|
||||||
will break tests. -->
|
will break tests. -->
|
||||||
<!-- <dependency>-->
|
<!-- <dependency>-->
|
||||||
<!-- <groupId>co.elastic.clients</groupId>-->
|
<!-- <groupId>co.elastic.clients</groupId>-->
|
||||||
<!-- <artifactId>elasticsearch-java</artifactId>-->
|
<!-- <artifactId>elasticsearch-java</artifactId>-->
|
||||||
<!-- <version>${elasticsearch.version}</version>-->
|
<!-- <version>${elasticsearch.version}</version>-->
|
||||||
<!-- </dependency>-->
|
<!-- </dependency>-->
|
||||||
<!-- <dependency>-->
|
<!-- <dependency>-->
|
||||||
<!-- <groupId>com.fasterxml.jackson.core</groupId>-->
|
<!-- <groupId>com.fasterxml.jackson.core</groupId>-->
|
||||||
<!-- <artifactId>jackson-databind</artifactId>-->
|
<!-- <artifactId>jackson-databind</artifactId>-->
|
||||||
<!-- <version>${jackson.version}</version>-->
|
<!-- <version>${jackson.version}</version>-->
|
||||||
<!-- </dependency>-->
|
<!-- </dependency>-->
|
||||||
<!-- Here for backward compatibility-->
|
<!-- Here for backward compatibility-->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.elasticsearch.client</groupId>
|
<groupId>org.elasticsearch.client</groupId>
|
||||||
@ -47,6 +47,7 @@
|
|||||||
<artifactId>spring-boot-autoconfigure</artifactId>
|
<artifactId>spring-boot-autoconfigure</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
@ -55,6 +56,7 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-data-elasticsearch.version>5.1.2</spring-data-elasticsearch.version>
|
<spring-data-elasticsearch.version>5.1.2</spring-data-elasticsearch.version>
|
||||||
<elasticsearch.version>8.9.0</elasticsearch.version>
|
<elasticsearch.version>8.9.0</elasticsearch.version>
|
||||||
|
@ -1,16 +1,16 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>spring-data-jpa-query-2</artifactId>
|
<artifactId>spring-data-jpa-query-2</artifactId>
|
||||||
<name>spring-data-jpa-query-2</name>
|
<name>spring-data-jpa-query-2</name>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-boot-2</artifactId>
|
<artifactId>parent-boot-3</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-boot-2</relativePath>
|
<relativePath>../../parent-boot-3</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -38,6 +38,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>mysql</groupId>
|
<groupId>mysql</groupId>
|
||||||
<artifactId>mysql-connector-java</artifactId>
|
<artifactId>mysql-connector-java</artifactId>
|
||||||
|
<version>3.1.12</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
@ -50,12 +51,19 @@
|
|||||||
<version>${tomcat-dbcp.version}</version>
|
<version>${tomcat-dbcp.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate</groupId>
|
<groupId>org.hibernate.orm</groupId>
|
||||||
<artifactId>hibernate-core</artifactId>
|
<artifactId>hibernate-core</artifactId>
|
||||||
|
<version>6.3.1.Final</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate</groupId>
|
<groupId>org.hibernate.orm</groupId>
|
||||||
<artifactId>hibernate-envers</artifactId>
|
<artifactId>hibernate-envers</artifactId>
|
||||||
|
<version>6.3.1.Final</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>3.13.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
package com.baeldung.hibernate.fetching.model;
|
package com.baeldung.hibernate.fetching.model;
|
||||||
|
|
||||||
import javax.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.sql.Date;
|
import java.sql.Date;
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
package com.baeldung.hibernate.fetching.model;
|
package com.baeldung.hibernate.fetching.model;
|
||||||
|
|
||||||
import javax.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
package com.baeldung.hibernate.fetching.model;
|
package com.baeldung.hibernate.fetching.model;
|
||||||
|
|
||||||
import javax.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
@ -3,12 +3,12 @@ package com.baeldung.persistence.dao.common;
|
|||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import javax.persistence.EntityManager;
|
import jakarta.persistence.EntityManager;
|
||||||
import javax.persistence.PersistenceContext;
|
import jakarta.persistence.PersistenceContext;
|
||||||
import javax.persistence.TypedQuery;
|
import jakarta.persistence.TypedQuery;
|
||||||
import javax.persistence.criteria.CriteriaBuilder;
|
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||||
import javax.persistence.criteria.CriteriaQuery;
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
import javax.persistence.criteria.Root;
|
import jakarta.persistence.criteria.Root;
|
||||||
|
|
||||||
public class AbstractJpaDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
|
public class AbstractJpaDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
|
||||||
|
|
||||||
|
@ -3,29 +3,29 @@ package com.baeldung.persistence.model;
|
|||||||
import com.google.common.collect.Sets;
|
import com.google.common.collect.Sets;
|
||||||
import org.hibernate.annotations.OrderBy;
|
import org.hibernate.annotations.OrderBy;
|
||||||
import org.hibernate.envers.Audited;
|
import org.hibernate.envers.Audited;
|
||||||
import org.jboss.logging.Logger;
|
|
||||||
import org.springframework.data.annotation.CreatedBy;
|
import org.springframework.data.annotation.CreatedBy;
|
||||||
import org.springframework.data.annotation.CreatedDate;
|
import org.springframework.data.annotation.CreatedDate;
|
||||||
import org.springframework.data.annotation.LastModifiedBy;
|
import org.springframework.data.annotation.LastModifiedBy;
|
||||||
import org.springframework.data.annotation.LastModifiedDate;
|
import org.springframework.data.annotation.LastModifiedDate;
|
||||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||||
|
|
||||||
import javax.persistence.CascadeType;
|
import jakarta.persistence.CascadeType;
|
||||||
import javax.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.EntityListeners;
|
import jakarta.persistence.EntityListeners;
|
||||||
import javax.persistence.FetchType;
|
import jakarta.persistence.FetchType;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.GenerationType;
|
import jakarta.persistence.GenerationType;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.NamedQuery;
|
import jakarta.persistence.NamedQuery;
|
||||||
import javax.persistence.OneToMany;
|
import jakarta.persistence.OneToMany;
|
||||||
import javax.persistence.PrePersist;
|
import jakarta.persistence.PrePersist;
|
||||||
import javax.persistence.PreRemove;
|
import jakarta.persistence.PreRemove;
|
||||||
import javax.persistence.PreUpdate;
|
import jakarta.persistence.PreUpdate;
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
|
@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
|
||||||
@ -33,7 +33,7 @@ import java.util.Set;
|
|||||||
@EntityListeners(AuditingEntityListener.class)
|
@EntityListeners(AuditingEntityListener.class)
|
||||||
public class Bar implements Serializable {
|
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 {
|
public enum OPERATION {
|
||||||
INSERT, UPDATE, DELETE;
|
INSERT, UPDATE, DELETE;
|
||||||
|
@ -2,10 +2,10 @@ package com.baeldung.persistence.model;
|
|||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.OneToOne;
|
import jakarta.persistence.OneToOne;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class Child implements Serializable {
|
public class Child implements Serializable {
|
||||||
|
@ -2,20 +2,20 @@ package com.baeldung.persistence.model;
|
|||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
import javax.persistence.CascadeType;
|
import jakarta.persistence.CascadeType;
|
||||||
import javax.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.FetchType;
|
import jakarta.persistence.FetchType;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.GenerationType;
|
import jakarta.persistence.GenerationType;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.JoinColumn;
|
import jakarta.persistence.JoinColumn;
|
||||||
import javax.persistence.ManyToOne;
|
import jakarta.persistence.ManyToOne;
|
||||||
import javax.persistence.NamedNativeQueries;
|
import jakarta.persistence.NamedNativeQueries;
|
||||||
import javax.persistence.NamedNativeQuery;
|
import jakarta.persistence.NamedNativeQuery;
|
||||||
import javax.persistence.NamedStoredProcedureQuery;
|
import jakarta.persistence.NamedStoredProcedureQuery;
|
||||||
import javax.persistence.ParameterMode;
|
import jakarta.persistence.ParameterMode;
|
||||||
import javax.persistence.StoredProcedureParameter;
|
import jakarta.persistence.StoredProcedureParameter;
|
||||||
|
|
||||||
import org.hibernate.envers.Audited;
|
import org.hibernate.envers.Audited;
|
||||||
|
|
||||||
|
@ -2,12 +2,12 @@ package com.baeldung.persistence.model;
|
|||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
import javax.persistence.CascadeType;
|
import jakarta.persistence.CascadeType;
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.JoinColumn;
|
import jakarta.persistence.JoinColumn;
|
||||||
import javax.persistence.OneToOne;
|
import jakarta.persistence.OneToOne;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class Parent implements Serializable {
|
public class Parent implements Serializable {
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
package com.baeldung.persistence.model;
|
package com.baeldung.persistence.model;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class Person {
|
public class Person {
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
package com.baeldung.spring.data.jpa.query;
|
package com.baeldung.spring.data.jpa.query;
|
||||||
|
|
||||||
import javax.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
package com.baeldung.spring.data.jpa.query;
|
package com.baeldung.spring.data.jpa.query;
|
||||||
|
|
||||||
import javax.persistence.EntityManager;
|
import jakarta.persistence.EntityManager;
|
||||||
import javax.persistence.PersistenceContext;
|
import jakarta.persistence.PersistenceContext;
|
||||||
import javax.persistence.criteria.*;
|
import jakarta.persistence.criteria.*;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
@ -4,8 +4,8 @@ import static org.junit.Assert.assertEquals;
|
|||||||
import static org.junit.Assert.assertNotNull;
|
import static org.junit.Assert.assertNotNull;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import javax.persistence.EntityManager;
|
import jakarta.persistence.EntityManager;
|
||||||
import javax.persistence.EntityManagerFactory;
|
import jakarta.persistence.EntityManagerFactory;
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.AfterClass;
|
import org.junit.AfterClass;
|
||||||
@ -30,15 +30,15 @@ import com.baeldung.spring.config.PersistenceTestConfig;
|
|||||||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
public class JPABarAuditIntegrationTest {
|
public class JPABarAuditIntegrationTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class);
|
private static final Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class);
|
||||||
|
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void setUpBeforeClass() throws Exception {
|
public static void setUpBeforeClass() {
|
||||||
logger.info("setUpBeforeClass()");
|
logger.info("setUpBeforeClass()");
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterClass
|
@AfterClass
|
||||||
public static void tearDownAfterClass() throws Exception {
|
public static void tearDownAfterClass(){
|
||||||
logger.info("tearDownAfterClass()");
|
logger.info("tearDownAfterClass()");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,8 +3,8 @@ package com.baeldung.persistence.audit;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import javax.persistence.EntityManager;
|
import jakarta.persistence.EntityManager;
|
||||||
import javax.persistence.EntityManagerFactory;
|
import jakarta.persistence.EntityManagerFactory;
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.AfterClass;
|
import org.junit.AfterClass;
|
||||||
@ -29,7 +29,7 @@ import com.baeldung.spring.config.PersistenceTestConfig;
|
|||||||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
public class SpringDataJPABarAuditIntegrationTest {
|
public class SpringDataJPABarAuditIntegrationTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
|
private static final Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
|
||||||
|
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void setUpBeforeClass() throws Exception {
|
public static void setUpBeforeClass() throws Exception {
|
||||||
@ -37,7 +37,7 @@ public class SpringDataJPABarAuditIntegrationTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@AfterClass
|
@AfterClass
|
||||||
public static void tearDownAfterClass() throws Exception {
|
public static void tearDownAfterClass(){
|
||||||
logger.info("tearDownAfterClass()");
|
logger.info("tearDownAfterClass()");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,7 +17,7 @@ public class FooFixtures {
|
|||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(FooFixtures.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(FooFixtures.class);
|
||||||
|
|
||||||
private SessionFactory sessionFactory;
|
private final SessionFactory sessionFactory;
|
||||||
|
|
||||||
public FooFixtures(final SessionFactory sessionFactory) {
|
public FooFixtures(final SessionFactory sessionFactory) {
|
||||||
super();
|
super();
|
||||||
@ -28,8 +28,8 @@ public class FooFixtures {
|
|||||||
// API
|
// API
|
||||||
|
|
||||||
public void createBars() {
|
public void createBars() {
|
||||||
Session session = null;
|
Session session;
|
||||||
Transaction tx = null;
|
Transaction tx;
|
||||||
session = sessionFactory.openSession();
|
session = sessionFactory.openSession();
|
||||||
tx = session.getTransaction();
|
tx = session.getTransaction();
|
||||||
try {
|
try {
|
||||||
@ -39,13 +39,13 @@ public class FooFixtures {
|
|||||||
bar.setName("Bar_" + i);
|
bar.setName("Bar_" + i);
|
||||||
final Foo foo = new Foo("Foo_" + (i + 120));
|
final Foo foo = new Foo("Foo_" + (i + 120));
|
||||||
foo.setBar(bar);
|
foo.setBar(bar);
|
||||||
session.save(foo);
|
session.persist(foo);
|
||||||
final Foo foo2 = new Foo(null);
|
final Foo foo2 = new Foo(null);
|
||||||
if (i % 2 == 0) {
|
if (i % 2 == 0) {
|
||||||
foo2.setName("LuckyFoo" + (i + 120));
|
foo2.setName("LuckyFoo" + (i + 120));
|
||||||
}
|
}
|
||||||
foo2.setBar(bar);
|
foo2.setBar(bar);
|
||||||
session.save(foo2);
|
session.persist(foo2);
|
||||||
bar.getFooSet().add(foo);
|
bar.getFooSet().add(foo);
|
||||||
bar.getFooSet().add(foo2);
|
bar.getFooSet().add(foo2);
|
||||||
session.merge(bar);
|
session.merge(bar);
|
||||||
@ -53,16 +53,12 @@ public class FooFixtures {
|
|||||||
tx.commit();
|
tx.commit();
|
||||||
session.flush();
|
session.flush();
|
||||||
} catch (final HibernateException he) {
|
} catch (final HibernateException he) {
|
||||||
if (tx != null) {
|
tx.rollback();
|
||||||
tx.rollback();
|
|
||||||
}
|
|
||||||
LOGGER.error("Not able to open session", he);
|
LOGGER.error("Not able to open session", he);
|
||||||
} catch (final Exception e) {
|
} catch (final Exception e) {
|
||||||
LOGGER.error(e.getLocalizedMessage(), e);
|
LOGGER.error(e.getLocalizedMessage(), e);
|
||||||
} finally {
|
} finally {
|
||||||
if (session != null) {
|
session.close();
|
||||||
session.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -86,23 +82,18 @@ public class FooFixtures {
|
|||||||
try {
|
try {
|
||||||
tx.begin();
|
tx.begin();
|
||||||
for (final Foo foo : fooList) {
|
for (final Foo foo : fooList) {
|
||||||
|
session.persist(foo.getBar());
|
||||||
session.save(foo.getBar());
|
session.persist(foo);
|
||||||
session.save(foo);
|
|
||||||
}
|
}
|
||||||
tx.commit();
|
tx.commit();
|
||||||
session.flush();
|
session.flush();
|
||||||
} catch (final HibernateException he) {
|
} catch (final HibernateException he) {
|
||||||
if (tx != null) {
|
tx.rollback();
|
||||||
tx.rollback();
|
|
||||||
}
|
|
||||||
LOGGER.error("Not able to open session", he);
|
LOGGER.error("Not able to open session", he);
|
||||||
} catch (final Exception e) {
|
} catch (final Exception e) {
|
||||||
LOGGER.error(e.getLocalizedMessage(), e);
|
LOGGER.error(e.getLocalizedMessage(), e);
|
||||||
} finally {
|
} finally {
|
||||||
if (session != null) {
|
session.close();
|
||||||
session.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,19 +1,19 @@
|
|||||||
package com.baeldung.persistence.hibernate;
|
package com.baeldung.persistence.hibernate;
|
||||||
|
|
||||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
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.hasSize;
|
||||||
import static org.hamcrest.Matchers.lessThan;
|
import static org.hamcrest.Matchers.lessThan;
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.hibernate.Criteria;
|
|
||||||
import org.hibernate.Query;
|
|
||||||
import org.hibernate.ScrollMode;
|
import org.hibernate.ScrollMode;
|
||||||
import org.hibernate.ScrollableResults;
|
import org.hibernate.ScrollableResults;
|
||||||
import org.hibernate.Session;
|
import org.hibernate.Session;
|
||||||
import org.hibernate.SessionFactory;
|
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.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
@ -28,6 +28,8 @@ import com.baeldung.persistence.service.IFooService;
|
|||||||
import com.baeldung.spring.config.PersistenceTestConfig;
|
import com.baeldung.spring.config.PersistenceTestConfig;
|
||||||
import com.google.common.collect.Lists;
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
public class FooPaginationPersistenceIntegrationTest {
|
public class FooPaginationPersistenceIntegrationTest {
|
||||||
@ -40,8 +42,6 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||||||
|
|
||||||
private Session session;
|
private Session session;
|
||||||
|
|
||||||
// tests
|
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public final void before() {
|
public final void before() {
|
||||||
final int minimalNumberOfEntities = 25;
|
final int minimalNumberOfEntities = 25;
|
||||||
@ -59,20 +59,17 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||||||
session.close();
|
session.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenContextIsBootstrapped_thenNoExceptions() {
|
public final void whenContextIsBootstrapped_thenNoExceptions() {
|
||||||
//
|
//
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenRetrievingPaginatedEntities_thenCorrectSize() {
|
public final void whenRetrievingPaginatedEntities_thenCorrectSize() {
|
||||||
final int pageNumber = 1;
|
final int pageNumber = 1;
|
||||||
final int pageSize = 10;
|
final int pageSize = 10;
|
||||||
|
|
||||||
final Query query = session.createQuery("From Foo");
|
final Query<Foo> query = session.createQuery("From Foo",Foo.class);
|
||||||
query.setFirstResult((pageNumber - 1) * pageSize);
|
query.setFirstResult((pageNumber - 1) * pageSize);
|
||||||
query.setMaxResults(pageSize);
|
query.setMaxResults(pageSize);
|
||||||
final List<Foo> fooList = query.list();
|
final List<Foo> fooList = query.list();
|
||||||
@ -80,19 +77,18 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||||||
assertThat(fooList, hasSize(pageSize));
|
assertThat(fooList, hasSize(pageSize));
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenRetrievingAllPages_thenCorrect() {
|
public final void whenRetrievingAllPages_thenCorrect() {
|
||||||
int pageNumber = 1;
|
int pageNumber = 1;
|
||||||
final int pageSize = 10;
|
final int pageSize = 10;
|
||||||
|
|
||||||
final String countQ = "Select count (f.id) from Foo f";
|
final String countQ = "Select count (f.id) from Foo f";
|
||||||
final Query countQuery = session.createQuery(countQ);
|
final Query<Long> countQuery = session.createQuery(countQ, Long.class);
|
||||||
final Long countResult = (Long) countQuery.uniqueResult();
|
final Long countResult = (Long) countQuery.uniqueResult();
|
||||||
|
|
||||||
final List<Foo> fooList = Lists.newArrayList();
|
final List<Foo> fooList = Lists.newArrayList();
|
||||||
int totalEntities = 0;
|
int totalEntities = 0;
|
||||||
final Query query = session.createQuery("From Foo");
|
final Query<Foo> query = session.createQuery("From Foo", Foo.class);
|
||||||
while (totalEntities < countResult) {
|
while (totalEntities < countResult) {
|
||||||
query.setFirstResult((pageNumber - 1) * pageSize);
|
query.setFirstResult((pageNumber - 1) * pageSize);
|
||||||
query.setMaxResults(pageSize);
|
query.setMaxResults(pageSize);
|
||||||
@ -102,17 +98,16 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenRetrievingLastPage_thenCorrectSize() {
|
public final void whenRetrievingLastPage_thenCorrectSize() {
|
||||||
final int pageSize = 10;
|
final int pageSize = 10;
|
||||||
|
|
||||||
final String countQ = "Select count (f.id) from Foo f";
|
final String countQ = "Select count (f.id) from Foo f";
|
||||||
final Query countQuery = session.createQuery(countQ);
|
final Query<Long> countQuery = session.createQuery(countQ, Long.class);
|
||||||
final Long countResults = (Long) countQuery.uniqueResult();
|
final Long countResults = countQuery.uniqueResult();
|
||||||
final int lastPageNumber = (int) (Math.ceil(countResults / pageSize));
|
final int lastPageNumber = (int) (Math.ceil(countResults / pageSize));
|
||||||
|
|
||||||
final Query selectQuery = session.createQuery("From Foo");
|
final Query<Foo> selectQuery = session.createQuery("From Foo",Foo.class);
|
||||||
selectQuery.setFirstResult((lastPageNumber - 1) * pageSize);
|
selectQuery.setFirstResult((lastPageNumber - 1) * pageSize);
|
||||||
selectQuery.setMaxResults(pageSize);
|
selectQuery.setMaxResults(pageSize);
|
||||||
final List<Foo> lastPage = selectQuery.list();
|
final List<Foo> lastPage = selectQuery.list();
|
||||||
@ -126,9 +121,9 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||||||
public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() {
|
public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() {
|
||||||
final int pageSize = 10;
|
final int pageSize = 10;
|
||||||
final String hql = "FROM Foo f order by f.name";
|
final String hql = "FROM Foo f order by f.name";
|
||||||
final Query query = session.createQuery(hql);
|
final Query<Foo> query = session.createQuery(hql,Foo.class);
|
||||||
|
|
||||||
final ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY);
|
final ScrollableResults<Foo> resultScroll = query.scroll(ScrollMode.FORWARD_ONLY);
|
||||||
|
|
||||||
// resultScroll.last();
|
// resultScroll.last();
|
||||||
// final int totalResults = resultScroll.getRowNumber() + 1;
|
// final int totalResults = resultScroll.getRowNumber() + 1;
|
||||||
@ -138,7 +133,7 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||||||
final List<Foo> fooPage = Lists.newArrayList();
|
final List<Foo> fooPage = Lists.newArrayList();
|
||||||
int i = 0;
|
int i = 0;
|
||||||
while (pageSize > i++) {
|
while (pageSize > i++) {
|
||||||
fooPage.add((Foo) resultScroll.get(0));
|
fooPage.add((Foo) resultScroll.get());
|
||||||
if (!resultScroll.next()) {
|
if (!resultScroll.next()) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -147,36 +142,42 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||||||
assertThat(fooPage, hasSize(lessThan(10 + 1)));
|
assertThat(fooPage, hasSize(lessThan(10 + 1)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingTheCriteriaApi_whenRetrievingFirstPage_thenCorrect() {
|
public final void givenUsingTheCriteriaApi_whenRetrievingFirstPage_thenCorrect() {
|
||||||
final int pageSize = 10;
|
final int pageSize = 10;
|
||||||
|
|
||||||
final Criteria criteria = session.createCriteria(Foo.class);
|
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||||
criteria.setFirstResult(0);
|
selectQuery.from(Foo.class);
|
||||||
criteria.setMaxResults(pageSize);
|
|
||||||
final List<Foo> firstPage = criteria.list();
|
SelectionQuery<Foo> query = session.createQuery(selectQuery);
|
||||||
|
query.setFirstResult(0);
|
||||||
|
query.setMaxResults(pageSize);
|
||||||
|
final List<Foo> firstPage = query.list();
|
||||||
|
|
||||||
assertThat(firstPage, hasSize(pageSize));
|
assertThat(firstPage, hasSize(pageSize));
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() {
|
public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() {
|
||||||
final Criteria criteriaCount = session.createCriteria(Foo.class);
|
|
||||||
criteriaCount.setProjection(Projections.rowCount());
|
HibernateCriteriaBuilder qb = session.getCriteriaBuilder();
|
||||||
final Long count = (Long) criteriaCount.uniqueResult();
|
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
|
||||||
|
cq.select(qb.count(cq.from(Foo.class)));
|
||||||
|
final Long count = session.createQuery(cq).getSingleResult();
|
||||||
|
|
||||||
int pageNumber = 1;
|
int pageNumber = 1;
|
||||||
final int pageSize = 10;
|
final int pageSize = 10;
|
||||||
final List<Foo> fooList = Lists.newArrayList();
|
final List<Foo> fooList = Lists.newArrayList();
|
||||||
|
|
||||||
final Criteria criteria = session.createCriteria(Foo.class);
|
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||||
|
selectQuery.from(Foo.class);
|
||||||
|
SelectionQuery<Foo> query = session.createQuery(selectQuery);
|
||||||
|
|
||||||
int totalEntities = 0;
|
int totalEntities = 0;
|
||||||
while (totalEntities < count.intValue()) {
|
while (totalEntities < count.intValue()) {
|
||||||
criteria.setFirstResult((pageNumber - 1) * pageSize);
|
query.setFirstResult((pageNumber - 1) * pageSize);
|
||||||
criteria.setMaxResults(pageSize);
|
query.setMaxResults(pageSize);
|
||||||
fooList.addAll(criteria.list());
|
fooList.addAll(query.list());
|
||||||
totalEntities = fooList.size();
|
totalEntities = fooList.size();
|
||||||
pageNumber++;
|
pageNumber++;
|
||||||
}
|
}
|
||||||
|
@ -2,15 +2,17 @@ package com.baeldung.persistence.hibernate;
|
|||||||
|
|
||||||
import static org.junit.Assert.assertNull;
|
import static org.junit.Assert.assertNull;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import org.hibernate.Criteria;
|
|
||||||
import org.hibernate.NullPrecedence;
|
|
||||||
import org.hibernate.Query;
|
|
||||||
import org.hibernate.Session;
|
import org.hibernate.Session;
|
||||||
import org.hibernate.SessionFactory;
|
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.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
@ -26,6 +28,8 @@ import com.baeldung.persistence.model.Bar;
|
|||||||
import com.baeldung.persistence.model.Foo;
|
import com.baeldung.persistence.model.Foo;
|
||||||
import com.baeldung.spring.config.PersistenceTestConfig;
|
import com.baeldung.spring.config.PersistenceTestConfig;
|
||||||
|
|
||||||
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@ -91,7 +95,7 @@ public class FooSortingPersistenceIntegrationTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() {
|
public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() {
|
||||||
final String hql = "FROM Foo f ORDER BY f.name ASC";
|
final String hql = "FROM Foo f ORDER BY f.name ASC";
|
||||||
final Query query = session.createQuery(hql);
|
Query<Foo> query = session.createQuery(hql, Foo.class);
|
||||||
final List<Foo> fooList = query.list();
|
final List<Foo> fooList = query.list();
|
||||||
for (final Foo foo : fooList) {
|
for (final Foo foo : fooList) {
|
||||||
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
|
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
|
||||||
@ -101,7 +105,7 @@ public class FooSortingPersistenceIntegrationTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void whenHQlSortingByMultipleAttributes_thenSortedResults() {
|
public final void whenHQlSortingByMultipleAttributes_thenSortedResults() {
|
||||||
final String hql = "FROM Foo f ORDER BY f.name, f.id";
|
final String hql = "FROM Foo f ORDER BY f.name, f.id";
|
||||||
final Query query = session.createQuery(hql);
|
Query<Foo> query = session.createQuery(hql, Foo.class);
|
||||||
final List<Foo> fooList = query.list();
|
final List<Foo> fooList = query.list();
|
||||||
for (final Foo foo : fooList) {
|
for (final Foo foo : fooList) {
|
||||||
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
|
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
|
||||||
@ -111,7 +115,7 @@ public class FooSortingPersistenceIntegrationTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() {
|
public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() {
|
||||||
final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC";
|
final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC";
|
||||||
final Query query = session.createQuery(hql);
|
Query<Foo> query = session.createQuery(hql, Foo.class);
|
||||||
final List<Foo> fooList = query.list();
|
final List<Foo> fooList = query.list();
|
||||||
for (final Foo foo : fooList) {
|
for (final Foo foo : fooList) {
|
||||||
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
|
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
|
||||||
@ -120,9 +124,12 @@ public class FooSortingPersistenceIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() {
|
public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() {
|
||||||
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
|
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||||
criteria.addOrder(Order.asc("id"));
|
selectQuery.from(Foo.class);
|
||||||
final List<Foo> fooList = criteria.list();
|
Query<Foo> query = session.createQuery(selectQuery);
|
||||||
|
|
||||||
|
query.setOrder(Collections.singletonList(Order.asc(Foo.class,"id")));
|
||||||
|
final List<Foo> fooList = query.list();
|
||||||
for (final Foo foo : fooList) {
|
for (final Foo foo : fooList) {
|
||||||
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
||||||
}
|
}
|
||||||
@ -130,10 +137,16 @@ public class FooSortingPersistenceIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() {
|
public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() {
|
||||||
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
|
|
||||||
criteria.addOrder(Order.asc("name"));
|
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||||
criteria.addOrder(Order.asc("id"));
|
selectQuery.from(Foo.class);
|
||||||
final List<Foo> fooList = criteria.list();
|
Query<Foo> query = session.createQuery(selectQuery);
|
||||||
|
|
||||||
|
List<Order<? super Foo>> orderBy = new ArrayList<>(2);
|
||||||
|
orderBy.add(Order.asc(Foo.class,"name"));
|
||||||
|
orderBy.add(Order.asc(Foo.class,"id"));
|
||||||
|
query.setOrder(orderBy);
|
||||||
|
final List<Foo> fooList = query.list();
|
||||||
for (final Foo foo : fooList) {
|
for (final Foo foo : fooList) {
|
||||||
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
||||||
}
|
}
|
||||||
@ -141,9 +154,15 @@ public class FooSortingPersistenceIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() {
|
public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() {
|
||||||
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
|
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||||
criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST));
|
selectQuery.from(Foo.class);
|
||||||
final List<Foo> fooList = criteria.list();
|
Query<Foo> query = session.createQuery(selectQuery);
|
||||||
|
|
||||||
|
List<Order<? super Foo>> orderBy = new ArrayList<>(2);
|
||||||
|
orderBy.add(Order.by(Foo.class,"name", SortDirection.ASCENDING, NullPrecedence.LAST));
|
||||||
|
query.setOrder(orderBy);
|
||||||
|
|
||||||
|
final List<Foo> fooList = query.list();
|
||||||
assertNull(fooList.get(fooList.toArray().length - 1).getName());
|
assertNull(fooList.get(fooList.toArray().length - 1).getName());
|
||||||
for (final Foo foo : fooList) {
|
for (final Foo foo : fooList) {
|
||||||
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
||||||
@ -152,9 +171,15 @@ public class FooSortingPersistenceIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() {
|
public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() {
|
||||||
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
|
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||||
criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST));
|
selectQuery.from(Foo.class);
|
||||||
final List<Foo> fooList = criteria.list();
|
Query<Foo> query = session.createQuery(selectQuery);
|
||||||
|
|
||||||
|
List<Order<? super Foo>> orderBy = new ArrayList<>(2);
|
||||||
|
orderBy.add(Order.by(Foo.class,"name", SortDirection.ASCENDING, NullPrecedence.FIRST));
|
||||||
|
query.setOrder(orderBy);
|
||||||
|
|
||||||
|
final List<Foo> fooList = query.list();
|
||||||
assertNull(fooList.get(0).getName());
|
assertNull(fooList.get(0).getName());
|
||||||
for (final Foo foo : fooList) {
|
for (final Foo foo : fooList) {
|
||||||
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
||||||
@ -164,7 +189,7 @@ public class FooSortingPersistenceIntegrationTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void whenSortingBars_thenBarsWithSortedFoos() {
|
public final void whenSortingBars_thenBarsWithSortedFoos() {
|
||||||
final String hql = "FROM Bar b ORDER BY b.id";
|
final String hql = "FROM Bar b ORDER BY b.id";
|
||||||
final Query query = session.createQuery(hql);
|
final Query<Bar> query = session.createQuery(hql, Bar.class);
|
||||||
final List<Bar> barList = query.list();
|
final List<Bar> barList = query.list();
|
||||||
for (final Bar bar : barList) {
|
for (final Bar bar : barList) {
|
||||||
final Set<Foo> fooSet = bar.getFooSet();
|
final Set<Foo> fooSet = bar.getFooSet();
|
||||||
|
@ -5,14 +5,14 @@ import static org.junit.Assert.assertEquals;
|
|||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import javax.persistence.EntityManager;
|
import jakarta.persistence.EntityManager;
|
||||||
import javax.persistence.EntityManagerFactory;
|
import jakarta.persistence.EntityManagerFactory;
|
||||||
import javax.persistence.StoredProcedureQuery;
|
import jakarta.persistence.StoredProcedureQuery;
|
||||||
|
|
||||||
import org.hibernate.Query;
|
|
||||||
import org.hibernate.Session;
|
import org.hibernate.Session;
|
||||||
import org.hibernate.SessionFactory;
|
import org.hibernate.SessionFactory;
|
||||||
import org.hibernate.exception.SQLGrammarException;
|
import org.hibernate.exception.SQLGrammarException;
|
||||||
|
import org.hibernate.query.Query;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Assume;
|
import org.junit.Assume;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
@ -59,22 +59,22 @@ public class FooStoredProceduresLiveTest {
|
|||||||
|
|
||||||
private boolean getFoosByNameExists() {
|
private boolean getFoosByNameExists() {
|
||||||
try {
|
try {
|
||||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetFoosByName()",Foo.class);
|
||||||
sqlQuery.list();
|
sqlQuery.list();
|
||||||
return true;
|
return true;
|
||||||
} catch (SQLGrammarException e) {
|
} catch (SQLGrammarException e) {
|
||||||
LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e);
|
LOGGER.error("WARNING : GetFoosByName() Procedure may be missing ", e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean getAllFoosExists() {
|
private boolean getAllFoosExists() {
|
||||||
try {
|
try {
|
||||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetAllFoos()",Foo.class);
|
||||||
sqlQuery.list();
|
sqlQuery.list();
|
||||||
return true;
|
return true;
|
||||||
} catch (SQLGrammarException e) {
|
} catch (SQLGrammarException e) {
|
||||||
LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e);
|
LOGGER.error("WARNING : GetAllFoos() Procedure may be missing ", e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -90,9 +90,9 @@ public class FooStoredProceduresLiveTest {
|
|||||||
|
|
||||||
fooService.create(new Foo(randomAlphabetic(6)));
|
fooService.create(new Foo(randomAlphabetic(6)));
|
||||||
|
|
||||||
// Stored procedure getAllFoos using createSQLQuery
|
// Stored procedure getAllFoos using createQuery
|
||||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetAllFoos()", Foo.class);
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
List<Foo> allFoos = sqlQuery.list();
|
List<Foo> allFoos = sqlQuery.list();
|
||||||
for (Foo foo : allFoos) {
|
for (Foo foo : allFoos) {
|
||||||
LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
|
LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
|
||||||
@ -100,8 +100,8 @@ public class FooStoredProceduresLiveTest {
|
|||||||
assertEquals(allFoos.size(), fooService.findAll().size());
|
assertEquals(allFoos.size(), fooService.findAll().size());
|
||||||
|
|
||||||
// Stored procedure getAllFoos using a Named Query
|
// Stored procedure getAllFoos using a Named Query
|
||||||
Query namedQuery = session.getNamedQuery("callGetAllFoos");
|
Query<Foo> namedQuery = session.createNamedQuery("callGetAllFoos", Foo.class);
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
List<Foo> allFoos2 = namedQuery.list();
|
List<Foo> allFoos2 = namedQuery.list();
|
||||||
for (Foo foo : allFoos2) {
|
for (Foo foo : allFoos2) {
|
||||||
LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
|
LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
|
||||||
@ -110,6 +110,7 @@ public class FooStoredProceduresLiveTest {
|
|||||||
|
|
||||||
StoredProcedureQuery spQuery =
|
StoredProcedureQuery spQuery =
|
||||||
entityManager.createNamedStoredProcedureQuery("GetAllFoos");
|
entityManager.createNamedStoredProcedureQuery("GetAllFoos");
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
List<Foo> allFoos3 = spQuery.getResultList();
|
List<Foo> allFoos3 = spQuery.getResultList();
|
||||||
for (Foo foo : allFoos3) {
|
for (Foo foo : allFoos3) {
|
||||||
LOGGER.info("getAllFoos() StoredProcedureQuery result : {}", foo.getName());
|
LOGGER.info("getAllFoos() StoredProcedureQuery result : {}", foo.getName());
|
||||||
@ -124,16 +125,16 @@ public class FooStoredProceduresLiveTest {
|
|||||||
fooService.create(new Foo("NewFooName"));
|
fooService.create(new Foo("NewFooName"));
|
||||||
|
|
||||||
// Stored procedure getFoosByName using createSQLQuery()
|
// Stored procedure getFoosByName using createSQLQuery()
|
||||||
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName");
|
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetFoosByName(:fooName)", Foo.class).setParameter("fooName", "NewFooName");
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
List<Foo> allFoosByName = sqlQuery.list();
|
List<Foo> allFoosByName = sqlQuery.list();
|
||||||
for (Foo foo : allFoosByName) {
|
for (Foo foo : allFoosByName) {
|
||||||
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
|
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stored procedure getFoosByName using getNamedQuery()
|
// Stored procedure getFoosByName using getNamedQuery()
|
||||||
Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName");
|
Query<Foo> namedQuery = session.createQuery("callGetFoosByName", Foo.class).setParameter("fooName", "NewFooName");
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
List<Foo> allFoosByName2 = namedQuery.list();
|
List<Foo> allFoosByName2 = namedQuery.list();
|
||||||
for (Foo foo : allFoosByName2) {
|
for (Foo foo : allFoosByName2) {
|
||||||
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
|
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
|
||||||
@ -142,6 +143,7 @@ public class FooStoredProceduresLiveTest {
|
|||||||
StoredProcedureQuery spQuery = entityManager.
|
StoredProcedureQuery spQuery = entityManager.
|
||||||
createNamedStoredProcedureQuery("GetFoosByName")
|
createNamedStoredProcedureQuery("GetFoosByName")
|
||||||
.setParameter("fooName", "NewFooName");
|
.setParameter("fooName", "NewFooName");
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
List<Foo> allFoosByName3 = spQuery.getResultList();
|
List<Foo> allFoosByName3 = spQuery.getResultList();
|
||||||
assertEquals(1, allFoosByName3.size());
|
assertEquals(1, allFoosByName3.size());
|
||||||
for (Foo foo : allFoosByName3) {
|
for (Foo foo : allFoosByName3) {
|
||||||
|
@ -19,7 +19,7 @@ public class Library {
|
|||||||
private List<String> addresses = new ArrayList<>();
|
private List<String> addresses = new ArrayList<>();
|
||||||
|
|
||||||
@ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
|
@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)
|
@Column(name = "book", nullable = false)
|
||||||
private List<String> books = new ArrayList<>();
|
private List<String> books = new ArrayList<>();
|
||||||
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||||
spring.jpa.hibernate.ddl-auto=none
|
spring.jpa.hibernate.ddl-auto=none
|
||||||
|
spring.jpa.generate-ddl=true
|
||||||
logging.level.org.hibernate.SQL=DEBUG
|
logging.level.org.hibernate.SQL=DEBUG
|
||||||
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
|
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
|
||||||
|
@ -21,13 +21,13 @@ public class BookPagingAndSortingRepositoryIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDbContainsBooks_whenfindBooksByAuthor_thenReturnBooksByAuthor() {
|
public void givenDbContainsBooks_whenfindBooksByAuthor_thenReturnBooksByAuthor() {
|
||||||
Book book1 = new Book("Spring Data", "John Doe", "1234567890");
|
Book book1 = new Book("Spring Data", "John Miller", "1234567890");
|
||||||
Book book2 = new Book("Spring Data 2", "John Doe", "1234567891");
|
Book book2 = new Book("Spring Data 2", "John Miller", "1234567891");
|
||||||
Book book3 = new Book("Spring Data 3", "John Doe", "1234567892");
|
Book book3 = new Book("Spring Data 3", "John Miller", "1234567892");
|
||||||
bookPagingAndSortingRepository.saveAll(Arrays.asList(book1, book2, book3));
|
bookPagingAndSortingRepository.saveAll(Arrays.asList(book1, book2, book3));
|
||||||
|
|
||||||
Pageable pageable = PageRequest.of(0, 2, Sort.by("title").descending());
|
Pageable pageable = PageRequest.of(0, 2, Sort.by("title").descending());
|
||||||
List<Book> books = bookPagingAndSortingRepository.findBooksByAuthor("John Doe", pageable);
|
List<Book> books = bookPagingAndSortingRepository.findBooksByAuthor("John Miller", pageable);
|
||||||
Assertions.assertEquals(2, books.size());
|
Assertions.assertEquals(2, books.size());
|
||||||
Assertions.assertEquals(book3.getId(), books.get(0).getId());
|
Assertions.assertEquals(book3.getId(), books.get(0).getId());
|
||||||
Assertions.assertEquals(book2.getId(), books.get(1).getId());
|
Assertions.assertEquals(book2.getId(), books.get(1).getId());
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user