Merge branch 'master' into JAVA-25997

This commit is contained in:
panos-kakos 2023-10-22 20:36:09 +03:00
commit de34619039
353 changed files with 2687 additions and 1550 deletions

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,9 +8,9 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
@ -21,30 +21,8 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>12</maven.compiler.source.version>
<maven.compiler.target.version>12</maven.compiler.target.version>
<java.version>17</java.version>
</properties>
</project>

View File

@ -19,19 +19,6 @@ public class SwitchUnitTest {
Assert.assertEquals(value, 2);
}
@Test
public void switchLocalVariable(){
var month = Month.AUG;
int i = switch (month){
case JAN,JUN, JUL -> 3;
case FEB,SEP, OCT, NOV, DEC -> 1;
case MAR,MAY, APR, AUG -> {
int j = month.toString().length() * 4;
break j;
}
};
Assert.assertEquals(12, i);
}
enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}
}

View File

@ -8,39 +8,13 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<release>13</release>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>13</maven.compiler.source.version>
<maven.compiler.target.version>13</maven.compiler.target.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
<java.version>17</java.version>
</properties>
</project>

View File

@ -7,7 +7,6 @@ import org.junit.Test;
public class SwitchExpressionsWithYieldUnitTest {
@Test
@SuppressWarnings("preview")
public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() {
var me = 4;
var operation = "squareMe";

View File

@ -8,7 +8,6 @@ public class TextBlocksUnitTest {
private static final String JSON_STRING = "{\r\n" + "\"name\" : \"Baeldung\",\r\n" + "\"website\" : \"https://www.%s.com/\"\r\n" + "}";
@SuppressWarnings("preview")
private static final String TEXT_BLOCK_JSON = """
{
"name" : "Baeldung",
@ -25,7 +24,6 @@ public class TextBlocksUnitTest {
}
@SuppressWarnings("removal")
@Test
public void whenTextBlocks_thenFormattedWorksAsFormat() {
assertThat(TEXT_BLOCK_JSON.formatted("baeldung")

View File

@ -13,7 +13,6 @@ import org.junit.Test;
public class SwitchExpressionsUnitTest {
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthJune_thenWillReturn3() {
var month = JUNE;
@ -29,7 +28,6 @@ public class SwitchExpressionsUnitTest {
}
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthAugust_thenWillReturn24() {
var month = AUGUST;
@ -47,7 +45,6 @@ public class SwitchExpressionsUnitTest {
}
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthJanuary_thenWillReturn3() {
Function<Month, Integer> func = (month) -> {
@ -61,7 +58,6 @@ public class SwitchExpressionsUnitTest {
}
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthAugust_thenWillReturn2() {
var month = AUGUST;

View File

@ -8,10 +8,9 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
@ -27,33 +26,8 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.release>15</maven.compiler.release>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
<java.version>17</java.version>
</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-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

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

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

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

@ -0,0 +1,98 @@
package com.baeldung.map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
class Magic {
public String nullFunc() {
return null;
}
public String strFunc(String input) {
return input + ": A nice string";
}
}
public class PutIfAbsentVsComputeIfAbsentUnitTest {
private static final Map<String, String> MY_MAP = new HashMap<>();
private Magic magic = new Magic();
@BeforeEach
void resetTheMap() {
MY_MAP.clear();
MY_MAP.put("Key A", "value A");
MY_MAP.put("Key B", "value B");
MY_MAP.put("Key C", "value C");
MY_MAP.put("Key Null", null);
}
@Test
void whenCallingPutIfAbsentWithAbsentKey_thenGetNull() {
String putResult = MY_MAP.putIfAbsent("new key1", magic.nullFunc());
assertNull(putResult);
putResult = MY_MAP.putIfAbsent("new key2", magic.strFunc("new key2"));
assertNull(putResult);
putResult = MY_MAP.putIfAbsent("Key Null", magic.strFunc("Key Null"));
assertNull(putResult);
}
@Test
void whenCallingComputeIfAbsentWithAbsentKey_thenGetExpectedResult() {
String computeResult = MY_MAP.computeIfAbsent("new key1", k -> magic.nullFunc());
assertNull(computeResult);
computeResult = MY_MAP.computeIfAbsent("new key2", k -> magic.strFunc(k));
assertEquals("new key2: A nice string", computeResult);
computeResult = MY_MAP.computeIfAbsent("Key Null", k -> magic.strFunc(k));
assertEquals("Key Null: A nice string", computeResult);
}
@Test
void whenCallingPutIfAbsentWithAbsentKey_thenNullIsPut() {
assertEquals(4, MY_MAP.size()); // initial: 4 entries
MY_MAP.putIfAbsent("new key", magic.nullFunc());
assertEquals(5, MY_MAP.size());
assertTrue(MY_MAP.containsKey("new key")); // new entry has been added to the map
assertNull(MY_MAP.get("new key"));
}
@Test
void whenCallingComputeIfAbsentWithAbsentKey_thenNullIsNotPut() {
assertEquals(4, MY_MAP.size()); // initial: 4 entries
MY_MAP.computeIfAbsent("new key", k -> magic.nullFunc());
assertEquals(4, MY_MAP.size());
assertFalse(MY_MAP.containsKey("new key")); // <- no new entry added
}
@Test
void whenCallingPutIfAbsent_thenFunctionIsAlwaysCalled() {
Magic spyMagic = spy(magic);
MY_MAP.putIfAbsent("Key A", spyMagic.strFunc("Key A"));
verify(spyMagic, times(1)).strFunc(anyString());
MY_MAP.putIfAbsent("new key", spyMagic.strFunc("new key"));
verify(spyMagic, times(2)).strFunc(anyString());
}
@Test
void whenCallingComputeIfAbsent_thenFunctionIsCalledOnDemand() {
Magic spyMagic = spy(magic);
MY_MAP.computeIfAbsent("Key A", k -> spyMagic.strFunc(k));
verify(spyMagic, never()).strFunc(anyString());
MY_MAP.computeIfAbsent("new key", k -> spyMagic.strFunc(k));
verify(spyMagic, times(1)).strFunc(anyString());
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.writehashmaptocsvfile;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class WriteHashmaptoCVSFileUnitTest {
public Map<String, String> employeeData;
public WriteHashmaptoCVSFileUnitTest() {
employeeData = new HashMap<>();
employeeData.put("Name", "John Doe");
employeeData.put("Title", "Software Engineer");
employeeData.put("Department", "Engineering");
employeeData.put("Salary", "75000");
}
@Test
public void givenEmployeeData_whenWriteToCSVUsingFileWriter_thenCSVFileIsCreated() {
try (FileWriter csvWriter = new FileWriter("employee_data.csv")) {
// Write header row
csvWriter.append("Name,Title,Department,Salary\n");
// Write data row
csvWriter.append(employeeData.get("Name")).append(",");
csvWriter.append(employeeData.get("Title")).append(",");
csvWriter.append(employeeData.get("Department")).append(",");
csvWriter.append(employeeData.get("Salary")).append("\n");
} catch (IOException e) {
e.printStackTrace();
}
// Ensure the CSV file exists
assertTrue(new File("employee_data.csv").exists(), "CSV file does not exist!");
}
@Test
public void givenCSVFile_whenWriteToCSVUsingApacheCommons_thenContentsMatchExpected() {
try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter("employee_data2.csv"), CSVFormat.DEFAULT)) {
// Write header row
csvPrinter.printRecord("Name", "Title", "Department", "Salary");
// Write data row
csvPrinter.printRecord(employeeData.get("Name"), employeeData.get("Title"), employeeData.get("Department"), employeeData.get("Salary"));
} catch (IOException e) {
e.printStackTrace();
}
// Ensure the CSV file exists
assertTrue(new File("employee_data2.csv").exists());
}
}

View File

@ -0,0 +1,36 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-concurrency-advanced-5</artifactId>
<name>core-java-concurrency-advanced-5</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>
<finalName>core-java-concurrency-advanced-5</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,24 @@
package com.baeldung.wait_synchronization;
public class ConditionChecker {
private volatile Boolean jobIsDone;
private final Object lock = new Object();
public void ensureCondition() {
synchronized (lock) {
while (!jobIsDone) {
try {
lock.wait();
} catch (InterruptedException e) { }
}
}
}
public void complete() {
synchronized (lock) {
jobIsDone = true;
lock.notify();
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.wait_synchronization;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
class ConditionCheckerUnitTest {
@Test
public void givenBothMethodsAreSynchronized_whenBothMethodsAreCalled_thenNoExceptionsOrDeadlocks() {
ConditionChecker conditionChecker = new ConditionChecker();
ExecutorService executorService = Executors.newFixedThreadPool(2);
Assertions.assertThatCode(() -> {
executorService.submit(conditionChecker::ensureCondition);
executorService.submit(conditionChecker::complete);
}).doesNotThrowAnyException();
}
}

View File

@ -65,7 +65,7 @@
<properties>
<commons-validator.version>1.6</commons-validator.version>
<joda-time.version>2.10.10</joda-time.version>
<joda-time.version>2.12.5</joda-time.version>
<hirondelle-date4j.version>RELEASE</hirondelle-date4j.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>

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

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

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

@ -15,6 +15,7 @@ import java.util.Map;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.web.util.UriComponentsBuilder;
@ -23,95 +24,101 @@ import com.google.common.collect.ImmutableMap;
public class UrlUnitTest {
@Test
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com");
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com").toURL();
assertEquals("http", url.getProtocol());
}
@Test
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com");
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com").toURL();
assertEquals("baeldung.com", url.getHost());
}
@Test
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL();
assertEquals("/articles?topic=java&version=8", url.getFile());
}
@Test
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException {
final URL url = new URL("http://baeldung.com/guidelines.txt");
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com/guidelines.txt").toURL();
assertEquals("/guidelines.txt", url.getFile());
}
@Test
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL();
assertEquals("/articles", url.getPath());
}
@Test
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com/articles?topic=java");
assertEquals("topic=java", url.getQuery());
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com/articles?topic=java&amp;version=8").toURL();
assertEquals("topic=java&amp;version=8", url.getQuery());
}
@Test
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com");
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com").toURL();
assertEquals(-1, url.getPort());
assertEquals(80, url.getDefaultPort());
}
@Test
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com:8090");
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com:8090").toURL();
assertEquals(8090, url.getPort());
assertEquals(80, url.getDefaultPort());
}
@Test
public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException {
final URL baseUrl = new URL("http://baeldung.com");
final URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
public void givenHomeUrlAndFullUrl_whenRelativize_thenCorrect() throws MalformedURLException, URISyntaxException {
final URI homeUri = new URI("http://baeldung.com");
final URI fullUri = new URI("http://baeldung.com" + "/a-guide-to-java-sockets");
final URI relativeUri = homeUri.relativize(fullUri);
assertEquals("a-guide-to-java-sockets", relativeUri.toString());
}
@Test
public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException {
final URL baseUrl = new URL("http://baeldung.com");
final URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets");
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
}
@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException, URISyntaxException {
final String protocol = "http";
final String host = "baeldung.com";
final String file = "/guidelines.txt";
final URL url = new URL(protocol, host, file);
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
final String fragment = "myImage";
final URL url = new URI(protocol, host, file, fragment).toURL();
assertEquals("http://baeldung.com/guidelines.txt#myImage", url.toString());
}
@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException {
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException, URISyntaxException {
final String protocol = "http";
final String username = "admin";
final String host = "baeldung.com";
final String file = "/articles?topic=java&version=8";
final URL url = new URL(protocol, host, file);
assertEquals("http://baeldung.com/articles?topic=java&version=8", url.toString());
final String file = "/articles";
final String query = "topic=java&version=8";
final String fragment = "myImage";
final URL url = new URI(protocol, username, host, -1, file, query, fragment).toURL();
assertEquals("http://admin@baeldung.com/articles?topic=java&version=8#myImage", url.toString());
}
@Test
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
public void givenRelativeUrl_whenCreatesRelativeUrl_thenThrows() throws URISyntaxException, MalformedURLException {
final URI uri = new URI("/a-guide-to-java-sockets");
Assert.assertThrows(IllegalArgumentException.class, () -> uri.toURL());
}
@Test
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException, URISyntaxException {
final String protocol = "http";
final String username = "admin";
final String host = "baeldung.com";
final int port = 9000;
final String file = "/guidelines.txt";
final URL url = new URL(protocol, host, port, file);
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
final String fragment = "myImage";
final URL url = new URI(protocol, username, host, port, file, null, fragment).toURL();
assertEquals("http://admin@baeldung.com:9000/guidelines.txt#myImage", url.toString());
}
@Test
@ -120,7 +127,8 @@ public class UrlUnitTest {
uriBuilder.setPort(9090);
uriBuilder.addParameter("topic", "java");
uriBuilder.addParameter("version", "8");
URL url = uriBuilder.build().toURL();
URL url = uriBuilder.build()
.toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
@ -130,26 +138,27 @@ public class UrlUnitTest {
URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
uriBuilder.setPort(9090);
uriBuilder.addParameters(paramMap.entrySet()
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(toList()));
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(toList()));
URL url = uriBuilder.build().toURL();
URL url = uriBuilder.build()
.toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
@Test
public void givenUrlParameters_whenBuildUrlWithSpringUriComponentsBuilder_thenSuccess() throws MalformedURLException {
URL url = UriComponentsBuilder.newInstance()
.scheme("http")
.host("baeldung.com")
.port(9090)
.path("articles")
.queryParam("topic", "java")
.queryParam("version", "8")
.build()
.toUri()
.toURL();
.scheme("http")
.host("baeldung.com")
.port(9090)
.path("articles")
.queryParam("topic", "java")
.queryParam("version", "8")
.build()
.toUri()
.toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}

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

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

@ -0,0 +1,2 @@
### Relevant Articles:

View File

@ -0,0 +1,72 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-string-operations-7</artifactId>
<name>core-java-string-operations-7</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache.commons.lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<apache.commons.lang3.version>3.12.0</apache.commons.lang3.version>
<commons-text.version>1.10.0</commons-text.version>
</properties>
</project>

View File

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

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>
@ -34,6 +39,9 @@
<module>core-java-11</module>
<module>core-java-11-2</module>
<module>core-java-11-3</module>
<module>core-java-12</module>
<module>core-java-13</module>
<module>core-java-15</module>
<module>core-java-collections-array-list</module>
<module>core-java-collections-array-list-2</module>
<module>core-java-collections-list-4</module>
@ -178,12 +186,18 @@
<module>core-java-string-operations</module>
<module>core-java-string-operations-2</module>
<module>core-java-string-operations-6</module>
<module>core-java-string-operations-7</module>
<module>core-java-regex</module>
<module>core-java-regex-2</module>
<module>core-java-uuid</module>
<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

@ -237,7 +237,6 @@
<jsoniter.version>0.9.23</jsoniter.version>
<moshi.version>1.9.2</moshi.version>
<fastjson.version>1.2.21</fastjson.version>
<json.version>20211205</json.version>
<jsonschema2pojo-core.version>1.1.1</jsonschema2pojo-core.version>
<jackson-jsonld.version>0.1.1</jackson-jsonld.version>
<hydra-jsonld.version>0.4.2</hydra-jsonld.version>

View File

@ -38,7 +38,6 @@
<properties>
<jsonb-api.version>1.0</jsonb-api.version>
<json.version>20230227</json.version>
<gson.version>2.8.5</gson.version>
<javax.version>1.1.2</javax.version>
<json-unit-assertj.version>2.28.0</json-unit-assertj.version>

View File

@ -37,7 +37,6 @@
</dependencies>
<properties>
<json.version>20211205</json.version>
<gson.version>2.10.1</gson.version>
<guava.version>32.1.2-jre</guava.version>
</properties>

View File

@ -68,7 +68,6 @@
<networknt.json.schema.version>1.0.72</networknt.json.schema.version>
<jsonb-api.version>1.0</jsonb-api.version>
<yasson.version>1.0.1</yasson.version>
<json.version>20230227</json.version>
<gson.version>2.8.5</gson.version>
<javax.version>1.1.2</javax.version>
<json-unit-assertj.version>2.28.0</json-unit-assertj.version>

View File

@ -34,4 +34,8 @@
</pluginManagement>
</build>
<properties>
<json.version>20230618</json.version>
</properties>
</project>

View File

@ -4,9 +4,9 @@
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>
<groupId>com.baeldung</groupId>
<artifactId>api-service</artifactId>
<artifactId>lightrun-api-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api-service</name>
<name>lightrun-api-service</name>
<description>Aggregator Service for LightRun Article</description>
<parent>

View File

@ -4,9 +4,9 @@
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>
<groupId>com.baeldung</groupId>
<artifactId>tasks-service</artifactId>
<artifactId>lightrun-tasks-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tasks-service</name>
<name>lightrun-tasks-service</name>
<description>Tasks Service for LightRun Article</description>
<parent>

View File

@ -4,9 +4,9 @@
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>
<groupId>com.baeldung</groupId>
<artifactId>users-service</artifactId>
<artifactId>lightrun-users-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>users-service</name>
<name>lightrun-users-service</name>
<description>Users Service for LightRun Article</description>
<parent>

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