Merge branch 'master' of github.com:markathomas/tutorials into BAEL-3817

This commit is contained in:
mthomas 2020-02-19 12:20:14 -06:00
commit a3aa277766
486 changed files with 29009 additions and 1194 deletions

1
.gitignore vendored
View File

@ -65,6 +65,7 @@ core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/
jmeter/src/main/resources/*-JMeter.csv
ninja/devDb.mv.db
**/node_modules/
**/dist

View File

@ -16,4 +16,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
- [Kruskals Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)

View File

@ -0,0 +1,141 @@
package com.baeldung.algorithms.balancedbinarytree;
public class AVLTree {
public class Node {
int key;
int height;
Node left;
Node right;
Node(int key) {
this.key = key;
}
}
private Node root;
public Node find(int key) {
Node current = root;
while (current != null) {
if (current.key == key) {
break;
}
current = current.key < key ? current.right : current.left;
}
return current;
}
public void insert(int key) {
root = insert(root, key);
}
public void delete(int key) {
root = delete(root, key);
}
public Node getRoot() {
return root;
}
public int height() {
return root == null ? -1 : root.height;
}
private Node insert(Node node, int key) {
if (node == null) {
return new Node(key);
} else if (node.key > key) {
node.left = insert(node.left, key);
} else if (node.key < key) {
node.right = insert(node.right, key);
} else {
throw new RuntimeException("duplicate Key!");
}
return rebalance(node);
}
private Node delete(Node node, int key) {
if (node == null) {
return node;
} else if (node.key > key) {
node.left = delete(node.left, key);
} else if (node.key < key) {
node.right = delete(node.right, key);
} else {
if (node.left == null || node.right == null) {
node = (node.left == null) ? node.right : node.left;
} else {
Node mostLeftChild = mostLeftChild(node.right);
node.key = mostLeftChild.key;
node.right = delete(node.right, node.key);
}
}
if (node != null) {
node = rebalance(node);
}
return node;
}
private Node mostLeftChild(Node node) {
Node current = node;
/* loop down to find the leftmost leaf */
while (current.left != null) {
current = current.left;
}
return current;
}
private Node rebalance(Node z) {
updateHeight(z);
int balance = getBalance(z);
if (balance > 1) {
if (height(z.right.right) > height(z.right.left)) {
z = rotateLeft(z);
} else {
z.right = rotateRight(z.right);
z = rotateLeft(z);
}
} else if (balance < -1) {
if (height(z.left.left) > height(z.left.right)) {
z = rotateRight(z);
} else {
z.left = rotateLeft(z.left);
z = rotateRight(z);
}
}
return z;
}
private Node rotateRight(Node y) {
Node x = y.left;
Node z = x.right;
x.right = y;
y.left = z;
updateHeight(y);
updateHeight(x);
return x;
}
private Node rotateLeft(Node y) {
Node x = y.right;
Node z = x.left;
x.left = y;
y.right = z;
updateHeight(y);
updateHeight(x);
return x;
}
private void updateHeight(Node n) {
n.height = 1 + Math.max(height(n.left), height(n.right));
}
private int height(Node n) {
return n == null ? -1 : n.height;
}
public int getBalance(Node n) {
return (n == null) ? 0 : height(n.right) - height(n.left);
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.algorithms.balancedbinarytree;
import org.junit.Assert;
import org.junit.Test;
public class AVLTreeUnitTest {
@Test
public void givenEmptyTree_whenHeightCalled_shouldReturnMinus1() {
AVLTree tree = new AVLTree();
Assert.assertEquals(-1, tree.height());
}
@Test
public void givenEmptyTree_whenInsertCalled_heightShouldBeZero() {
AVLTree tree = new AVLTree();
tree.insert(1);
Assert.assertEquals(0, tree.height());
}
@Test
public void givenEmptyTree_whenInsertCalled_treeShouldBeAvl() {
AVLTree tree = new AVLTree();
tree.insert(1);
Assert.assertTrue(isAVL(tree));
}
@Test
public void givenSampleTree_whenInsertCalled_treeShouldBeAvl() {
AVLTree tree = getSampleAVLTree();
int newKey = 11;
tree.insert(newKey);
Assert.assertTrue(isAVL(tree));
}
@Test
public void givenSampleTree_whenFindExistingKeyCalled_shouldReturnMatchedNode() {
AVLTree tree = getSampleAVLTree();
int existingKey = 2;
AVLTree.Node result = tree.find(existingKey);
Assert.assertEquals(result.key, existingKey);
}
@Test
public void givenSampleTree_whenFindNotExistingKeyCalled_shouldReturnNull() {
AVLTree tree = getSampleAVLTree();
int notExistingKey = 11;
AVLTree.Node result = tree.find(notExistingKey);
Assert.assertNull(result);
}
@Test
public void givenEmptyTree_whenDeleteCalled_treeShouldBeAvl() {
AVLTree tree = new AVLTree();
tree.delete(1);
Assert.assertTrue(isAVL(tree));
}
@Test
public void givenSampleTree_whenDeleteCalled_treeShouldBeAvl() {
AVLTree tree = getSampleAVLTree();
tree.delete(1);
Assert.assertTrue(isAVL(tree, tree.getRoot()));
}
private boolean isAVL(AVLTree tree) {
return isAVL(tree, tree.getRoot());
}
private boolean isAVL(AVLTree tree, AVLTree.Node node) {
if ( node == null )
return true;
int balance = tree.getBalance(node);
return (balance <= 1 && balance >= -1) && isAVL(tree, node.left) && isAVL(tree, node.right);
}
private AVLTree getSampleAVLTree() {
AVLTree avlTree = new AVLTree();
for (int i = 0; i < 10; i++)
avlTree.insert(i);
return avlTree;
}
}

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)

View File

@ -6,3 +6,6 @@ This module contains articles about Apache POI
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel)
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://github.com/eugenp/tutorials/tree/master/apache-poi)

View File

@ -1,4 +1,4 @@
package com.baeldung.poi.excel;
package com.baeldung.poi.excel.merge;
import static org.junit.Assert.assertEquals;

View File

@ -3,3 +3,5 @@
This module contains articles about Apache RocketMQ
### Relevant Articles:
- [Apache RocketMQ with Spring Boot](https://www.baeldung.com/apache-rocketmq-spring-boot)

View File

@ -106,7 +106,7 @@
<arguments>
<argument>java</argument>
<argument>-jar</argument>
<argument>sample-blade-app.jar</argument>
<argument>blade.jar</argument>
</arguments>
</configuration>
</execution>

View File

@ -1,3 +1,4 @@
### Relevant articles:
- [Java Switch Statement](https://www.baeldung.com/java-switch)
- [New Java 13 Features](https://www.baeldung.com/java-13-new-features)

View File

@ -13,4 +13,5 @@ This module contains articles about Java arrays
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list)
- [Arrays.sort vs Arrays.parallelSort](https://www.baeldung.com/java-arrays-sort-vs-parallelsort)
- [[<-- Prev]](/core-java-modules/core-java-arrays)

View File

@ -69,7 +69,7 @@ public class SortComparisonUnitTest {
}
@Test
public void givenArrayOfIntegers_whenUsingArraysSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() {
public void givenArrayOfIntegers_whenUsingArraysSortWithRange_thenSortRangeOfArrayAsc() {
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 };
@ -89,7 +89,7 @@ public class SortComparisonUnitTest {
}
@Test
public void givenArrayOfIntegers_whenUsingArraysParallelSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() {
public void givenArrayOfIntegers_whenUsingArraysParallelSortWithRange_thenSortRangeOfArrayAsc() {
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 };

View File

@ -0,0 +1,5 @@
## Core Java Arrays (Part 3)
This module contains articles about Java arrays
## Relevant Articles

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,4 +8,6 @@ This module contains articles about advanced topics about multithreading with co
- [Common Concurrency Pitfalls in Java](https://www.baeldung.com/java-common-concurrency-pitfalls)
- [Guide to RejectedExecutionHandler](https://www.baeldung.com/java-rejectedexecutionhandler)
[[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)
- [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing)
- [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -4,7 +4,7 @@ package com.baeldung.concurrent.volatilekeyword;
public class SharedObject {
private volatile int count=0;
void increamentCount(){
void incrementCount(){
count++;
}
public int getCount(){

View File

@ -10,7 +10,7 @@ public class SharedObjectManualTest {
public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
SharedObject sharedObject = new SharedObject();
Thread writer = new Thread(() -> sharedObject.increamentCount());
Thread writer = new Thread(() -> sharedObject.incrementCount());
writer.start();
Thread.sleep(100);
@ -31,11 +31,11 @@ public class SharedObjectManualTest {
@Test
public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
SharedObject sharedObject = new SharedObject();
Thread writerOne = new Thread(() -> sharedObject.increamentCount());
Thread writerOne = new Thread(() -> sharedObject.incrementCount());
writerOne.start();
Thread.sleep(100);
Thread writerTwo = new Thread(() -> sharedObject.increamentCount());
Thread writerTwo = new Thread(() -> sharedObject.incrementCount());
writerTwo.start();
Thread.sleep(100);

View File

@ -6,4 +6,5 @@ This module contains articles about date operations in Java.
- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends)
- [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day)
- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime)
- [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-1)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)

View File

@ -6,3 +6,4 @@ This module contains articles about core java exceptions
- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice)
- [Wrapping vs Rethrowing Exceptions in Java](https://www.baeldung.com/java-wrapping-vs-rethrowing-exceptions)
- [java.net.UnknownHostException: Invalid Hostname for Server](https://www.baeldung.com/java-unknownhostexception)

View File

@ -0,0 +1,32 @@
package com.baeldung.socketexception;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) throws IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public String sendMessage(String msg) throws IOException {
out.println(msg);
return in.readLine();
}
public void stopConnection() throws IOException {
in.close();
out.close();
clientSocket.close();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.socketexception;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) {
try {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String msg = in.readLine();
if (msg.contains("hi"))
out.println("hi");
else
out.println("didn't understand");
close();
stop();
} catch (IOException e) {
}
}
private void close() throws IOException {
in.close();
out.close();
}
private void stop() throws IOException {
clientSocket.close();
serverSocket.close();
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.socketexception;
import java.io.IOException;
import java.net.SocketException;
import java.util.concurrent.Executors;
import org.junit.BeforeClass;
import org.junit.Test;
public class SocketExceptionHandlingUnitTest {
@BeforeClass
public static void runServer() throws IOException, InterruptedException {
Executors.newSingleThreadExecutor()
.submit(() -> new SocketServer().start(6699));
Thread.sleep(100);
}
@Test
public void givenRunningServer_whenConnectToClosedSocket_thenHandleException() throws IOException {
SocketClient client = new SocketClient();
client.startConnection("127.0.0.1", 6699);
try {
client.sendMessage("hi");
client.sendMessage("hi again");
} catch (SocketException e) {
client.stopConnection();
}
}
}

View File

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

View File

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

View File

@ -1 +1 @@
Hello World from fileTest.txt!!!
Hello, world!

View File

@ -1 +0,0 @@
Hello world 1

View File

@ -1,2 +0,0 @@
Hello world
Test line

View File

@ -7,4 +7,6 @@ This module contains articles about core features in the Java language
- [Command-Line Arguments in Java](https://www.baeldung.com/java-command-line-arguments)
- [What is a POJO Class?](https://www.baeldung.com/java-pojo-class)
- [Java Default Parameters Using Method Overloading](https://www.baeldung.com/java-default-parameters-method-overloading)
- [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values)
- [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword)
- [[<-- Prev]](/core-java-modules/core-java-lang)

View File

@ -0,0 +1,27 @@
package com.baeldung.headlessmode;
import java.awt.GraphicsEnvironment;
import javax.swing.JOptionPane;
public class FlexibleApp {
public static final int HEADLESS = 0;
public static final int HEADED = 1;
public FlexibleApp() {
if (GraphicsEnvironment.isHeadless()) {
System.out.println("Hello World");
} else {
JOptionPane.showMessageDialog(null, "Hello World");
}
}
public static int iAmFlexible() {
if (GraphicsEnvironment.isHeadless()) {
return HEADLESS;
} else {
return HEADED;
}
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.headlessmode;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.awt.Canvas;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
public class HeadlessModeUnitTest {
private static final String IN_FILE = "/product.png";
private static final String OUT_FILE = System.getProperty("java.io.tmpdir") + "/product.jpg";
private static final String FORMAT = "jpg";
@Before
public void setUpHeadlessMode() {
System.setProperty("java.awt.headless", "true");
}
@Test
public void whenJavaAwtHeadlessSetToTrue_thenIsHeadlessReturnsTrue() {
assertThat(GraphicsEnvironment.isHeadless()).isTrue();
}
@Test
public void whenHeadlessMode_thenFontsWork() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String fonts[] = ge.getAvailableFontFamilyNames();
assertThat(fonts).isNotEmpty();
Font font = new Font(fonts[0], Font.BOLD, 14);
FontMetrics fm = (new Canvas()).getFontMetrics(font);
assertThat(fm.getHeight()).isGreaterThan(0);
assertThat(fm.getAscent()).isGreaterThan(0);
assertThat(fm.getDescent()).isGreaterThan(0);
}
@Test
public void whenHeadlessMode_thenImagesWork() throws IOException {
boolean result = false;
try (InputStream inStream = HeadlessModeUnitTest.class.getResourceAsStream(IN_FILE); FileOutputStream outStream = new FileOutputStream(OUT_FILE)) {
BufferedImage inputImage = ImageIO.read(inStream);
result = ImageIO.write(inputImage, FORMAT, outStream);
}
assertThat(result).isTrue();
}
@Test
public void whenHeadlessmode_thenFrameThrowsHeadlessException() {
assertThatExceptionOfType(HeadlessException.class).isThrownBy(() -> {
Frame frame = new Frame();
frame.setVisible(true);
frame.setSize(120, 120);
});
}
@Test
public void whenHeadless_thenFlexibleAppAdjustsItsBehavior() {
assertThat(FlexibleApp.iAmFlexible()).isEqualTo(FlexibleApp.HEADLESS);
}
@Test
public void whenHeaded_thenFlexibleAppAdjustsItsBehavior() {
Assume.assumeFalse(GraphicsEnvironment.isHeadless());
assertThat(FlexibleApp.iAmFlexible()).isEqualTo(FlexibleApp.HEADED);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@ -9,3 +9,4 @@
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
- [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator)
- [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow)
- [Obtaining a Power Set of a Set in Java](https://www.baeldung.com/java-power-set-of-a-set)

View File

@ -12,4 +12,5 @@ This module contains articles about Java syntax
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
- [Introduction to Basic Syntax in Java](https://www.baeldung.com/java-syntax)
- [Java protected Access Modifier](https://www.baeldung.com/java-protected-access-modifier)
- [Using the Not Operator in If Conditions in Java](https://www.baeldung.com/java-using-not-in-if-conditions)
- [[<-- Prev]](/core-java-modules/core-java-lang-syntax)

View File

@ -13,4 +13,7 @@ This module contains articles about Java syntax
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
- [Java Switch Statement](https://www.baeldung.com/java-switch)
- [Breaking Out of Nested Loops](https://www.baeldung.com/java-breaking-out-nested-loop)
- [Java Do-While Loop](https://www.baeldung.com/java-do-while-loop)
- [Java While Loop](https://www.baeldung.com/java-while-loop)
- [Java For Loop](https://www.baeldung.com/java-for-loop)
- [[More -->]](/core-java-modules/core-java-lang-syntax-2)

View File

@ -6,4 +6,5 @@
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception)

View File

@ -0,0 +1,10 @@
=========
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile)
- [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches)

View File

@ -2,9 +2,9 @@
<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-text</artifactId>
<artifactId>core-java-regex</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-text</name>
<name>core-java-regex</name>
<packaging>jar</packaging>
<parent>
@ -28,7 +28,7 @@
</dependencies>
<build>
<finalName>core-java-text</finalName>
<finalName>core-java-regex</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>

View File

@ -1,4 +1,4 @@
package com.baeldung.java.regex;
package com.baeldung.regex;
import static org.junit.Assert.*;

View File

@ -1,7 +0,0 @@
=========
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile)

View File

@ -2,7 +2,6 @@
### Relevant Articles:
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
@ -11,7 +10,6 @@
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)

View File

@ -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>
@ -113,7 +114,7 @@
<module>core-java-strings</module>
<module>core-java-sun</module>
<module>core-java-text</module>
<module>core-java-regex</module>
<!-- <module>core-java-time-measurements</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>multimodulemavenproject</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->

View File

@ -4,5 +4,5 @@ This module contains articles about Kotlin core features.
### Relevant articles:
- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates)
- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-conditional-operator)
- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-operator)
- [[<-- Prev]](/core-kotlin-modules/core-kotlin)

View File

@ -3,7 +3,7 @@
This module contains articles about Kotlin core features.
### Relevant articles:
- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin)
- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin-intro)
- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability)
- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number)
- [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project)

View File

@ -8,3 +8,4 @@ This module contains articles about data structures in Java
- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree)
- [Circular Linked List Java Implementation](https://www.baeldung.com/java-circular-linked-list)
- [How to Print a Binary Tree Diagram](https://www.baeldung.com/java-print-binary-tree-diagram)
- [Introduction to Big Queue](https://www.baeldung.com/java-big-queue)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package com.baeldung.dddhexagonalspring.infrastracture.repository;
package com.baeldung.dddhexagonalspring.infrastracture.repository.mongo;
import com.baeldung.dddhexagonalspring.domain.Order;
import org.springframework.data.mongodb.repository.MongoRepository;
@ -7,5 +7,5 @@ import org.springframework.stereotype.Repository;
import java.util.UUID;
@Repository
public interface SpringDataOrderRepository extends MongoRepository<Order, UUID> {
public interface SpringDataMongoOrderRepository extends MongoRepository<Order, UUID> {
}

View File

@ -1,5 +1,12 @@
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=order-database
spring.data.mongodb.username=order
spring.data.mongodb.password=order
spring.data.mongodb.password=order
spring.data.cassandra.keyspaceName=order_database
spring.data.cassandra.username=cassandra
spring.data.cassandra.password=cassandra
spring.data.cassandra.contactPoints=localhost
spring.data.cassandra.port=9042

View File

@ -0,0 +1,57 @@
package com.baeldung.dddhexagonalspring.infrastracture.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import com.baeldung.dddhexagonalspring.domain.Order;
import com.baeldung.dddhexagonalspring.domain.Product;
import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository;
import com.baeldung.dddhexagonalspring.infrastracture.repository.cassandra.SpringDataCassandraOrderRepository;
@SpringJUnitConfig
@SpringBootTest
@TestPropertySource("classpath:ddd-layers-test.properties")
class CassandraDbOrderRepositoryIntegrationTest {
@Autowired
private SpringDataCassandraOrderRepository cassandraOrderRepository;
@Autowired
private OrderRepository orderRepository;
@AfterEach
void cleanUp() {
cassandraOrderRepository.deleteAll();
}
@Test
void shouldFindById_thenReturnOrder() {
// given
final UUID id = UUID.randomUUID();
final Order order = createOrder(id);
order.addOrder(new Product(UUID.randomUUID(), BigDecimal.TEN, "second"));
order.complete();
// when
orderRepository.save(order);
final Optional<Order> result = orderRepository.findById(id);
assertEquals(order, result.get());
}
private Order createOrder(UUID id) {
return new Order(id, new Product(UUID.randomUUID(), BigDecimal.TEN, "product"));
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.dddhexagonalspring.infrastracture.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import com.baeldung.dddhexagonalspring.domain.Order;
import com.baeldung.dddhexagonalspring.domain.Product;
import com.baeldung.dddhexagonalspring.domain.repository.OrderRepository;
import com.baeldung.dddhexagonalspring.infrastracture.repository.mongo.SpringDataMongoOrderRepository;
@SpringJUnitConfig
@SpringBootTest
@TestPropertySource("classpath:ddd-layers-test.properties")
class MongoDbOrderRepositoryIntegrationTest {
@Autowired
private SpringDataMongoOrderRepository mongoOrderRepository;
@Autowired
private OrderRepository orderRepository;
@AfterEach
void cleanUp() {
mongoOrderRepository.deleteAll();
}
@Test
void shouldFindById_thenReturnOrder() {
// given
final UUID id = UUID.randomUUID();
final Order order = createOrder(id);
// when
orderRepository.save(order);
final Optional<Order> result = orderRepository.findById(id);
assertEquals(order, result.get());
}
private Order createOrder(UUID id) {
return new Order(id, new Product(UUID.randomUUID(), BigDecimal.TEN, "product"));
}
}

View File

@ -2,6 +2,9 @@ package com.baeldung.dddhexagonalspring.infrastracture.repository;
import com.baeldung.dddhexagonalspring.domain.Order;
import com.baeldung.dddhexagonalspring.domain.Product;
import com.baeldung.dddhexagonalspring.infrastracture.repository.mongo.MongoDbOrderRepository;
import com.baeldung.dddhexagonalspring.infrastracture.repository.mongo.SpringDataMongoOrderRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -14,12 +17,12 @@ import static org.mockito.Mockito.*;
class MongoDbOrderRepositoryUnitTest {
private SpringDataOrderRepository springDataOrderRepository;
private SpringDataMongoOrderRepository springDataOrderRepository;
private MongoDbOrderRepository tested;
@BeforeEach
void setUp(){
springDataOrderRepository = mock(SpringDataOrderRepository.class);
void setUp() {
springDataOrderRepository = mock(SpringDataMongoOrderRepository.class);
tested = new MongoDbOrderRepository(springDataOrderRepository);
}

View File

@ -4,4 +4,6 @@ To run this project, follow these steps:
* Run the application database by executing `docker-compose up` in this directory.
* Launch the Spring Boot Application (DomainLayerApplication).
* By default, application will connect to this database (configuration in *ddd-layers.properties*)
* By default, the application will connect to the one of the two databases (configuration in *ddd-layers.properties*)
* check `CassandraDbOrderRepository.java` and `MongoDbOrderRepository.java`
* switch between the databases by making one of the above beans primary using the `@Primary` annotation

View File

@ -0,0 +1,12 @@
CREATE KEYSPACE IF NOT exists order_database
WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};
CREATE TYPE IF NOT EXISTS order_database.orderitementity (productid uuid, price decimal);
CREATE TABLE IF NOT EXISTS order_database.orderentity(
id uuid,
status text,
orderitementities list<frozen<orderitementity>>,
price decimal,
primary key(id)
);

View File

@ -3,6 +3,7 @@ version: '3'
services:
order-mongo-database:
image: mongo:3.4.13
container_name: order-mongo-db
restart: always
ports:
- 27017:27017
@ -11,4 +12,19 @@ services:
MONGO_INITDB_ROOT_PASSWORD: admin
MONGO_INITDB_DATABASE: order-database
volumes:
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
order-cassandra-database:
image: cassandra:3.11.5
container_name: order-cassandra-db
restart: always
ports:
- 9042:9042
order-cassandra-init:
image: cassandra:3.11.5
container_name: order-cassandra-db-init
depends_on:
- order-cassandra-database
volumes:
- ./cassandra-init.cql:/cassandra-init.cql:ro
command: bin/bash -c "echo Initializing cassandra schema... && sleep 30 && cqlsh -u cassandra -p cassandra -f cassandra-init.cql order-cassandra-db"

View File

@ -0,0 +1,12 @@
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=order-database
spring.data.mongodb.username=order
spring.data.mongodb.password=order
spring.data.cassandra.keyspaceName=order_database
spring.data.cassandra.username=cassandra
spring.data.cassandra.password=cassandra
spring.data.cassandra.contactPoints=127.0.0.1
spring.data.cassandra.port=9042

View File

@ -1 +1,5 @@
# Dropwizard
# Dropwizard
### Relevant Articles:
- [Introduction to Dropwizard](https://www.baeldung.com/java-dropwizard)

18
gradle-6/.gitignore vendored Normal file
View File

@ -0,0 +1,18 @@
# Gradle
.gradle
build
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties

View File

@ -0,0 +1,5 @@
subprojects {
repositories {
mavenCentral()
}
}

View File

@ -0,0 +1,37 @@
plugins {
base
}
description = """
Demonstrates Gradle Configuraiton Avoidance API. Creates a new configuration "extralibs" to
which we add dependencies. The custom task "copyExtraLibs" copies those dependencies to a new
build directory "extra-libs". This build uses the Task Configuraion Avoidance APIs which have
been marked stable in Gradle 6.0
""".trimIndent()
// extraLibs is a NamedDomainObjectProvider<Configuration!> - the Configuration object will not be
// realized until it is needed. In the meantime, the build may reference it by name
val extralibs by configurations.registering
dependencies {
// we can call extralibs.name without causing the extralibs to be realized
add(extralibs.name, "junit:junit:4.12")
}
// extraLibsDir is a Provider<Directory!> - the Directory object will not be realized until it is
// needed
val extraLibsDir = project.layout.buildDirectory.dir("extra-libs")
// copyExtraLibs is a TaskProvider<Copy!> - the task will not be realized until it is needed
val copyExtraLibs by tasks.registering(Copy::class) {
// the copy task's "from" and "into" APIs accept Provider types to support configuration
// avoidance
from(extralibs)
into(extraLibsDir)
}
// configures the "build" task only if it needs to be
tasks.build {
// dependsOn accepts a TaskProvider to avoid realizing the copyExtraLibs needlessly
dependsOn(copyExtraLibs)
}

View File

@ -0,0 +1,29 @@
plugins {
`java-library`
}
group = "com.baeldung"
version = "1.0.0"
dependencies {
api("io.reactivex.rxjava2:rxjava:2.2.16")
implementation("com.google.guava:guava") {
version {
require("10.0")
prefer("28.1-jre")
because("Only uses ImmutableList type, so any version since 2.0 will do, but tested with 28.1-jre")
}
}
testImplementation("org.junit.jupiter:junit-jupiter-api:5.5.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.5.2")
}
tasks.compileJava {
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
}
tasks.test {
useJUnitPlatform()
}

View File

@ -0,0 +1,24 @@
package com.baeldung.gradle;
import com.google.common.collect.ImmutableList;
import io.reactivex.Observable;
import java.util.List;
/**
* Demonstrates a library type that returns an RxJava type.
*/
public class RxHelloWorld {
/**
* @return an {@link Observable} that emits events "hello" and "world" before completing.
*/
public static Observable<String> hello() {
// Guava ImmutableList class is an implementation detail.
List<String> values = ImmutableList.of("hello", "world");
return Observable.fromIterable(values);
}
private RxHelloWorld() {
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.gradle;
import org.junit.jupiter.api.Test;
import static com.baeldung.gradle.RxHelloWorld.hello;
/**
* Unit test for {@link RxHelloWorld}.
*/
final class RxHelloWorldUnitTest {
@Test void it_emits_hello_world_values() {
hello().test().assertValues("hello", "world").assertComplete();
}
}

View File

@ -0,0 +1,17 @@
plugins {
`java-library`
}
dependencies {
api(project(":fibonacci-spi"))
compileOnly("com.google.auto.service:auto-service-annotations:1.0-rc6")
annotationProcessor("com.google.auto.service:auto-service:1.0-rc6")
testImplementation(testFixtures(project(":fibonacci-spi")))
testImplementation("org.junit.jupiter:junit-jupiter-api:5.5.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.5.2")
}
tasks.test {
useJUnitPlatform()
}

View File

@ -0,0 +1,20 @@
package com.baeldung.fibonacci.impl;
import com.baeldung.fibonacci.FibonacciSequenceGenerator;
import com.google.auto.service.AutoService;
/**
* Recursive implementation of the {@link FibonacciSequenceGenerator}.
*/
@AutoService(FibonacciSequenceGenerator.class) public final class RecursiveFibonacci implements FibonacciSequenceGenerator {
@Override public int generate(int nth) {
if (nth < 0) {
throw new IllegalArgumentException("sequence number must be 0 or greater");
}
if (nth <= 1) {
return nth;
}
return generate(nth - 1) + generate(nth - 2);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.fibonacci.impl;
import com.baeldung.fibonacci.FibonacciSequenceGenerator;
import com.baeldung.fibonacci.FibonacciSequenceGeneratorFixture;
/**
* Unit test which reuses the {@link FibonacciSequenceGeneratorFixture} test mix-in exported from the fibonacci-spi project.
*/
final class RecursiveFibonacciUnitTest implements FibonacciSequenceGeneratorFixture {
@Override public FibonacciSequenceGenerator provide() {
return new RecursiveFibonacci();
}
}

View File

@ -0,0 +1,13 @@
plugins {
`java-library`
`java-test-fixtures`
}
dependencies {
testFixturesApi("org.junit.jupiter:junit-jupiter-api:5.5.2")
testFixturesImplementation("org.junit.jupiter:junit-jupiter-engine:5.5.2")
}
tasks.test {
useJUnitPlatform()
}

View File

@ -0,0 +1,13 @@
package com.baeldung.fibonacci;
/**
* Describes an SPI for a Fibonacci sequence generator function.
*/
public interface FibonacciSequenceGenerator {
/**
* @param nth the index of the number in the fibonacci sequence
* @return the nth number in the fibonacci sequence
*/
int generate(int nth);
}

View File

@ -0,0 +1,30 @@
package com.baeldung.fibonacci;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Reusable test fixture for {@link FibonacciSequenceGenerator} implementations. Tests will be skipped if no such implementation exists.
*/
public interface FibonacciSequenceGeneratorFixture {
/**
* @return the implementation of {@link FibonacciSequenceGenerator} to test. Must not be null
*/
FibonacciSequenceGenerator provide();
@Test default void when_sequence_index_is_negative_then_throws() {
final FibonacciSequenceGenerator generator = provide();
assertThrows(IllegalArgumentException.class, () -> generator.generate(-1));
}
@Test default void when_given_index_then_generates_fibonacci_number() {
final FibonacciSequenceGenerator generator = provide();
final int[] sequence = { 0, 1, 1, 2, 3, 5, 8 };
for (int i = 0; i < sequence.length; i++) {
assertEquals(sequence[i], generator.generate(i));
}
}
}

View File

@ -0,0 +1,2 @@
org.gradle.parallel=true
org.gradle.configureondemand=true

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

183
gradle-6/gradlew vendored Executable file
View File

@ -0,0 +1,183 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

100
gradle-6/gradlew.bat vendored Normal file
View File

@ -0,0 +1,100 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,11 @@
plugins {
`java-platform`
}
dependencies {
constraints {
api("org.apache.httpcomponents:fluent-hc:4.5.10")
api("org.apache.httpcomponents:httpclient:4.5.10")
runtime("commons-logging:commons-logging:1.2")
}
}

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