Merge branch 'eugenp:master' into PR-7135

This commit is contained in:
parthiv39731 2023-10-25 16:08:15 +05:30 committed by GitHub
commit f8bad9e049
263 changed files with 3777 additions and 1121 deletions

View File

@ -4,4 +4,5 @@
- [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)
- [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)

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-poi-3</artifactId>
<version>0.0.1-SNAPSHOT</version>

View File

@ -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>

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}
}

View File

@ -1 +0,0 @@
aws.s3bucket=baeldung-documents;

View File

@ -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));
}
}

View File

@ -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"));
}
}

View File

@ -11,3 +11,4 @@ This module contains articles about Simple Storage Service (S3) on AWS
- [Listing All AWS S3 Objects in a Bucket Using Java](https://www.baeldung.com/java-aws-s3-list-bucket-objects)
- [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object)
- [How To Rename Files and Folders in Amazon S3](https://www.baeldung.com/java-amazon-s3-rename-files-folders)
- [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object)

View File

@ -45,6 +45,13 @@ public class S3Application {
new File("/Users/user/Document/hello.txt")
);
s3Service.updateObject(
AWS_BUCKET,
"Document/hello2.txt",
new File("/Users/user/Document/hello2.txt")
);
//listing objects
s3Service.listObjects(AWS_BUCKET);

View File

@ -24,6 +24,7 @@ import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
@ -99,7 +100,13 @@ class S3Service {
.key(key)
.build();
return s3Client.putObject(request, Path.of(file.toURI()) );
return s3Client.putObject(request, Path.of(file.toURI()));
}
//updating object
public PutObjectResponse updateObject(String bucketName, String key, java.io.File file) {
return this.putObject(bucketName, key, file);
}
//listing objects
@ -110,6 +117,7 @@ class S3Service {
ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request);
for(S3Object os : listObjectsV2Response.contents()) {
System.out.println(os.key());
}
}

View File

@ -11,6 +11,8 @@ import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.io.File;
import java.nio.file.Path;
import java.util.Collections;
import software.amazon.awssdk.services.s3.S3Client;
@ -23,6 +25,7 @@ import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
class S3ServiceIntegrationTest {
@ -38,6 +41,8 @@ class S3ServiceIntegrationTest {
private final String AWS_BUCKET = "baeldung-tutorial-s3";
private File file = new File("/Users/user/Document/hello2.txt");
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
@ -75,6 +80,17 @@ class S3ServiceIntegrationTest {
verify(s3Client).createBucket(bucketRequest);
}
@Test
void whenVerifyingUploadOfS3Object_thenCorrect() {
PutObjectRequest request = PutObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(KEY_NAME)
.build();
s3Service.putObject(BUCKET_NAME, KEY_NAME, file);
verify(s3Client).putObject(request, Path.of(file.toURI()) );
}
@Test
void whenVerifyingListBuckets_thenCorrect() {
when(s3Client.listBuckets()).thenReturn(ListBucketsResponse.builder().buckets(Collections.emptyList()).build());

View File

@ -28,7 +28,6 @@
<module>aws-miscellaneous</module>
<module>aws-reactive</module>
<module>aws-s3</module>
<module>aws-s3-update-object</module>
</modules>
<properties>

View File

@ -8,3 +8,4 @@
- [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)
- [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)

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Deprecate Finalization in Java 18](https://www.baeldung.com/java-18-deprecate-finalization)

View File

@ -1,7 +1,7 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-21</artifactId>
<name>core-java-21</name>
@ -12,12 +12,6 @@
<version>0.0.1-SNAPSHOT</version>
</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>
<plugins>
<plugin>
@ -44,4 +38,10 @@
</plugins>
</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>

View File

@ -1,7 +1,7 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-arrays-operations-advanced-2</artifactId>
<name>core-java-arrays-operations-advanced-2</name>

View File

@ -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"));
}
}

View File

@ -1,17 +1,17 @@
<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"
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>core-java-collections-array-list-2</artifactId>
<name>core-java-collections-array-list-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
@ -24,7 +24,7 @@
</plugin>
</plugins>
</build>
<properties>
<maven-compiler-plugin.source>17</maven-compiler-plugin.source>
<maven-compiler-plugin.target>17</maven-compiler-plugin.target>

View File

@ -4,3 +4,4 @@ This module contains articles about conversions among Collection types in Java.
### Relevant Articles:
- [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)

View File

@ -71,4 +71,15 @@ public class ListOfListsUnitTest {
assertThat(listOfLists.get(2)).containsExactly("Slack", "Zoom", "Microsoft Teams", "Telegram");
printListOfLists(listOfLists);
}
}
@Test
void givenListOfLists_whenGettingSizeOfSubListsAndSizeOfElements_thenGetExpectedResults() throws URISyntaxException, IOException {
List<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);
}
}

View File

@ -1,7 +1,7 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-list-6</artifactId>
<name>core-java-collections-list-6</name>
@ -12,4 +12,5 @@
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>

View File

@ -9,3 +9,4 @@
- [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)
- [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)

View File

@ -1 +1,2 @@
## Relevant Articles
## Relevant Articles
- [Difference Between putIfAbsent() and computeIfAbsent() in Javas Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent)

View File

@ -73,6 +73,11 @@
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
</dependencies>
</project>
</project>

View File

@ -10,18 +10,26 @@ import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class WriteHashmaptoCVSFileUnitTest {
public Map<String, String> employeeData;
@Test
public void givenEmployeeData_whenWriteToCSV_thenCSVFileIsCreated() {
Map<String, String> employeeData = new HashMap<>();
public WriteHashmaptoCVSFileUnitTest() {
employeeData = new HashMap<>();
employeeData.put("Name", "John Doe");
employeeData.put("Title", "Software Engineer");
employeeData.put("Department", "Engineering");
employeeData.put("Salary", "75000");
}
@Test
public void givenEmployeeData_whenWriteToCSVUsingFileWriter_thenCSVFileIsCreated() {
try (FileWriter csvWriter = new FileWriter("employee_data.csv")) {
// Write header row
csvWriter.append("Name,Title,Department,Salary\n");
@ -40,23 +48,19 @@ public class WriteHashmaptoCVSFileUnitTest {
}
@Test
public void givenCSVFile_whenRead_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"));
public void givenCSVFile_whenWriteToCSVUsingApacheCommons_thenContentsMatchExpected() {
// Define the expected CSV content
String expectedCsvContent = "Name,Title,Department,Salary\n" +
"John Doe,Software Engineer,Engineering,75000\n";
try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter("employee_data2.csv"), CSVFormat.DEFAULT)) {
// Write header row
csvPrinter.printRecord("Name", "Title", "Department", "Salary");
// Compare the actual content with the expected content
assertEquals(expectedCsvContent, actualCsvContent.toString());
System.out.println("CSV file created successfully.");
// Write data row
csvPrinter.printRecord(employeeData.get("Name"), employeeData.get("Title"), employeeData.get("Department"), employeeData.get("Salary"));
} catch (IOException e) {
e.printStackTrace();
}
// Ensure the CSV file exists
assertTrue(new File("employee_data2.csv").exists());
}
}

View File

@ -20,8 +20,9 @@ public class Main {
System.out.println("General exception");
}
checkedException();
checkedExceptionWithTryCatch();
checkedExceptionWithThrows();
divideByZero();
}
private static void checkedExceptionWithThrows() throws FileNotFoundException {
@ -29,7 +30,7 @@ public class Main {
FileInputStream stream = new FileInputStream(file);
}
private static void checkedException() {
private static void checkedExceptionWithTryCatch() {
File file = new File("not_existing_file.txt");
try {
FileInputStream stream = new FileInputStream(file);
@ -37,5 +38,11 @@ public class Main {
e.printStackTrace();
}
}
private static void divideByZero() {
int numerator = 1;
int denominator = 0;
int result = numerator / denominator;
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.exceptions.throwvsthrows;
public class NullOrEmptyException extends RuntimeException {
public NullOrEmptyException(String errorMessage) {
super(errorMessage);
}
}

View File

@ -4,5 +4,6 @@ This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [Get File Extension From MIME Type in Java](https://www.baeldung.com/java-mime-type-file-extension)
- [How to Remove Line Breaks From a File in Java](https://www.baeldung.com/java-file-remove-line-breaks)
- [[<-- Prev]](/core-java-modules/core-java-io-4)

View File

@ -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);
}
}
}

View File

@ -3,7 +3,10 @@ package com.baeldung.size;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -62,4 +65,24 @@ public class JavaFileSizeUnitTest {
final long length = file.length();
return length;
}
@Test
public void whenGetFileSizeUsingFileInputStream_thenCorrect() throws IOException {
try (FileInputStream fis = new FileInputStream(filePath)) {
long result = fis.getChannel().size();
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, result);
}
}
@Test
public void whenGetFileSizeUsingUrlAndInputStream_thenCorrect() throws IOException {
File file = new File(filePath);
URL url = file.toURI().toURL();
try (InputStream stream = url.openStream()) {
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, stream.available());
}
}
}

View File

@ -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)
- [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)
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)

View File

@ -12,4 +12,5 @@
- [Java Program to Print Pascals Triangle](https://www.baeldung.com/java-pascal-triangle)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [Clamp Function in Java](https://www.baeldung.com/java-clamp-function)
- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)

View File

@ -1,7 +1,5 @@
package com.baeldung.magicsquare;
import org.junit.platform.commons.util.StringUtils;
import java.util.stream.IntStream;
public class MagicSquare {

View File

@ -1,2 +0,0 @@
## Relevant Articles
- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square)

View File

@ -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)
- [Law of Demeter in Java](https://www.baeldung.com/java-demeter-law)
- [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)

View File

@ -6,4 +6,5 @@
- [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)
- [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)

View File

@ -2,3 +2,5 @@
- [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 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)

View File

@ -3,5 +3,5 @@
This module contains articles about working with the operating system (OS) in Java
### Relevant Articles:
- [How to Detect the Username Using Java](https://www.baeldung.com/java-get-username)

View File

@ -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)
- [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)
- [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.

View File

@ -1,2 +1,2 @@
### 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)

View File

@ -1,7 +1,7 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-security-4</artifactId>
<name>core-java-security-4</name>

View File

@ -6,19 +6,23 @@ import java.util.function.BinaryOperator;
import java.util.stream.Collector;
class SkippingCollector {
private static final BinaryOperator<SkippingCollector> IGNORE_COMBINE = (a, b) -> a;
private final int skip;
private final List<String> list = new ArrayList<>();
private int currentIndex = 0;
private SkippingCollector(int skip) {
this.skip = skip;
}
private void accept(String item) {
final int index = ++currentIndex % skip;
if (index == 0)
if (index == 0) {
list.add(item);
}
}
private List<String> getResult() {
return list;
}

View File

@ -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));
}
}

View File

@ -3,7 +3,11 @@ package com.baeldung.skippingelements;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
@ -14,21 +18,22 @@ class SkippingElementsUnitTest {
private static Stream<Arguments> testSource() {
return Stream.of(
Arguments.of(
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
Stream.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
"Thirty One", "Thirty Two", "Thirty Three"),
List.of("Three", "Six", "Nine", "Twelve", "Fifteen", "Eighteen", "Twenty One", "Twenty Four", "Twenty Seven", "Thirty", "Thirty Three"),
List.of("Three", "Six", "Nine", "Twelve", "Fifteen", "Eighteen", "Twenty One", "Twenty Four", "Twenty Seven", "Thirty",
"Thirty Three"),
3),
Arguments.of(
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
Stream.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
"Thirty One", "Thirty Two", "Thirty Three"),
List.of("Five", "Ten", "Fifteen", "Twenty", "Twenty Five", "Thirty"),
5),
Arguments.of(
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
Stream.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
"Thirty One", "Thirty Two", "Thirty Three"),
@ -38,29 +43,29 @@ class SkippingElementsUnitTest {
"Thirty One", "Thirty Two", "Thirty Three"),
1),
Arguments.of(
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
Stream.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
List.of("Wednesday", "Saturday"),
3),
Arguments.of(
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
Stream.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
List.of("Friday"),
5),
Arguments.of(
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
Stream.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
1),
Arguments.of(
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
Stream.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
"December"),
List.of("March", "June", "September", "December"),
3),
Arguments.of(
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
Stream.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
"December"),
List.of("May", "October"),
5),
Arguments.of(
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
Stream.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
"December"),
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
"December"),
@ -70,45 +75,73 @@ class SkippingElementsUnitTest {
@ParameterizedTest
@MethodSource("testSource")
void givenListSkipNthElementInListWithFilterTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
final List<String> actual = SkippingElements.skipNthElementInListWithFilter(input, n);
void givenListSkipNthElementInListWithFilterTestShouldFilterNthElement(Stream<String> input, List<String> expected, int 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);
}
@ParameterizedTest
@MethodSource("testSource")
void givenListSkipNthElementInListWithIterateTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
final List<String> actual = SkippingElements.skipNthElementInListWithIterate(input, n);
void givenListSkipNthElementInListWithIterateTestShouldFilterNthElement(Stream<String> input, List<String> expected, int 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);
}
@ParameterizedTest
@MethodSource("testSource")
void givenListSkipNthElementInListWithSublistTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
final List<String> actual = SkippingElements.skipNthElementInListWithSublist(input, n);
void givenListSkipNthElementInListWithSublistTestShouldFilterNthElement(Stream<String> input, List<String> expected, int 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);
}
@ParameterizedTest
@MethodSource("testSource")
void givenListSkipNthElementInListWithForTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
final List<String> actual = SkippingElements.skipNthElementInListWithFor(input, n);
void givenListSkipNthElementInListWithForTestShouldFilterNthElement(Stream<String> input, List<String> expected, int 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);
}
@ParameterizedTest
@MethodSource("testSource")
void givenListSkipNthElementInStreamWithIteratorTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
final Stream<String> inputStream = input.stream();
final List<String> actual = SkippingElements.skipNthElementInListWithIterator(inputStream, n);
void givenListSkipNthElementInStreamWithIteratorTestShouldFilterNthElement(Stream<String> input, List<String> expected, int n) {
List<String> result = new ArrayList<>();
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);
}
@ParameterizedTest
@MethodSource("testSource")
void givenListSkipNthElementInStreamWithCollectorShouldFilterNthElement(List<String> input, List<String> expected, int n) {
final Stream<String> inputStream = input.stream();
final List<String> actual = SkippingElements.skipNthElementInStreamWithCollector(inputStream, n);
void givenListSkipNthElementInStreamWithCollectorShouldFilterNthElement(Stream<String> input, List<String> expected, int n) {
final List<String> actual = input.collect(SkippingCollector.collector(n));
assertEquals(expected, actual);
}
}

View File

@ -2,6 +2,10 @@
This module contains articles about Streams that are part of the Java Streams Ebook.
### NOTE:
Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article.
### Relevant Articles
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
@ -11,4 +15,4 @@ This module contains articles about Streams that are part of the Java Streams Eb
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
- [When to Use a Parallel Stream in Java](https://www.baeldung.com/java-when-to-use-parallel-stream)
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)

View File

@ -28,6 +28,11 @@
<artifactId>emoji-java</artifactId>
<version>${emoji-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${apache-commons-text.version}</version>
</dependency>
</dependencies>
<build>
@ -58,6 +63,7 @@
<validator.version>1.7</validator.version>
<apache-commons-lang3.version>3.12.0</apache-commons-lang3.version>
<emoji-java.version>5.1.1</emoji-java.version>
<apache-commons-text.version>1.10.0</apache-commons-text.version>
</properties>
</project>

View File

@ -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();
}
}

View File

@ -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));
}
}

View File

@ -2,3 +2,4 @@
- [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)
- [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)

View File

@ -23,4 +23,12 @@
</resources>
</build>
</project>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -3,6 +3,7 @@ package com.baeldung.centertext;
import liquibase.repackaged.org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
public class CenteringTextUnitTest {
@ -10,17 +11,16 @@ public class CenteringTextUnitTest {
@Test
public void givenTextAndTotalWidth_whenUsingStringFormat_thenTextIsCentered() {
String text = "Centered Text";
int totalWidth = 20;
int totalWidth = 15;
int padding = (totalWidth - text.length()) / 2;
String centeredText = String.format("%" + padding + "s%s%" + padding + "s", "", text, "");
String expectedCenteredText = " Centered Text ";
Assert.assertEquals("Centered Text", expectedCenteredText, centeredText);
Assert.assertEquals(" Centered Text ", centeredText);
}
@Test
public void givenTextAndTotalWidth_whenCenterUsingStringBuilder_thenTextIsCentered() {
String text = "Centered Text";
int width = 20;
int width = 15;
int padding = (width - text.length()) / 2;
StringBuilder centeredText = new StringBuilder();
for (int i = 0; i < padding; i++) {
@ -31,17 +31,15 @@ public class CenteringTextUnitTest {
centeredText.append(" ");
}
String centeredTextString = centeredText.toString();
String expectedCenteredText = " Centered Text ";
Assert.assertEquals("Centered Text", expectedCenteredText, centeredTextString);
Assert.assertEquals(" Centered Text ", centeredTextString);
}
@Test
public void givenTextAndTotalWidth_whenUsingStringUtilsCenterMethod_thenTextIsCentered() {
String text = "Centered Text";
int width = 20;
int width = 15;
String centeredText = StringUtils.center(text, width);
String expectedCenteredText = StringUtils.center("Centered Text", width);
assertEquals("Centered Text", expectedCenteredText, centeredText);
assertEquals(" Centered Text ", centeredText);
}
}
}

View File

@ -27,6 +27,11 @@
<!--<module>core-java-security</module> -->
<!--<module>core-java-streams-2</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-streams</module>
<module>core-java-9</module>
@ -188,6 +193,11 @@
<module>core-java-collections-maps-6</module>
<module>core-java-records</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>
<dependencyManagement>

View File

@ -8,8 +8,10 @@ buildscript {
}
}
apply plugin: 'java'
apply plugin: 'com.github.johnrengelman.shadow'
plugins {
id 'com.github.johnrengelman.shadow' version '7.1.2'
id 'java'
}
repositories {
mavenCentral()
@ -30,7 +32,7 @@ task customFatJar(type: Jar) {
manifest {
attributes 'Main-Class': 'com.baeldung.fatjar.Application'
}
baseName = 'all-in-one-jar'
archiveBaseName = 'all-in-one-jar'
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
with jar

View File

@ -33,7 +33,7 @@
</build>
<properties>
<jackson.version>2.14.2</jackson.version>
<jackson.version>2.15.2</jackson.version>
<java.version>17</java.version>
</properties>

View File

@ -11,3 +11,4 @@ This module contains articles about Jersey.
- [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)
- [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)

View File

@ -4,4 +4,5 @@ This module contains articles about Apache Commons libraries.
### Relevant articles
- [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)

View File

@ -14,7 +14,7 @@ public class BuilderWithDefaultValueUnitTest {
}
@Test
public void givenBuilderWithDefaultValue_NoArgsWorksAlso() {
public void givenBuilderWithDefaultValue_ThanNoArgsWorksAlso() {
Pojo build = new Pojo().toBuilder()
.build();
Pojo pojo = new Pojo();

View File

@ -1,7 +1,7 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>parent-spring-6</artifactId>
<version>0.0.1-SNAPSHOT</version>

View File

@ -1,2 +1,3 @@
## Relevant Articles
- [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)

View File

@ -12,4 +12,13 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}
}

View File

@ -35,7 +35,7 @@
<module>hibernate-queries</module>
<module>hibernate-enterprise</module>
<module>influxdb</module>
<module>java-cassandra</module>
<module>java-cassandra</module>
<module>java-cockroachdb</module>
<module>java-jdbi</module>
<module>java-jpa</module> <!-- long running -->
@ -110,7 +110,6 @@
<module>spring-mybatis</module>
<module>spring-persistence-simple</module>
<module>spring-data-yugabytedb</module>
<module>fauna</module>
<module>spring-data-rest</module>
<module>java-mongodb</module>

View File

@ -11,9 +11,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -44,12 +44,19 @@
<artifactId>db-util</artifactId>
<version>${db-util.version}</version>
</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>
<properties>
<!-- The main class to start by executing java -jar -->
<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>
</project>

View File

@ -1,7 +1,7 @@
package com.baeldung.h2.exceptions.models;
import javax.persistence.Entity;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class User {

View File

@ -3,15 +3,15 @@ package com.baeldung.h2db.demo.client;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import jakarta.annotation.PostConstruct;
@SpringBootApplication
@ComponentScan("com.baeldung.h2db.demo.client")
public class ClientSpringBootApp {

View File

@ -3,7 +3,7 @@ package com.baeldung.h2db.demo.server;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import jakarta.annotation.PostConstruct;
import org.h2.tools.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;

View File

@ -1,13 +1,14 @@
package com.baeldung.h2db.lazy_load_no_trans.entity;
import jakarta.persistence.Column;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.Immutable;
import javax.persistence.Entity;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
@Getter
@ -22,5 +23,6 @@ public class Document {
private String title;
@Column(name="user_id")
private Long userId;
}

View File

@ -8,10 +8,10 @@ import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.Immutable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;

View File

@ -1,9 +1,10 @@
package com.baeldung.h2db.notnull.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
@Entity

View File

@ -1,9 +1,9 @@
package com.baeldung.h2db.springboot.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.util.Objects;
@Table(name = "countries")

View File

@ -4,9 +4,9 @@ insert into "user" values (103, 'user3', 'comment3');
insert into "user" values (104, 'user4', 'comment4');
insert into "user" values (105, 'user5', 'comment5');
insert into "document" values (1, 'doc1', 101);
insert into "document" values (2, 'doc2', 101);
insert into "document" values (3, 'doc3', 101);
insert into "document" values (4, 'doc4', 101);
insert into "document" values (5, 'doc5', 102);
insert into "document" values (6, 'doc6', 102);
insert into "document" ("id","title","user_id") values (1, 'doc1', 101);
insert into "document" ("id","title","user_id") values (2, 'doc2', 101);
insert into "document" ("id","title","user_id") values (3, 'doc3', 101);
insert into "document" ("id","title","user_id") values (4, 'doc4', 101);
insert into "document" ("id","title","user_id") values (5, 'doc5', 102);
insert into "document" ("id","title","user_id") values (6, 'doc6', 102);

View File

@ -2,16 +2,17 @@ package com.baeldung.h2db.notnull;
import com.baeldung.h2db.notnull.daos.ItemRepository;
import com.baeldung.h2db.notnull.models.Item;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.validation.ConstraintViolationException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import jakarta.validation.ConstraintViolationException;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NotNullVsNullableApplication.class)
public class ItemIntegrationTest {
@ -21,8 +22,8 @@ public class ItemIntegrationTest {
@Test
public void shouldNotAllowToPersistNullItemsPrice() {
assertThatThrownBy(() -> itemRepository.save(new Item()))
.hasRootCauseInstanceOf(ConstraintViolationException.class)
.hasStackTraceContaining("must not be null");
assertThatThrownBy(() -> itemRepository.save(new Item())).hasRootCauseInstanceOf(ConstraintViolationException.class)
.hasStackTraceContaining("propertyPath=price")
.hasStackTraceContaining("null");
}
}

View File

@ -19,18 +19,18 @@
<artifactId>spring-data-elasticsearch</artifactId>
<version>${spring-data-elasticsearch.version}</version>
</dependency>
<!--These two dependencies are inherited from spring-data-elasticsearch. Overriding to the newer version
will break tests. -->
<!-- <dependency>-->
<!-- <groupId>co.elastic.clients</groupId>-->
<!-- <artifactId>elasticsearch-java</artifactId>-->
<!-- <version>${elasticsearch.version}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.fasterxml.jackson.core</groupId>-->
<!-- <artifactId>jackson-databind</artifactId>-->
<!-- <version>${jackson.version}</version>-->
<!-- </dependency>-->
<!--These two dependencies are inherited from spring-data-elasticsearch. Overriding to the newer version
will break tests. -->
<!-- <dependency>-->
<!-- <groupId>co.elastic.clients</groupId>-->
<!-- <artifactId>elasticsearch-java</artifactId>-->
<!-- <version>${elasticsearch.version}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.fasterxml.jackson.core</groupId>-->
<!-- <artifactId>jackson-databind</artifactId>-->
<!-- <version>${jackson.version}</version>-->
<!-- </dependency>-->
<!-- Here for backward compatibility-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
@ -47,6 +47,7 @@
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@ -55,6 +56,7 @@
</plugin>
</plugins>
</build>
<properties>
<spring-data-elasticsearch.version>5.1.2</spring-data-elasticsearch.version>
<elasticsearch.version>8.9.0</elasticsearch.version>

View File

@ -1,16 +1,16 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-data-jpa-query-2</artifactId>
<name>spring-data-jpa-query-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -38,6 +38,7 @@
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>3.1.12</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
@ -50,12 +51,19 @@
<version>${tomcat-dbcp.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.3.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<groupId>org.hibernate.orm</groupId>
<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>
<groupId>org.springframework</groupId>

View File

@ -1,6 +1,6 @@
package com.baeldung.hibernate.fetching.model;
import javax.persistence.*;
import jakarta.persistence.*;
import java.io.Serializable;
import java.sql.Date;

View File

@ -1,6 +1,6 @@
package com.baeldung.hibernate.fetching.model;
import javax.persistence.*;
import jakarta.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

View File

@ -1,6 +1,6 @@
package com.baeldung.hibernate.fetching.model;
import javax.persistence.*;
import jakarta.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

View File

@ -3,12 +3,12 @@ package com.baeldung.persistence.dao.common;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
public class AbstractJpaDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {

View File

@ -3,29 +3,29 @@ package com.baeldung.persistence.model;
import com.google.common.collect.Sets;
import org.hibernate.annotations.OrderBy;
import org.hibernate.envers.Audited;
import org.jboss.logging.Logger;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.OneToMany;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreRemove;
import jakarta.persistence.PreUpdate;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import java.util.logging.Logger;
@Entity
@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
@ -33,7 +33,7 @@ import java.util.Set;
@EntityListeners(AuditingEntityListener.class)
public class Bar implements Serializable {
private static final Logger LOGGER = Logger.getLogger(Bar.class);
private static final Logger LOGGER = Logger.getLogger(Bar.class.toString());
public enum OPERATION {
INSERT, UPDATE, DELETE;

View File

@ -2,10 +2,10 @@ package com.baeldung.persistence.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToOne;
@Entity
public class Child implements Serializable {

View File

@ -2,20 +2,20 @@ package com.baeldung.persistence.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureParameter;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.NamedNativeQueries;
import jakarta.persistence.NamedNativeQuery;
import jakarta.persistence.NamedStoredProcedureQuery;
import jakarta.persistence.ParameterMode;
import jakarta.persistence.StoredProcedureParameter;
import org.hibernate.envers.Audited;

View File

@ -2,12 +2,12 @@ package com.baeldung.persistence.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
@Entity
public class Parent implements Serializable {

View File

@ -1,8 +1,8 @@
package com.baeldung.persistence.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class Person {

View File

@ -1,6 +1,6 @@
package com.baeldung.spring.data.jpa.query;
import javax.persistence.*;
import jakarta.persistence.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

View File

@ -1,8 +1,8 @@
package com.baeldung.spring.data.jpa.query;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.*;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

View File

@ -4,8 +4,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.junit.After;
import org.junit.AfterClass;
@ -30,15 +30,15 @@ import com.baeldung.spring.config.PersistenceTestConfig;
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class JPABarAuditIntegrationTest {
private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class);
private static final Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class);
@BeforeClass
public static void setUpBeforeClass() throws Exception {
public static void setUpBeforeClass() {
logger.info("setUpBeforeClass()");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
public static void tearDownAfterClass(){
logger.info("tearDownAfterClass()");
}

View File

@ -3,8 +3,8 @@ package com.baeldung.persistence.audit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.junit.After;
import org.junit.AfterClass;
@ -29,7 +29,7 @@ import com.baeldung.spring.config.PersistenceTestConfig;
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringDataJPABarAuditIntegrationTest {
private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
private static final Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
@BeforeClass
public static void setUpBeforeClass() throws Exception {
@ -37,7 +37,7 @@ public class SpringDataJPABarAuditIntegrationTest {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
public static void tearDownAfterClass(){
logger.info("tearDownAfterClass()");
}

View File

@ -17,7 +17,7 @@ public class FooFixtures {
private static final Logger LOGGER = LoggerFactory.getLogger(FooFixtures.class);
private SessionFactory sessionFactory;
private final SessionFactory sessionFactory;
public FooFixtures(final SessionFactory sessionFactory) {
super();
@ -28,8 +28,8 @@ public class FooFixtures {
// API
public void createBars() {
Session session = null;
Transaction tx = null;
Session session;
Transaction tx;
session = sessionFactory.openSession();
tx = session.getTransaction();
try {
@ -39,13 +39,13 @@ public class FooFixtures {
bar.setName("Bar_" + i);
final Foo foo = new Foo("Foo_" + (i + 120));
foo.setBar(bar);
session.save(foo);
session.persist(foo);
final Foo foo2 = new Foo(null);
if (i % 2 == 0) {
foo2.setName("LuckyFoo" + (i + 120));
}
foo2.setBar(bar);
session.save(foo2);
session.persist(foo2);
bar.getFooSet().add(foo);
bar.getFooSet().add(foo2);
session.merge(bar);
@ -53,16 +53,12 @@ public class FooFixtures {
tx.commit();
session.flush();
} catch (final HibernateException he) {
if (tx != null) {
tx.rollback();
}
tx.rollback();
LOGGER.error("Not able to open session", he);
} catch (final Exception e) {
LOGGER.error(e.getLocalizedMessage(), e);
} finally {
if (session != null) {
session.close();
}
session.close();
}
}
@ -86,23 +82,18 @@ public class FooFixtures {
try {
tx.begin();
for (final Foo foo : fooList) {
session.save(foo.getBar());
session.save(foo);
session.persist(foo.getBar());
session.persist(foo);
}
tx.commit();
session.flush();
} catch (final HibernateException he) {
if (tx != null) {
tx.rollback();
}
tx.rollback();
LOGGER.error("Not able to open session", he);
} catch (final Exception e) {
LOGGER.error(e.getLocalizedMessage(), e);
} finally {
if (session != null) {
session.close();
}
session.close();
}
}

View File

@ -1,19 +1,19 @@
package com.baeldung.persistence.hibernate;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.query.Query;
import org.hibernate.query.SelectionQuery;
import org.hibernate.query.criteria.HibernateCriteriaBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -28,6 +28,8 @@ import com.baeldung.persistence.service.IFooService;
import com.baeldung.spring.config.PersistenceTestConfig;
import com.google.common.collect.Lists;
import jakarta.persistence.criteria.CriteriaQuery;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooPaginationPersistenceIntegrationTest {
@ -40,8 +42,6 @@ public class FooPaginationPersistenceIntegrationTest {
private Session session;
// tests
@Before
public final void before() {
final int minimalNumberOfEntities = 25;
@ -59,20 +59,17 @@ public class FooPaginationPersistenceIntegrationTest {
session.close();
}
// tests
@Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@SuppressWarnings("unchecked")
@Test
public final void whenRetrievingPaginatedEntities_thenCorrectSize() {
final int pageNumber = 1;
final int pageSize = 10;
final Query query = session.createQuery("From Foo");
final Query<Foo> query = session.createQuery("From Foo",Foo.class);
query.setFirstResult((pageNumber - 1) * pageSize);
query.setMaxResults(pageSize);
final List<Foo> fooList = query.list();
@ -80,19 +77,18 @@ public class FooPaginationPersistenceIntegrationTest {
assertThat(fooList, hasSize(pageSize));
}
@SuppressWarnings("unchecked")
@Test
public final void whenRetrievingAllPages_thenCorrect() {
int pageNumber = 1;
final int pageSize = 10;
final String countQ = "Select count (f.id) from Foo f";
final Query countQuery = session.createQuery(countQ);
final Query<Long> countQuery = session.createQuery(countQ, Long.class);
final Long countResult = (Long) countQuery.uniqueResult();
final List<Foo> fooList = Lists.newArrayList();
int totalEntities = 0;
final Query query = session.createQuery("From Foo");
final Query<Foo> query = session.createQuery("From Foo", Foo.class);
while (totalEntities < countResult) {
query.setFirstResult((pageNumber - 1) * pageSize);
query.setMaxResults(pageSize);
@ -102,17 +98,16 @@ public class FooPaginationPersistenceIntegrationTest {
}
}
@SuppressWarnings("unchecked")
@Test
public final void whenRetrievingLastPage_thenCorrectSize() {
final int pageSize = 10;
final String countQ = "Select count (f.id) from Foo f";
final Query countQuery = session.createQuery(countQ);
final Long countResults = (Long) countQuery.uniqueResult();
final Query<Long> countQuery = session.createQuery(countQ, Long.class);
final Long countResults = countQuery.uniqueResult();
final int lastPageNumber = (int) (Math.ceil(countResults / pageSize));
final Query selectQuery = session.createQuery("From Foo");
final Query<Foo> selectQuery = session.createQuery("From Foo",Foo.class);
selectQuery.setFirstResult((lastPageNumber - 1) * pageSize);
selectQuery.setMaxResults(pageSize);
final List<Foo> lastPage = selectQuery.list();
@ -126,9 +121,9 @@ public class FooPaginationPersistenceIntegrationTest {
public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() {
final int pageSize = 10;
final String hql = "FROM Foo f order by f.name";
final Query query = session.createQuery(hql);
final Query<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();
// final int totalResults = resultScroll.getRowNumber() + 1;
@ -138,7 +133,7 @@ public class FooPaginationPersistenceIntegrationTest {
final List<Foo> fooPage = Lists.newArrayList();
int i = 0;
while (pageSize > i++) {
fooPage.add((Foo) resultScroll.get(0));
fooPage.add((Foo) resultScroll.get());
if (!resultScroll.next()) {
break;
}
@ -147,36 +142,42 @@ public class FooPaginationPersistenceIntegrationTest {
assertThat(fooPage, hasSize(lessThan(10 + 1)));
}
@SuppressWarnings("unchecked")
@Test
public final void givenUsingTheCriteriaApi_whenRetrievingFirstPage_thenCorrect() {
final int pageSize = 10;
final Criteria criteria = session.createCriteria(Foo.class);
criteria.setFirstResult(0);
criteria.setMaxResults(pageSize);
final List<Foo> firstPage = criteria.list();
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
selectQuery.from(Foo.class);
SelectionQuery<Foo> query = session.createQuery(selectQuery);
query.setFirstResult(0);
query.setMaxResults(pageSize);
final List<Foo> firstPage = query.list();
assertThat(firstPage, hasSize(pageSize));
}
@SuppressWarnings("unchecked")
@Test
public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() {
final Criteria criteriaCount = session.createCriteria(Foo.class);
criteriaCount.setProjection(Projections.rowCount());
final Long count = (Long) criteriaCount.uniqueResult();
HibernateCriteriaBuilder qb = session.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(Foo.class)));
final Long count = session.createQuery(cq).getSingleResult();
int pageNumber = 1;
final int pageSize = 10;
final List<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;
while (totalEntities < count.intValue()) {
criteria.setFirstResult((pageNumber - 1) * pageSize);
criteria.setMaxResults(pageSize);
fooList.addAll(criteria.list());
query.setFirstResult((pageNumber - 1) * pageSize);
query.setMaxResults(pageSize);
fooList.addAll(query.list());
totalEntities = fooList.size();
pageNumber++;
}

View File

@ -2,15 +2,17 @@ package com.baeldung.persistence.hibernate;
import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.NullPrecedence;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.query.NullPrecedence;
import org.hibernate.query.Order;
import org.hibernate.query.Query;
import org.hibernate.query.SortDirection;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -26,6 +28,8 @@ import com.baeldung.persistence.model.Bar;
import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.config.PersistenceTestConfig;
import jakarta.persistence.criteria.CriteriaQuery;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
@SuppressWarnings("unchecked")
@ -91,7 +95,7 @@ public class FooSortingPersistenceIntegrationTest {
@Test
public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() {
final String hql = "FROM Foo f ORDER BY f.name ASC";
final Query query = session.createQuery(hql);
Query<Foo> query = session.createQuery(hql, Foo.class);
final List<Foo> fooList = query.list();
for (final Foo foo : fooList) {
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
@ -101,7 +105,7 @@ public class FooSortingPersistenceIntegrationTest {
@Test
public final void whenHQlSortingByMultipleAttributes_thenSortedResults() {
final String hql = "FROM Foo f ORDER BY f.name, f.id";
final Query query = session.createQuery(hql);
Query<Foo> query = session.createQuery(hql, Foo.class);
final List<Foo> fooList = query.list();
for (final Foo foo : fooList) {
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
@ -111,7 +115,7 @@ public class FooSortingPersistenceIntegrationTest {
@Test
public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() {
final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC";
final Query query = session.createQuery(hql);
Query<Foo> query = session.createQuery(hql, Foo.class);
final List<Foo> fooList = query.list();
for (final Foo foo : fooList) {
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
@ -120,9 +124,12 @@ public class FooSortingPersistenceIntegrationTest {
@Test
public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() {
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
criteria.addOrder(Order.asc("id"));
final List<Foo> fooList = criteria.list();
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
selectQuery.from(Foo.class);
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) {
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
}
@ -130,10 +137,16 @@ public class FooSortingPersistenceIntegrationTest {
@Test
public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() {
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
criteria.addOrder(Order.asc("name"));
criteria.addOrder(Order.asc("id"));
final List<Foo> fooList = criteria.list();
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
selectQuery.from(Foo.class);
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) {
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
}
@ -141,9 +154,15 @@ public class FooSortingPersistenceIntegrationTest {
@Test
public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() {
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST));
final List<Foo> fooList = criteria.list();
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
selectQuery.from(Foo.class);
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());
for (final Foo foo : fooList) {
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
@ -152,9 +171,15 @@ public class FooSortingPersistenceIntegrationTest {
@Test
public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() {
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST));
final List<Foo> fooList = criteria.list();
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
selectQuery.from(Foo.class);
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());
for (final Foo foo : fooList) {
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
@ -164,7 +189,7 @@ public class FooSortingPersistenceIntegrationTest {
@Test
public final void whenSortingBars_thenBarsWithSortedFoos() {
final String hql = "FROM Bar b ORDER BY b.id";
final Query query = session.createQuery(hql);
final Query<Bar> query = session.createQuery(hql, Bar.class);
final List<Bar> barList = query.list();
for (final Bar bar : barList) {
final Set<Foo> fooSet = bar.getFooSet();

View File

@ -5,14 +5,14 @@ import static org.junit.Assert.assertEquals;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.StoredProcedureQuery;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.StoredProcedureQuery;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
@ -59,22 +59,22 @@ public class FooStoredProceduresLiveTest {
private boolean getFoosByNameExists() {
try {
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetFoosByName()",Foo.class);
sqlQuery.list();
return true;
} catch (SQLGrammarException e) {
LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e);
LOGGER.error("WARNING : GetFoosByName() Procedure may be missing ", e);
return false;
}
}
private boolean getAllFoosExists() {
try {
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetAllFoos()",Foo.class);
sqlQuery.list();
return true;
} catch (SQLGrammarException e) {
LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e);
LOGGER.error("WARNING : GetAllFoos() Procedure may be missing ", e);
return false;
}
}
@ -90,9 +90,9 @@ public class FooStoredProceduresLiveTest {
fooService.create(new Foo(randomAlphabetic(6)));
// Stored procedure getAllFoos using createSQLQuery
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
@SuppressWarnings("unchecked")
// Stored procedure getAllFoos using createQuery
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetAllFoos()", Foo.class);
List<Foo> allFoos = sqlQuery.list();
for (Foo foo : allFoos) {
LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
@ -100,8 +100,8 @@ public class FooStoredProceduresLiveTest {
assertEquals(allFoos.size(), fooService.findAll().size());
// Stored procedure getAllFoos using a Named Query
Query namedQuery = session.getNamedQuery("callGetAllFoos");
@SuppressWarnings("unchecked")
Query<Foo> namedQuery = session.createNamedQuery("callGetAllFoos", Foo.class);
List<Foo> allFoos2 = namedQuery.list();
for (Foo foo : allFoos2) {
LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
@ -110,6 +110,7 @@ public class FooStoredProceduresLiveTest {
StoredProcedureQuery spQuery =
entityManager.createNamedStoredProcedureQuery("GetAllFoos");
@SuppressWarnings("unchecked")
List<Foo> allFoos3 = spQuery.getResultList();
for (Foo foo : allFoos3) {
LOGGER.info("getAllFoos() StoredProcedureQuery result : {}", foo.getName());
@ -124,16 +125,16 @@ public class FooStoredProceduresLiveTest {
fooService.create(new Foo("NewFooName"));
// Stored procedure getFoosByName using createSQLQuery()
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetFoosByName(:fooName)", Foo.class).setParameter("fooName", "NewFooName");
List<Foo> allFoosByName = sqlQuery.list();
for (Foo foo : allFoosByName) {
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
}
// Stored procedure getFoosByName using getNamedQuery()
Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
Query<Foo> namedQuery = session.createQuery("callGetFoosByName", Foo.class).setParameter("fooName", "NewFooName");
List<Foo> allFoosByName2 = namedQuery.list();
for (Foo foo : allFoosByName2) {
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
@ -142,6 +143,7 @@ public class FooStoredProceduresLiveTest {
StoredProcedureQuery spQuery = entityManager.
createNamedStoredProcedureQuery("GetFoosByName")
.setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
List<Foo> allFoosByName3 = spQuery.getResultList();
assertEquals(1, allFoosByName3.size());
for (Foo foo : allFoosByName3) {

View File

@ -19,7 +19,7 @@ public class Library {
private List<String> addresses = new ArrayList<>();
@ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
@CollectionTable(name = "book", joinColumns = @JoinColumn(name = "library_id"))
@CollectionTable(name = "books", joinColumns = @JoinColumn(name = "library_id"))
@Column(name = "book", nullable = false)
private List<String> books = new ArrayList<>();

View File

@ -1,5 +1,5 @@
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=none
spring.jpa.generate-ddl=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

View File

@ -21,13 +21,13 @@ public class BookPagingAndSortingRepositoryIntegrationTest {
@Test
public void givenDbContainsBooks_whenfindBooksByAuthor_thenReturnBooksByAuthor() {
Book book1 = new Book("Spring Data", "John Doe", "1234567890");
Book book2 = new Book("Spring Data 2", "John Doe", "1234567891");
Book book3 = new Book("Spring Data 3", "John Doe", "1234567892");
Book book1 = new Book("Spring Data", "John Miller", "1234567890");
Book book2 = new Book("Spring Data 2", "John Miller", "1234567891");
Book book3 = new Book("Spring Data 3", "John Miller", "1234567892");
bookPagingAndSortingRepository.saveAll(Arrays.asList(book1, book2, book3));
Pageable pageable = PageRequest.of(0, 2, Sort.by("title").descending());
List<Book> books = bookPagingAndSortingRepository.findBooksByAuthor("John Doe", pageable);
List<Book> books = bookPagingAndSortingRepository.findBooksByAuthor("John Miller", pageable);
Assertions.assertEquals(2, books.size());
Assertions.assertEquals(book3.getId(), books.get(0).getId());
Assertions.assertEquals(book2.getId(), books.get(1).getId());

Some files were not shown because too many files have changed in this diff Show More