@@ -0,0 +1,5 @@
|
||||
## Core Java Arrays (Part 3)
|
||||
|
||||
This module contains articles about Java arrays
|
||||
|
||||
## Relevant Articles
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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-arrays-3</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-arrays-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.14.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.arrays.deepequals;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ArraysDeepEqualsUnitTest {
|
||||
|
||||
class Person {
|
||||
private int id;
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
Person(int id, String name, int age) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (!(obj instanceof Person))
|
||||
return false;
|
||||
Person person = (Person) obj;
|
||||
return id == person.id && name.equals(person.name) && age == person.age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name, age);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoUnidimensionalObjectTypeArrays_whenUsingEqualsAndDeepEquals_thenBothShouldReturnTrue() {
|
||||
Object[] anArray = new Object[] { "string1", "string2", "string3" };
|
||||
Object[] anotherArray = new Object[] { "string1", "string2", "string3" };
|
||||
|
||||
assertTrue(Arrays.equals(anArray, anotherArray));
|
||||
assertTrue(Arrays.deepEquals(anArray, anotherArray));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoUnidimensionalObjectTypeArraysWithNullElements_whenUsingEqualsAndDeepEquals_thenBothShouldReturnTrue() {
|
||||
Object[] anArray = new Object[] { "string1", null, "string3" };
|
||||
Object[] anotherArray = new Object[] { "string1", null, "string3" };
|
||||
|
||||
assertTrue(Arrays.equals(anArray, anotherArray));
|
||||
assertTrue(Arrays.deepEquals(anArray, anotherArray));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoUnidimensionalObjectTypeArraysWithNestedElements_whenUsingEqualsAndDeepEquals_thenShouldReturnDifferently() {
|
||||
Object[] anArray = new Object[] { "string1", null, new String[] { "nestedString1", "nestedString2" } };
|
||||
Object[] anotherArray = new Object[] { "string1", null, new String[] { "nestedString1", "nestedString2" } };
|
||||
|
||||
assertFalse(Arrays.equals(anArray, anotherArray));
|
||||
assertTrue(Arrays.deepEquals(anArray, anotherArray));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoMultidimensionalPrimitiveTypeArrays_whenUsingEqualsAndDeepEquals_thenBothShouldReturnDifferently() {
|
||||
int[][] anArray = { { 1, 2, 3 }, { 4, 5, 6, 9 }, { 7 } };
|
||||
int[][] anotherArray = { { 1, 2, 3 }, { 4, 5, 6, 9 }, { 7 } };
|
||||
|
||||
assertFalse(Arrays.equals(anArray, anotherArray));
|
||||
assertTrue(Arrays.deepEquals(anArray, anotherArray));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoMultidimensionalObjectTypeArrays_whenUsingEqualsAndDeepEquals_thenBothShouldReturnDifferently() {
|
||||
Person personArray1[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } };
|
||||
Person personArray2[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } };
|
||||
|
||||
assertFalse(Arrays.equals(personArray1, personArray2));
|
||||
assertTrue(Arrays.deepEquals(personArray1, personArray2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoMultidimensionalObjectTypeArrays_whenUsingDeepEqualsFromObjectsAndArraysClasses_thenBothShouldReturnTrue() {
|
||||
Person personArray1[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } };
|
||||
Person personArray2[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } };
|
||||
|
||||
assertTrue(Objects.deepEquals(personArray1, personArray2));
|
||||
assertTrue(Arrays.deepEquals(personArray1, personArray2));
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
public class Find2ndLargestInArray {
|
||||
|
||||
public static int find2ndLargestElement(int[] array) {
|
||||
int maxElement = array[0];
|
||||
int secondLargestElement = -1;
|
||||
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
if (maxElement <= array[index]) {
|
||||
secondLargestElement = maxElement;
|
||||
maxElement = array[index];
|
||||
} else if (secondLargestElement < array[index]) {
|
||||
secondLargestElement = array[index];
|
||||
}
|
||||
}
|
||||
return secondLargestElement;
|
||||
}
|
||||
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class FindElementInArray {
|
||||
|
||||
public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) {
|
||||
boolean actualResult = false;
|
||||
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
if (element == array[index]) {
|
||||
actualResult = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return actualResult;
|
||||
}
|
||||
|
||||
public static boolean findGivenElementInArrayUsingStream(int[] array, int element) {
|
||||
return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent();
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class Find2ndLargestInArrayUnitTest {
|
||||
@Test
|
||||
public void givenAnIntArray_thenFind2ndLargestElement() {
|
||||
int[] array = { 1, 3, 24, 16, 87, 20 };
|
||||
int expected2ndLargest = 24;
|
||||
|
||||
int actualSecondLargestElement = Find2ndLargestInArray.find2ndLargestElement(array);
|
||||
|
||||
Assert.assertEquals(expected2ndLargest, actualSecondLargestElement);
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindElementInArrayUnitTest {
|
||||
@Test
|
||||
public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() {
|
||||
int[] array = { 1, 3, 4, 8, 19, 20 };
|
||||
int element = 19;
|
||||
boolean expectedResult = true;
|
||||
boolean actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
|
||||
Assert.assertEquals(expectedResult, actualResult);
|
||||
|
||||
element = 78;
|
||||
expectedResult = false;
|
||||
actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
|
||||
Assert.assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntArray_whenUsingStream_thenFindAnElement() {
|
||||
int[] array = { 15, 16, 12, 18 };
|
||||
int element = 16;
|
||||
boolean expectedResult = true;
|
||||
boolean actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
|
||||
Assert.assertEquals(expectedResult, actualResult);
|
||||
|
||||
element = 20;
|
||||
expectedResult = false;
|
||||
actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
|
||||
Assert.assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
This module contains articles about core Java input and output (IO)
|
||||
|
||||
### Relevant Articles:
|
||||
- [How to Read a File in Java](https://www.baeldung.com/reading-file-in-java)
|
||||
- [Java – Read from File](https://www.baeldung.com/java-read-file)
|
||||
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
|
||||
- [Java – Directory Size](https://www.baeldung.com/java-folder-size)
|
||||
- [File Size in Java](https://www.baeldung.com/java-file-size)
|
||||
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
package com.baeldung.readfile;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class FileOperationsManualTest {
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
InputStream inputStream = new FileInputStream(file);
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Class clazz = FileOperationsManualTest.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
|
||||
String expectedData = "MIT License";
|
||||
|
||||
Class clazz = Matchers.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||
String expectedData = "Example Domain";
|
||||
|
||||
URL urlObject = new URL("http://www.example.com/");
|
||||
|
||||
URLConnection urlConnection = urlObject.openConnection();
|
||||
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
String data = FileUtils.readFileToString(file, "UTF-8");
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
byte[] fileBytes = Files.readAllBytes(path);
|
||||
String data = new String(fileBytes);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
Stream<String> lines = Files.lines(path);
|
||||
String data = lines.collect(Collectors.joining("\n"));
|
||||
lines.close();
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||
StringBuilder resultStringBuilder = new StringBuilder();
|
||||
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
resultStringBuilder.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
return resultStringBuilder.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException {
|
||||
String expectedData = "This is a content of the file";
|
||||
|
||||
FileInputStream fis = new FileInputStream("src/test/resources/fileToRead.txt");
|
||||
String data = IOUtils.toString(fis, "UTF-8");
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
}
|
||||
+149
-53
@@ -1,11 +1,15 @@
|
||||
package com.baeldung.readfile;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
import org.junit.Ignore;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.Charset;
|
||||
@@ -13,55 +17,148 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Scanner;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JavaReadFromFileUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenReadWithBufferedReader_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
final String expected_value = "Hello, world!";
|
||||
|
||||
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read.in"));
|
||||
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/fileTest.txt"));
|
||||
final String currentLine = reader.readLine();
|
||||
reader.close();
|
||||
|
||||
assertEquals(expected_value, currentLine);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
|
||||
String expectedData = "Hello, world!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
InputStream inputStream = new FileInputStream(file);
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
||||
String expectedData = "Hello, world!";
|
||||
|
||||
Class clazz = JavaReadFromFileUnitTest.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
|
||||
String expectedData = "BSD License";
|
||||
|
||||
Class clazz = Matchers.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||
String expectedData = "Example Domain";
|
||||
|
||||
URL urlObject = new URL("http://www.example.com/");
|
||||
|
||||
URLConnection urlConnection = urlObject.openConnection();
|
||||
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
||||
String expectedData = "Hello, world!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
String data = FileUtils.readFileToString(file, "UTF-8");
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello, world!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
byte[] fileBytes = Files.readAllBytes(path);
|
||||
String data = new String(fileBytes);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello, world!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
Stream<String> lines = Files.lines(path);
|
||||
String data = lines.collect(Collectors.joining("\n"));
|
||||
lines.close();
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException {
|
||||
String expectedData = "Hello, world!";
|
||||
|
||||
FileInputStream fis = new FileInputStream("src/test/resources/fileTest.txt");
|
||||
String data = IOUtils.toString(fis, "UTF-8");
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithScanner_thenCorrect() throws IOException {
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/test_read1.in"));
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/fileTest.txt"));
|
||||
scanner.useDelimiter(" ");
|
||||
|
||||
assertTrue(scanner.hasNext());
|
||||
assertEquals("Hello", scanner.next());
|
||||
assertEquals("world", scanner.next());
|
||||
assertEquals(1, scanner.nextInt());
|
||||
assertEquals("Hello,", scanner.next());
|
||||
assertEquals("world!", scanner.next());
|
||||
|
||||
scanner.close();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithScannerTwoDelimiters_thenCorrect() throws IOException {
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/test_read2.in"));
|
||||
scanner.useDelimiter(",| ");
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/fileTest.txt"));
|
||||
scanner.useDelimiter("\\s|,");
|
||||
|
||||
assertTrue(scanner.hasNextInt());
|
||||
assertEquals(2, scanner.nextInt());
|
||||
assertEquals(3, scanner.nextInt());
|
||||
assertEquals(4, scanner.nextInt());
|
||||
assertTrue(scanner.hasNext());
|
||||
assertEquals("Hello", scanner.next());
|
||||
assertEquals("", scanner.next());
|
||||
assertEquals("world!", scanner.next());
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithStreamTokenizer_thenCorrectTokens() throws IOException {
|
||||
final FileReader reader = new FileReader("src/test/resources/test_read3.in");
|
||||
final FileReader reader = new FileReader("src/test/resources/fileTestTokenizer.txt");
|
||||
final StreamTokenizer tokenizer = new StreamTokenizer(reader);
|
||||
|
||||
tokenizer.nextToken();
|
||||
@@ -78,49 +175,36 @@ public class JavaReadFromFileUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadWithDataInputStream_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello";
|
||||
String expectedValue = "Hello, world!";
|
||||
String file ="src/test/resources/fileTest.txt";
|
||||
|
||||
String result;
|
||||
final DataInputStream reader = new DataInputStream(new FileInputStream("src/test/resources/test_read4.in"));
|
||||
result = reader.readUTF();
|
||||
reader.close();
|
||||
String result = null;
|
||||
|
||||
assertEquals(expected_value, result);
|
||||
}
|
||||
DataInputStream reader = new DataInputStream(new FileInputStream(file));
|
||||
int nBytesToRead = reader.available();
|
||||
if(nBytesToRead > 0) {
|
||||
byte[] bytes = new byte[nBytesToRead];
|
||||
reader.read(bytes);
|
||||
result = new String(bytes);
|
||||
}
|
||||
|
||||
public void whenReadTwoFilesWithSequenceInputStream_thenCorrect() throws IOException {
|
||||
final int expected_value1 = 2000;
|
||||
final int expected_value2 = 5000;
|
||||
|
||||
final FileInputStream stream1 = new FileInputStream("src/test/resources/test_read5.in");
|
||||
final FileInputStream stream2 = new FileInputStream("src/test/resources/test_read6.in");
|
||||
|
||||
final SequenceInputStream sequence = new SequenceInputStream(stream1, stream2);
|
||||
final DataInputStream reader = new DataInputStream(sequence);
|
||||
|
||||
assertEquals(expected_value1, reader.readInt());
|
||||
assertEquals(expected_value2, reader.readInt());
|
||||
|
||||
reader.close();
|
||||
stream2.close();
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // TODO
|
||||
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
|
||||
final String expected_value = "青空";
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/fileTestUtf8.txt"), "UTF-8"));
|
||||
final String currentLine = reader.readLine();
|
||||
reader.close();
|
||||
LOG.debug(currentLine);
|
||||
|
||||
|
||||
assertEquals(expected_value, currentLine);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadFileContentsIntoString_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world \n Test line \n";
|
||||
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read8.in"));
|
||||
final String expected_value = "Hello, world!\n";
|
||||
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/fileTest.txt"));
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
String currentLine = reader.readLine();
|
||||
while (currentLine != null) {
|
||||
@@ -136,8 +220,8 @@ public class JavaReadFromFileUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadWithFileChannel_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
final RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
final String expected_value = "Hello, world!";
|
||||
final RandomAccessFile reader = new RandomAccessFile("src/test/resources/fileTest.txt", "r");
|
||||
final FileChannel channel = reader.getChannel();
|
||||
|
||||
int bufferSize = 1024;
|
||||
@@ -154,8 +238,8 @@ public class JavaReadFromFileUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadSmallFileJava7_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
final Path path = Paths.get("src/test/resources/test_read.in");
|
||||
final String expected_value = "Hello, world!";
|
||||
final Path path = Paths.get("src/test/resources/fileTest.txt");
|
||||
|
||||
final String read = Files.readAllLines(path, Charset.defaultCharset()).get(0);
|
||||
assertEquals(expected_value, read);
|
||||
@@ -163,12 +247,24 @@ public class JavaReadFromFileUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadLargeFileJava7_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
final String expected_value = "Hello, world!";
|
||||
|
||||
final Path path = Paths.get("src/test/resources/test_read.in");
|
||||
final Path path = Paths.get("src/test/resources/fileTest.txt");
|
||||
final BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset());
|
||||
final String line = reader.readLine();
|
||||
assertEquals(expected_value, line);
|
||||
}
|
||||
|
||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||
StringBuilder resultStringBuilder = new StringBuilder();
|
||||
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
resultStringBuilder.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
return resultStringBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
Hello World from fileTest.txt!!!
|
||||
Hello, world!
|
||||
@@ -1 +0,0 @@
|
||||
Hello world 1
|
||||
@@ -1 +0,0 @@
|
||||
2,3 4
|
||||
Binary file not shown.
@@ -1,2 +0,0 @@
|
||||
Hello world
|
||||
Test line
|
||||
@@ -31,6 +31,7 @@
|
||||
<module>core-java-annotations</module>
|
||||
<module>core-java-arrays</module>
|
||||
<module>core-java-arrays-2</module>
|
||||
<module>core-java-arrays-3</module>
|
||||
|
||||
<module>core-java-collections</module>
|
||||
<module>core-java-collections-2</module>
|
||||
|
||||
@@ -20,6 +20,10 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-mongodb</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-cassandra</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
|
||||
@@ -1,13 +1,37 @@
|
||||
package com.baeldung.dddhexagonalspring;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.application.cli.CliOrderController;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource(value = { "classpath:ddd-layers.properties" })
|
||||
public class DomainLayerApplication {
|
||||
public class DomainLayerApplication implements CommandLineRunner {
|
||||
|
||||
public static void main(final String[] args) {
|
||||
SpringApplication.run(DomainLayerApplication.class, args);
|
||||
SpringApplication application = new SpringApplication(DomainLayerApplication.class);
|
||||
// uncomment to run just the console application
|
||||
// application.setWebApplicationType(WebApplicationType.NONE);
|
||||
application.run(args);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public CliOrderController orderController;
|
||||
|
||||
@Autowired
|
||||
public ConfigurableApplicationContext context;
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
orderController.createCompleteOrder();
|
||||
orderController.createIncompleteOrder();
|
||||
// uncomment to stop the context when execution is done
|
||||
// context.close();
|
||||
}
|
||||
}
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.dddhexagonalspring.application.cli;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.domain.Product;
|
||||
import com.baeldung.dddhexagonalspring.domain.service.OrderService;
|
||||
|
||||
@Component
|
||||
public class CliOrderController {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CliOrderController.class);
|
||||
|
||||
private final OrderService orderService;
|
||||
|
||||
@Autowired
|
||||
public CliOrderController(OrderService orderService) {
|
||||
this.orderService = orderService;
|
||||
}
|
||||
|
||||
public void createCompleteOrder() {
|
||||
LOG.info("<<Create complete order>>");
|
||||
UUID orderId = createOrder();
|
||||
orderService.completeOrder(orderId);
|
||||
}
|
||||
|
||||
public void createIncompleteOrder() {
|
||||
LOG.info("<<Create incomplete order>>");
|
||||
UUID orderId = createOrder();
|
||||
}
|
||||
|
||||
private UUID createOrder() {
|
||||
LOG.info("Placing a new order with two products");
|
||||
Product mobilePhone = new Product(UUID.randomUUID(), BigDecimal.valueOf(200), "mobile");
|
||||
Product razor = new Product(UUID.randomUUID(), BigDecimal.valueOf(50), "razor");
|
||||
LOG.info("Creating order with mobile phone");
|
||||
UUID orderId = orderService.createOrder(mobilePhone);
|
||||
LOG.info("Adding a razor to the order");
|
||||
orderService.addProduct(orderId, razor);
|
||||
return orderId;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.dddhexagonalspring.application.controller;
|
||||
package com.baeldung.dddhexagonalspring.application.rest;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.application.request.AddProductRequest;
|
||||
import com.baeldung.dddhexagonalspring.application.request.CreateOrderRequest;
|
||||
@@ -4,6 +4,7 @@ import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public class Order {
|
||||
@@ -40,13 +41,11 @@ public class Order {
|
||||
}
|
||||
|
||||
private OrderItem getOrderItem(final UUID id) {
|
||||
return orderItems
|
||||
.stream()
|
||||
.filter(orderItem -> orderItem
|
||||
.getProductId()
|
||||
.equals(id))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new DomainException("Product with " + id + " doesn't exist."));
|
||||
return orderItems.stream()
|
||||
.filter(orderItem -> orderItem.getProductId()
|
||||
.equals(id))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new DomainException("Product with " + id + " doesn't exist."));
|
||||
}
|
||||
|
||||
private void validateState() {
|
||||
@@ -77,6 +76,21 @@ public class Order {
|
||||
return Collections.unmodifiableList(orderItems);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, orderItems, price, status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (!(obj instanceof Order))
|
||||
return false;
|
||||
Order other = (Order) obj;
|
||||
return Objects.equals(id, other.id) && Objects.equals(orderItems, other.orderItems) && Objects.equals(price, other.price) && status == other.status;
|
||||
}
|
||||
|
||||
private Order() {
|
||||
}
|
||||
}
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.dddhexagonalspring.infrastracture.configuration;
|
||||
|
||||
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra.SpringDataCassandraOrderRepository;
|
||||
|
||||
@EnableCassandraRepositories(basePackageClasses = SpringDataCassandraOrderRepository.class)
|
||||
public class CassandraConfiguration {
|
||||
|
||||
}
|
||||
+3
-2
@@ -1,8 +1,9 @@
|
||||
package com.baeldung.dddhexagonalspring.infrastracture.configuration;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.infrastracture.repository.SpringDataOrderRepository;
|
||||
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
||||
|
||||
@EnableMongoRepositories(basePackageClasses = SpringDataOrderRepository.class)
|
||||
import com.baeldung.dddhexagonalspring.infrastracture.repository.mongo.SpringDataMongoOrderRepository;
|
||||
|
||||
@EnableMongoRepositories(basePackageClasses = SpringDataMongoOrderRepository.class)
|
||||
public class MongoDBConfiguration {
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.domain.Order;
|
||||
import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository;
|
||||
|
||||
@Component
|
||||
public class CassandraDbOrderRepository implements OrderRepository {
|
||||
|
||||
private final SpringDataCassandraOrderRepository orderRepository;
|
||||
|
||||
@Autowired
|
||||
public CassandraDbOrderRepository(SpringDataCassandraOrderRepository orderRepository) {
|
||||
this.orderRepository = orderRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Order> findById(UUID id) {
|
||||
Optional<OrderEntity> orderEntity = orderRepository.findById(id);
|
||||
if (orderEntity.isPresent()) {
|
||||
return Optional.of(orderEntity.get()
|
||||
.toOrder());
|
||||
} else {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(Order order) {
|
||||
orderRepository.save(new OrderEntity(order));
|
||||
}
|
||||
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.domain.Order;
|
||||
import com.baeldung.dddhexagonalspring.domain.OrderItem;
|
||||
import com.baeldung.dddhexagonalspring.domain.OrderStatus;
|
||||
import com.baeldung.dddhexagonalspring.domain.Product;
|
||||
|
||||
public class OrderEntity {
|
||||
|
||||
@PrimaryKey
|
||||
private UUID id;
|
||||
private OrderStatus status;
|
||||
private List<OrderItemEntity> orderItemEntities;
|
||||
private BigDecimal price;
|
||||
|
||||
public OrderEntity(UUID id, OrderStatus status, List<OrderItemEntity> orderItemEntities, BigDecimal price) {
|
||||
this.id = id;
|
||||
this.status = status;
|
||||
this.orderItemEntities = orderItemEntities;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public OrderEntity() {
|
||||
}
|
||||
|
||||
public OrderEntity(Order order) {
|
||||
this.id = order.getId();
|
||||
this.price = order.getPrice();
|
||||
this.status = order.getStatus();
|
||||
this.orderItemEntities = order.getOrderItems()
|
||||
.stream()
|
||||
.map(OrderItemEntity::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
}
|
||||
|
||||
public Order toOrder() {
|
||||
List<OrderItem> orderItems = orderItemEntities.stream()
|
||||
.map(OrderItemEntity::toOrderItem)
|
||||
.collect(Collectors.toList());
|
||||
List<Product> namelessProducts = orderItems.stream()
|
||||
.map(orderItem -> new Product(orderItem.getProductId(), orderItem.getPrice(), ""))
|
||||
.collect(Collectors.toList());
|
||||
Order order = new Order(id, namelessProducts.remove(0));
|
||||
namelessProducts.forEach(product -> order.addOrder(product));
|
||||
if (status == OrderStatus.COMPLETED) {
|
||||
order.complete();
|
||||
}
|
||||
return order;
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public OrderStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public List<OrderItemEntity> getOrderItems() {
|
||||
return orderItemEntities;
|
||||
}
|
||||
|
||||
public BigDecimal getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.data.cassandra.core.mapping.UserDefinedType;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.domain.OrderItem;
|
||||
import com.baeldung.dddhexagonalspring.domain.Product;
|
||||
|
||||
@UserDefinedType
|
||||
public class OrderItemEntity {
|
||||
|
||||
private UUID productId;
|
||||
private BigDecimal price;
|
||||
|
||||
public OrderItemEntity() {
|
||||
}
|
||||
|
||||
public OrderItemEntity(final OrderItem orderItem) {
|
||||
this.productId = orderItem.getProductId();
|
||||
this.price = orderItem.getPrice();
|
||||
}
|
||||
|
||||
public OrderItem toOrderItem() {
|
||||
return new OrderItem(new Product(productId, price, ""));
|
||||
}
|
||||
|
||||
public UUID getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(UUID productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public BigDecimal getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(BigDecimal price) {
|
||||
this.price = price;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.data.cassandra.repository.CassandraRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface SpringDataCassandraOrderRepository extends CassandraRepository<OrderEntity, UUID> {
|
||||
}
|
||||
+11
-8
@@ -1,20 +1,23 @@
|
||||
package com.baeldung.dddhexagonalspring.infrastracture.repository;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.domain.Order;
|
||||
import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
package com.baeldung.dddhexagonalspring.infrastracture.repository.mongo;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.dddhexagonalspring.domain.Order;
|
||||
import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository;
|
||||
|
||||
@Component
|
||||
@Primary
|
||||
public class MongoDbOrderRepository implements OrderRepository {
|
||||
|
||||
private final SpringDataOrderRepository orderRepository;
|
||||
private final SpringDataMongoOrderRepository orderRepository;
|
||||
|
||||
@Autowired
|
||||
public MongoDbOrderRepository(final SpringDataOrderRepository orderRepository) {
|
||||
public MongoDbOrderRepository(final SpringDataMongoOrderRepository orderRepository) {
|
||||
this.orderRepository = orderRepository;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user