Merge branch 'master' into master
This commit is contained in:
@@ -1,2 +1,3 @@
|
||||
## Relevant Articles
|
||||
- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
|
||||
- [How to Read Zip Files Entries With Java](https://www.baeldung.com/java-read-zip-files)
|
||||
|
||||
@@ -6,3 +6,4 @@
|
||||
- [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex)
|
||||
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)
|
||||
- [How to Check if All Runnables Are Done](https://www.baeldung.com/java-runnables-check-status)
|
||||
- [Parallelize for Loop in Java](https://www.baeldung.com/java-for-loop-parallel)
|
||||
|
||||
@@ -8,4 +8,5 @@ This module contains articles about basic Java concurrency.
|
||||
- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await)
|
||||
- [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking)
|
||||
- [Returning a Value After Finishing Thread’s Job in Java](https://www.baeldung.com/java-return-value-after-thread-finish)
|
||||
- [CompletableFuture and ThreadPool in Java](https://www.baeldung.com/java-completablefuture-threadpool)
|
||||
- [[<-- Prev]](../core-java-concurrency-basic-2)
|
||||
|
||||
@@ -8,4 +8,5 @@ This module contains articles about date operations in Java.
|
||||
- [How to Determine Date of the First Day of the Week Using LocalDate in Java](https://www.baeldung.com/java-first-day-of-the-week)
|
||||
- [Adding One Month to Current Date in Java](https://www.baeldung.com/java-adding-one-month-to-current-date)
|
||||
- [How to Get Last Day of a Month in Java](https://www.baeldung.com/java-last-day-month)
|
||||
- [Getting Yesterday’s Date in Java](https://www.baeldung.com/java-find-yesterdays-date)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)
|
||||
|
||||
@@ -4,13 +4,5 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
|
||||
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
|
||||
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
|
||||
- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||
- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array)
|
||||
- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces)
|
||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
||||
- [What’s the Difference between Scanner next() and nextLine() Methods?](https://www.baeldung.com/java-scanner-next-vs-nextline)
|
||||
- [Handle NoSuchElementException When Reading a File Through Scanner](https://www.baeldung.com/java-scanner-nosuchelementexception-reading-file)
|
||||
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
|
||||
@@ -92,12 +92,6 @@
|
||||
<version>7.1.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.5</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>core-java-io-apis-2</finalName>
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.emptyfile;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class CheckFileIsEmptyUnitTest {
|
||||
@Test
|
||||
void whenTheFileIsEmpty_thenFileLengthIsZero(@TempDir Path tempDir) throws IOException {
|
||||
File emptyFile = tempDir.resolve("an-empty-file.txt")
|
||||
.toFile();
|
||||
emptyFile.createNewFile();
|
||||
assertTrue(emptyFile.exists());
|
||||
assertEquals(0, emptyFile.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFileDoesNotExist_thenFileLengthIsZero(@TempDir Path tempDir) {
|
||||
File aNewFile = tempDir.resolve("a-new-file.txt")
|
||||
.toFile();
|
||||
assertFalse(aNewFile.exists());
|
||||
assertEquals(0, aNewFile.length());
|
||||
}
|
||||
|
||||
boolean isFileEmpty(File file) {
|
||||
if (!file.exists()) {
|
||||
throw new IllegalArgumentException("Cannot check the file length. The file is not found: " + file.getAbsolutePath());
|
||||
}
|
||||
return file.length() == 0;
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileDoesNotExist_thenIsFilesEmptyThrowsException(@TempDir Path tempDir) {
|
||||
File aNewFile = tempDir.resolve("a-new-file.txt")
|
||||
.toFile();
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> isFileEmpty(aNewFile));
|
||||
assertEquals(ex.getMessage(), "Cannot check the file length. The file is not found: " + aNewFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileIsEmpty_thenIsFilesEmptyReturnsTrue(@TempDir Path tempDir) throws IOException {
|
||||
File emptyFile = tempDir.resolve("an-empty-file.txt")
|
||||
.toFile();
|
||||
emptyFile.createNewFile();
|
||||
assertTrue(isFileEmpty(emptyFile));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileIsEmpty_thenFilesSizeReturnsTrue(@TempDir Path tempDir) throws IOException {
|
||||
Path emptyFilePath = tempDir.resolve("an-empty-file.txt");
|
||||
Files.createFile(emptyFilePath);
|
||||
assertEquals(0, Files.size(emptyFilePath));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileDoesNotExist_thenFilesSizeThrowsException(@TempDir Path tempDir) {
|
||||
Path aNewFilePath = tempDir.resolve("a-new-file.txt");
|
||||
assertThrows(NoSuchFileException.class, () -> Files.size(aNewFilePath));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
## Core Java IO APIs
|
||||
|
||||
This module contains articles about core Java input/output(IO) APIs.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Read Date in Java Using Scanner](https://www.baeldung.com/java-scanner-read-date)
|
||||
@@ -1,15 +0,0 @@
|
||||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-io-apis-3</artifactId>
|
||||
<name>core-java-io-apis-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
</project>
|
||||
@@ -10,6 +10,6 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](https://www.baeldung.com/java-path)
|
||||
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
- [Java Scanner](https://www.baeldung.com/java-scanner)
|
||||
- [Scanner nextLine() Method](https://www.baeldung.com/java-scanner-nextline)
|
||||
- [Java Scanner hasNext() vs. hasNextLine()](https://www.baeldung.com/java-scanner-hasnext-vs-hasnextline)
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
||||
@@ -31,6 +31,12 @@
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.5</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+36
-36
@@ -1,36 +1,36 @@
|
||||
package com.baeldung.multinput;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class MultiInputs {
|
||||
public void UsingSpaceDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter two numbers: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingREDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter("[\\s,]+");
|
||||
System.out.print("Enter two numbers separated by a space or a comma: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingCustomDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter(";");
|
||||
System.out.print("Enter two numbers separated by a semicolon: ");
|
||||
try { int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2); }
|
||||
catch (InputMismatchException e)
|
||||
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
package com.baeldung.multinput;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class MultiInputs {
|
||||
public void UsingSpaceDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter two numbers: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingREDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter("[\\s,]+");
|
||||
System.out.print("Enter two numbers separated by a space or a comma: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingCustomDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter(";");
|
||||
System.out.print("Enter two numbers separated by a semicolon: ");
|
||||
try { int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2); }
|
||||
catch (InputMismatchException e)
|
||||
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+36
-36
@@ -1,36 +1,36 @@
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BufferedReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsLineByLine() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
final Path filePath = new File("src/test/resources/sampleText1.txt").toPath();
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
|
||||
while((line = br.readLine()) != null) {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BufferedReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsLineByLine() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
final Path filePath = new File("src/test/resources/sampleText1.txt").toPath();
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
|
||||
while((line = br.readLine()) != null) {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||
}
|
||||
|
||||
}
|
||||
+30
-30
@@ -1,30 +1,30 @@
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsCharByChar() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||
int i = fr.read();
|
||||
|
||||
while(i != -1) {
|
||||
result.append((char)i);
|
||||
|
||||
i = fr.read();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("qwerty", result.toString());
|
||||
}
|
||||
}
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsCharByChar() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||
int i = fr.read();
|
||||
|
||||
while(i != -1) {
|
||||
result.append((char)i);
|
||||
|
||||
i = fr.read();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("qwerty", result.toString());
|
||||
}
|
||||
}
|
||||
+49
-47
@@ -1,47 +1,49 @@
|
||||
package com.baeldung.multinput;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.InputMismatchException;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
import com.baeldung.multinput.MultiInputs;
|
||||
public class TestMultipleInputsUnitTest {
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "10 20\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingSpaceDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "30, 40\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingREDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "50; 60\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingCustomDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() {
|
||||
String input = "abc\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter);
|
||||
}
|
||||
}
|
||||
package com.baeldung.multinput;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.InputMismatchException;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class TestMultipleInputsUnitTest {
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "10 20\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingSpaceDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "30, 40\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingREDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "50; 60\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingCustomDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() {
|
||||
String input = "abc\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ This module contains articles about JAR files
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
||||
- [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven)
|
||||
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
|
||||
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
|
||||
- [Get Names of Classes Inside a JAR File](https://www.baeldung.com/jar-file-get-class-names)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
## Core Java Lang (Part 6)
|
||||
|
||||
This module contains articles about core features in the Java language
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Convert One Enum to Another Enum in Java](https://www.baeldung.com/java-convert-enums)
|
||||
@@ -0,0 +1,52 @@
|
||||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>core-java-lang-6</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct -->
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>17</source>
|
||||
<target>17</target>
|
||||
<annotationProcessorPaths>
|
||||
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
|
||||
<path>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<mapstruct.version>1.5.5.Final</mapstruct.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.enums.mapping;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.MappingConstants;
|
||||
import org.mapstruct.ValueMapping;
|
||||
|
||||
import com.baeldung.enums.mapping.order.CmsOrderStatus;
|
||||
import com.baeldung.enums.mapping.order.OrderStatus;
|
||||
import com.baeldung.enums.mapping.user.ExternalUserStatus;
|
||||
import com.baeldung.enums.mapping.user.UserStatus;
|
||||
|
||||
@Mapper
|
||||
public interface EnumMapper {
|
||||
|
||||
CmsOrderStatus map(OrderStatus orderStatus);
|
||||
|
||||
@ValueMapping(source = "PENDING", target = "INACTIVE")
|
||||
@ValueMapping(source = "BLOCKED", target = "INACTIVE")
|
||||
@ValueMapping(source = "INACTIVATED_BY_SYSTEM", target = "INACTIVE")
|
||||
@ValueMapping(source = "DELETED", target = "INACTIVE")
|
||||
ExternalUserStatus map(UserStatus userStatus);
|
||||
|
||||
@ValueMapping(source = MappingConstants.ANY_REMAINING, target = "INACTIVE")
|
||||
ExternalUserStatus mapDefault(UserStatus userStatus);
|
||||
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.enums.mapping.order;
|
||||
|
||||
public enum CmsOrderStatus {
|
||||
PENDING, APPROVED, PACKED, DELIVERED
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.enums.mapping.order;
|
||||
|
||||
public enum OrderStatus {
|
||||
PENDING, APPROVED, PACKED, DELIVERED;
|
||||
|
||||
public CmsOrderStatus toCmsOrderStatus() {
|
||||
return CmsOrderStatus.valueOf(this.name());
|
||||
}
|
||||
|
||||
public CmsOrderStatus toCmsOrderStatusOrdinal() {
|
||||
return CmsOrderStatus.values()[this.ordinal()];
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.enums.mapping.user;
|
||||
|
||||
public enum ExternalUserStatus {
|
||||
ACTIVE, INACTIVE
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.enums.mapping.user;
|
||||
|
||||
public enum UserStatus {
|
||||
PENDING, ACTIVE, BLOCKED, INACTIVATED_BY_SYSTEM, DELETED;
|
||||
|
||||
public ExternalUserStatus toExternalUserStatusViaSwitchStatement() {
|
||||
return switch (this) {
|
||||
case PENDING, BLOCKED, INACTIVATED_BY_SYSTEM, DELETED -> ExternalUserStatus.INACTIVE;
|
||||
case ACTIVE -> ExternalUserStatus.ACTIVE;
|
||||
};
|
||||
}
|
||||
|
||||
public ExternalUserStatus toExternalUserStatusViaRegularSwitch() {
|
||||
switch (this) {
|
||||
case PENDING:
|
||||
case BLOCKED:
|
||||
case INACTIVATED_BY_SYSTEM:
|
||||
case DELETED:
|
||||
return ExternalUserStatus.INACTIVE;
|
||||
case ACTIVE:
|
||||
return ExternalUserStatus.ACTIVE;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.enums.mapping.user;
|
||||
|
||||
import java.util.EnumMap;
|
||||
|
||||
public class UserStatusMapper {
|
||||
public static EnumMap<UserStatus, ExternalUserStatus> statusesMap;
|
||||
|
||||
static {
|
||||
statusesMap = new EnumMap<>(UserStatus.class);
|
||||
statusesMap.put(UserStatus.PENDING, ExternalUserStatus.INACTIVE);
|
||||
statusesMap.put(UserStatus.BLOCKED, ExternalUserStatus.INACTIVE);
|
||||
statusesMap.put(UserStatus.DELETED, ExternalUserStatus.INACTIVE);
|
||||
statusesMap.put(UserStatus.INACTIVATED_BY_SYSTEM, ExternalUserStatus.INACTIVE);
|
||||
statusesMap.put(UserStatus.ACTIVE, ExternalUserStatus.ACTIVE);
|
||||
}
|
||||
|
||||
public static ExternalUserStatus toExternalUserStatus(UserStatus userStatus) {
|
||||
return statusesMap.get(userStatus);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.enums.mapping.user;
|
||||
|
||||
public enum UserStatusWithFieldVariable {
|
||||
PENDING(ExternalUserStatus.INACTIVE),
|
||||
ACTIVE(ExternalUserStatus.ACTIVE),
|
||||
BLOCKED(ExternalUserStatus.INACTIVE),
|
||||
INACTIVATED_BY_SYSTEM(ExternalUserStatus.INACTIVE),
|
||||
DELETED(ExternalUserStatus.INACTIVE);
|
||||
|
||||
private final ExternalUserStatus externalUserStatus;
|
||||
|
||||
UserStatusWithFieldVariable(ExternalUserStatus externalUserStatus) {
|
||||
this.externalUserStatus = externalUserStatus;
|
||||
}
|
||||
|
||||
public ExternalUserStatus toExternalUserStatus() {
|
||||
return externalUserStatus;
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.baeldung.enums.mapping;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.enums.mapping.order.CmsOrderStatus;
|
||||
import com.baeldung.enums.mapping.order.OrderStatus;
|
||||
import com.baeldung.enums.mapping.user.ExternalUserStatus;
|
||||
import com.baeldung.enums.mapping.user.UserStatus;
|
||||
import com.baeldung.enums.mapping.user.UserStatusMapper;
|
||||
import com.baeldung.enums.mapping.user.UserStatusWithFieldVariable;
|
||||
|
||||
public class EnumConversionUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingSwitchStatement_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatusViaSwitchStatement());
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatusViaSwitchStatement());
|
||||
assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatusViaSwitchStatement());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingSwitch_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatusViaRegularSwitch());
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatusViaRegularSwitch());
|
||||
assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatusViaRegularSwitch());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingFieldVariable_thenEnumConverted() {
|
||||
UserStatusWithFieldVariable userStatusDeleted = UserStatusWithFieldVariable.DELETED;
|
||||
UserStatusWithFieldVariable userStatusPending = UserStatusWithFieldVariable.PENDING;
|
||||
UserStatusWithFieldVariable userStatusActive = UserStatusWithFieldVariable.ACTIVE;
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatus());
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatus());
|
||||
assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEnumMap_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, UserStatusMapper.toExternalUserStatus(userStatusDeleted));
|
||||
assertEquals(ExternalUserStatus.INACTIVE, UserStatusMapper.toExternalUserStatus(userStatusPending));
|
||||
assertEquals(ExternalUserStatus.ACTIVE, UserStatusMapper.toExternalUserStatus(userStatusActive));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingOrdinalApproach_thenEnumConverted() {
|
||||
OrderStatus orderStatusApproved = OrderStatus.APPROVED;
|
||||
OrderStatus orderStatusDelivered = OrderStatus.DELIVERED;
|
||||
OrderStatus orderStatusPending = OrderStatus.PENDING;
|
||||
|
||||
assertEquals(CmsOrderStatus.APPROVED, orderStatusApproved.toCmsOrderStatusOrdinal());
|
||||
assertEquals(CmsOrderStatus.DELIVERED, orderStatusDelivered.toCmsOrderStatusOrdinal());
|
||||
assertEquals(CmsOrderStatus.PENDING, orderStatusPending.toCmsOrderStatusOrdinal());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEnumName_thenEnumConverted() {
|
||||
OrderStatus orderStatusApproved = OrderStatus.APPROVED;
|
||||
OrderStatus orderStatusDelivered = OrderStatus.DELIVERED;
|
||||
OrderStatus orderStatusPending = OrderStatus.PENDING;
|
||||
|
||||
assertEquals(CmsOrderStatus.APPROVED, orderStatusApproved.toCmsOrderStatus());
|
||||
assertEquals(CmsOrderStatus.DELIVERED, orderStatusDelivered.toCmsOrderStatus());
|
||||
assertEquals(CmsOrderStatus.PENDING, orderStatusPending.toCmsOrderStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingDefaultMapstruct_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
EnumMapper enumMapper = new EnumMapperImpl();
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.map(userStatusDeleted));
|
||||
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.map(userStatusPending));
|
||||
assertEquals(ExternalUserStatus.ACTIVE, enumMapper.map(userStatusActive));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingConfiguredMapstruct_thenEnumConverted() {
|
||||
OrderStatus orderStatusApproved = OrderStatus.APPROVED;
|
||||
OrderStatus orderStatusDelivered = OrderStatus.DELIVERED;
|
||||
OrderStatus orderStatusPending = OrderStatus.PENDING;
|
||||
|
||||
EnumMapper enumMapper = new EnumMapperImpl();
|
||||
|
||||
assertEquals(CmsOrderStatus.APPROVED, enumMapper.map(orderStatusApproved));
|
||||
assertEquals(CmsOrderStatus.DELIVERED, enumMapper.map(orderStatusDelivered));
|
||||
assertEquals(CmsOrderStatus.PENDING, enumMapper.map(orderStatusPending));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingConfiguredWithRemainingMapstruct_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
EnumMapper enumMapper = new EnumMapperImpl();
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.mapDefault(userStatusDeleted));
|
||||
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.mapDefault(userStatusPending));
|
||||
assertEquals(ExternalUserStatus.ACTIVE, enumMapper.mapDefault(userStatusActive));
|
||||
}
|
||||
}
|
||||
@@ -9,3 +9,4 @@ This module contains articles about Object-oriented programming (OOP) patterns i
|
||||
- [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy)
|
||||
- [Using an Interface vs. Abstract Class in Java](https://www.baeldung.com/java-interface-vs-abstract-class)
|
||||
- [Should We Create an Interface for Only One Implementation?](https://www.baeldung.com/java-interface-single-implementation)
|
||||
- [How to Deep Copy an ArrayList in Java](https://www.baeldung.com/java-arraylist-deep-copy)
|
||||
|
||||
+2
-1
@@ -65,6 +65,7 @@ public class NioVsNio2UnitTest {
|
||||
public void listFilesUsingWalk() throws Exception {
|
||||
Path path = Paths.get("src/test");
|
||||
Stream<Path> walk = Files.walk(path);
|
||||
walk.forEach(System.out::println);
|
||||
|
||||
assertThat(walk.findAny()).isPresent();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
### Relevant Articles:
|
||||
- [Java Program to Estimate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi)
|
||||
- [Convert Integer to Hexadecimal in Java](https://www.baeldung.com/java-convert-int-to-hex)
|
||||
- [Integer.class Vs. Integer.TYPE Vs. int.class](https://www.baeldung.com/java-integer-class-vs-type-vs-int)
|
||||
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
|
||||
- More articles: [[<-- prev]](../core-java-numbers-5)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user