Merge pull request #1220 from anuragagarwal561994/java-11

Java 11 (patterns with m)
This commit is contained in:
Ilkka Seppälä 2020-08-05 17:38:54 +03:00 committed by GitHub
commit 888af23219
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
74 changed files with 542 additions and 549 deletions

View File

@ -46,17 +46,18 @@ public class App {
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
final var logger = LoggerFactory.getLogger(App.class);
var guard = new Guard();
var thief = new Thief();
final Logger logger = LoggerFactory.getLogger(App.class); //noinspection ConstantConditions
Guard guard = new Guard();
Thief thief = new Thief();
if (guard instanceof Permission) { if (guard instanceof Permission) {
guard.enter(); guard.enter();
} else { } else {
logger.info("You have no permission to enter, please leave this area"); logger.info("You have no permission to enter, please leave this area");
} }
//noinspection ConstantConditions
if (thief instanceof Permission) { if (thief instanceof Permission) {
thief.steal(); thief.steal();
} else { } else {

View File

@ -28,11 +28,9 @@ import org.slf4j.LoggerFactory;
* Class defining Guard. * Class defining Guard.
*/ */
public class Guard implements Permission { public class Guard implements Permission {
private static final Logger LOGGER = LoggerFactory.getLogger(Guard.class); private static final Logger LOGGER = LoggerFactory.getLogger(Guard.class);
protected static void enter() { protected void enter() {
LOGGER.info("You can enter"); LOGGER.info("You can enter");
} }
} }

View File

@ -28,14 +28,13 @@ import org.slf4j.LoggerFactory;
* Class defining Thief. * Class defining Thief.
*/ */
public class Thief { public class Thief {
private static final Logger LOGGER = LoggerFactory.getLogger(Thief.class); private static final Logger LOGGER = LoggerFactory.getLogger(Thief.class);
protected static void steal() { protected void steal() {
LOGGER.info("Steal valuable items"); LOGGER.info("Steal valuable items");
} }
protected static void doNothing() { protected void doNothing() {
LOGGER.info("Pretend nothing happened and just leave"); LOGGER.info("Pretend nothing happened and just leave");
} }
} }

View File

@ -30,7 +30,6 @@ public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -33,7 +33,7 @@ public class GuardTest {
@Test @Test
public void testGuard() { public void testGuard() {
Guard guard = new Guard(); var guard = new Guard();
assertThat(guard, instanceOf(Permission.class)); assertThat(guard, instanceOf(Permission.class));
} }
} }

View File

@ -21,9 +21,11 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test;
/** /**
* Thief test * Thief test
@ -31,7 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
public class ThiefTest { public class ThiefTest {
@Test @Test
public void testThief() { public void testThief() {
Thief thief = new Thief(); var thief = new Thief();
assertFalse(thief instanceof Permission); assertThat(thief, not(instanceOf(Permission.class)));
} }
} }

View File

@ -22,38 +22,39 @@
THE SOFTWARE. THE SOFTWARE.
--> -->
<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"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<modelVersion>4.0.0</modelVersion> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId> <parent>
<artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId>
<version>1.23.0-SNAPSHOT</version> <artifactId>java-design-patterns</artifactId>
</parent> <version>1.23.0-SNAPSHOT</version>
<artifactId>master-worker-pattern</artifactId> </parent>
<dependencies> <artifactId>master-worker-pattern</artifactId>
<dependency> <dependencies>
<groupId>org.junit.jupiter</groupId> <dependency>
<artifactId>junit-jupiter-engine</artifactId> <groupId>org.junit.jupiter</groupId>
<scope>test</scope> <artifactId>junit-jupiter-engine</artifactId>
</dependency> <scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
<mainClass>com.iluwatar.masterworker.App</mainClass> <mainClass>com.iluwatar.masterworker.App</mainClass>
</manifest> </manifest>
</archive> </archive>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@ -34,27 +34,25 @@ import org.slf4j.LoggerFactory;
/** /**
* <p>The <b><em>Master-Worker</em></b> pattern is used when the problem at hand can be solved by * <p>The <b><em>Master-Worker</em></b> pattern is used when the problem at hand can be solved by
* dividing into * dividing into multiple parts which need to go through the same computation and may need to be
* multiple parts which need to go through the same computation and may need to be aggregated to get * aggregated to get final result. Parallel processing is performed using a system consisting of a
* final result. Parallel processing is performed using a system consisting of a master and some * master and some number of workers, where a master divides the work among the workers, gets the
* number of workers, where a master divides the work among the workers, gets the result back from * result back from them and assimilates all the results to give final result. The only
* them and assimilates all the results to give final result. The only communication is between the * communication is between the master and the worker - none of the workers communicate among one
* master and the worker - none of the workers communicate among one another and the user only * another and the user only communicates with the master to get required job done.</p>
* communicates with the master to get required job done.</p>
* <p>In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and * <p>In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and
* {@link Worker} which * {@link Worker} which have to be extended by the classes which will perform the specific job at
* have to be extended by the classes which will perform the specific job at hand (in this case * hand (in this case finding transpose of matrix, done by {@link ArrayTransposeMasterWorker},
* finding transpose of matrix, done by {@link ArrayTransposeMasterWorker}, {@link * {@link ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work
* ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work into * into parts to be given to the workers, collects the results from the workers and aggregates it
* parts to be given to the workers, collects the results from the workers and aggregates it when * when all workers have responded before returning the solution. The Worker class extends the
* all workers have responded before returning the solution. The Worker class extends the Thread * Thread class to enable parallel processing, and does the work once the data has been received
* class to enable parallel processing, and does the work once the data has been received from the * from the Master. The MasterWorker contains a reference to the Master class, gets the input from
* Master. The MasterWorker contains a reference to the Master class, gets the input from the App * the App and passes it on to the Master. These 3 classes define the system which computes the
* and passes it on to the Master. These 3 classes define the system which computes the result. We * result. We also have 2 abstract classes {@link Input} and {@link Result}, which contain the input
* also have 2 abstract classes {@link Input} and {@link Result}, which contain the input data and * data and result data respectively. The Input class also has an abstract method divideData which
* result data respectively. The Input class also has an abstract method divideData which defines * defines how the data is to be divided into segments. These classes are extended by {@link
* how the data is to be divided into segments. These classes are extended by {@link ArrayInput} and * ArrayInput} and {@link ArrayResult}.</p>
* {@link ArrayResult}.</p>
*/ */
public class App { public class App {
@ -68,12 +66,12 @@ public class App {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
ArrayTransposeMasterWorker mw = new ArrayTransposeMasterWorker(); var mw = new ArrayTransposeMasterWorker();
int rows = 10; var rows = 10;
int columns = 20; var columns = 20;
int[][] inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns); var inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns);
ArrayInput input = new ArrayInput(inputMatrix); var input = new ArrayInput(inputMatrix);
ArrayResult result = (ArrayResult) mw.getResult(input); var result = (ArrayResult) mw.getResult(input);
if (result != null) { if (result != null) {
ArrayUtilityMethods.printMatrix(inputMatrix); ArrayUtilityMethods.printMatrix(inputMatrix);
ArrayUtilityMethods.printMatrix(result.data); ArrayUtilityMethods.printMatrix(result.data);

View File

@ -25,6 +25,7 @@ package com.iluwatar.masterworker;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
/** /**
* Class ArrayInput extends abstract class {@link Input} and contains data of type int[][]. * Class ArrayInput extends abstract class {@link Input} and contains data of type int[][].
@ -37,12 +38,12 @@ public class ArrayInput extends Input<int[][]> {
} }
static int[] makeDivisions(int[][] data, int num) { static int[] makeDivisions(int[][] data, int num) {
int initialDivision = data.length / num; //equally dividing var initialDivision = data.length / num; //equally dividing
int[] divisions = new int[num]; var divisions = new int[num];
Arrays.fill(divisions, initialDivision); Arrays.fill(divisions, initialDivision);
if (initialDivision * num != data.length) { if (initialDivision * num != data.length) {
int extra = data.length - initialDivision * num; var extra = data.length - initialDivision * num;
int l = 0; var l = 0;
//equally dividing extra among all parts //equally dividing extra among all parts
while (extra > 0) { while (extra > 0) {
divisions[l] = divisions[l] + 1; divisions[l] = divisions[l] + 1;
@ -58,22 +59,20 @@ public class ArrayInput extends Input<int[][]> {
} }
@Override @Override
public ArrayList<Input> divideData(int num) { public List<Input<int[][]>> divideData(int num) {
if (this.data == null) { if (this.data == null) {
return null; return null;
} else { } else {
int[] divisions = makeDivisions(this.data, num); var divisions = makeDivisions(this.data, num);
ArrayList<Input> result = new ArrayList<Input>(num); var result = new ArrayList<Input<int[][]>>(num);
int rowsDone = 0; //number of rows divided so far var rowsDone = 0; //number of rows divided so far
for (int i = 0; i < num; i++) { for (var i = 0; i < num; i++) {
int rows = divisions[i]; var rows = divisions[i];
if (rows != 0) { if (rows != 0) {
int[][] divided = new int[rows][this.data[0].length]; var divided = new int[rows][this.data[0].length];
for (int j = 0; j < rows; j++) { System.arraycopy(this.data, rowsDone, divided, 0, rows);
divided[j] = this.data[rowsDone + j];
}
rowsDone += rows; rowsDone += rows;
ArrayInput dividedInput = new ArrayInput(divided); var dividedInput = new ArrayInput(divided);
result.add(dividedInput); result.add(dividedInput);
} else { } else {
break; //rest of divisions will also be 0 break; //rest of divisions will also be 0

View File

@ -47,8 +47,8 @@ public class ArrayUtilityMethods {
if (a1.length != a2.length) { if (a1.length != a2.length) {
return false; return false;
} else { } else {
boolean answer = false; var answer = false;
for (int i = 0; i < a1.length; i++) { for (var i = 0; i < a1.length; i++) {
if (a1[i] == a2[i]) { if (a1[i] == a2[i]) {
answer = true; answer = true;
} else { } else {
@ -69,8 +69,8 @@ public class ArrayUtilityMethods {
if (m1.length != m2.length) { if (m1.length != m2.length) {
return false; return false;
} else { } else {
boolean answer = false; var answer = false;
for (int i = 0; i < m1.length; i++) { for (var i = 0; i < m1.length; i++) {
if (arraysSame(m1[i], m2[i])) { if (arraysSame(m1[i], m2[i])) {
answer = true; answer = true;
} else { } else {
@ -88,9 +88,9 @@ public class ArrayUtilityMethods {
* @return it (int[][]). * @return it (int[][]).
*/ */
public static int[][] createRandomIntMatrix(int rows, int columns) { public static int[][] createRandomIntMatrix(int rows, int columns) {
int[][] matrix = new int[rows][columns]; var matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) { for (var i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) { for (var j = 0; j < columns; j++) {
//filling cells in matrix //filling cells in matrix
matrix[i][j] = RANDOM.nextInt(10); matrix[i][j] = RANDOM.nextInt(10);
} }
@ -104,9 +104,9 @@ public class ArrayUtilityMethods {
public static void printMatrix(int[][] matrix) { public static void printMatrix(int[][] matrix) {
//prints out int[][] //prints out int[][]
for (int i = 0; i < matrix.length; i++) { for (var ints : matrix) {
for (int j = 0; j < matrix[0].length; j++) { for (var j = 0; j < matrix[0].length; j++) {
LOGGER.info(matrix[i][j] + " "); LOGGER.info(ints[j] + " ");
} }
LOGGER.info(""); LOGGER.info("");
} }

View File

@ -23,7 +23,7 @@
package com.iluwatar.masterworker; package com.iluwatar.masterworker;
import java.util.ArrayList; import java.util.List;
/** /**
* The abstract Input class, having 1 public field which contains input data, and abstract method * The abstract Input class, having 1 public field which contains input data, and abstract method
@ -40,5 +40,5 @@ public abstract class Input<T> {
this.data = data; this.data = data;
} }
public abstract ArrayList<Input> divideData(int num); public abstract List<Input<T>> divideData(int num);
} }

View File

@ -40,7 +40,7 @@ public abstract class MasterWorker {
abstract Master setMaster(int numOfWorkers); abstract Master setMaster(int numOfWorkers);
public Result getResult(Input input) { public Result<?> getResult(Input<?> input) {
this.master.doWork(input); this.master.doWork(input);
return this.master.getFinalResult(); return this.master.getFinalResult();
} }

View File

@ -27,7 +27,8 @@ import com.iluwatar.masterworker.ArrayResult;
import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker; import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker;
import com.iluwatar.masterworker.system.systemworkers.Worker; import com.iluwatar.masterworker.system.systemworkers.Worker;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration; import java.util.stream.Collectors;
import java.util.stream.IntStream;
/** /**
* Class ArrayTransposeMaster extends abstract class {@link Master} and contains definition of * Class ArrayTransposeMaster extends abstract class {@link Master} and contains definition of
@ -41,35 +42,33 @@ public class ArrayTransposeMaster extends Master {
@Override @Override
ArrayList<Worker> setWorkers(int num) { ArrayList<Worker> setWorkers(int num) {
ArrayList<Worker> ws = new ArrayList<Worker>(num); //i+1 will be id
for (int i = 0; i < num; i++) { return IntStream.range(0, num)
ws.add(new ArrayTransposeWorker(this, i + 1)); .mapToObj(i -> new ArrayTransposeWorker(this, i + 1))
//i+1 will be id .collect(Collectors.toCollection(() -> new ArrayList<>(num)));
}
return ws;
} }
@Override @Override
ArrayResult aggregateData() { ArrayResult aggregateData() {
// number of rows in final result is number of rows in any of obtained results from workers // number of rows in final result is number of rows in any of obtained results from workers
int rows = ((ArrayResult) this.getAllResultData() var allResultData = this.getAllResultData();
.get(this.getAllResultData().keys().nextElement())).data.length; var rows = ((ArrayResult) allResultData.elements().nextElement()).data.length;
int columns = var elements = allResultData.elements();
0; //number of columns is sum of number of columns in all results obtained from workers var columns = 0; // columns = sum of number of columns in all results obtained from workers
for (Enumeration<Integer> e = this.getAllResultData().keys(); e.hasMoreElements(); ) { while (elements.hasMoreElements()) {
columns += ((ArrayResult) this.getAllResultData().get(e.nextElement())).data[0].length; columns += ((ArrayResult) elements.nextElement()).data[0].length;
} }
int[][] resultData = new int[rows][columns]; var resultData = new int[rows][columns];
int columnsDone = 0; //columns aggregated so far var columnsDone = 0; //columns aggregated so far
for (int i = 0; i < this.getExpectedNumResults(); i++) { var workers = this.getWorkers();
for (var i = 0; i < this.getExpectedNumResults(); i++) {
//result obtained from ith worker //result obtained from ith worker
int[][] work = var worker = workers.get(i);
((ArrayResult) this.getAllResultData().get(this.getWorkers().get(i).getWorkerId())).data; var workerId = worker.getWorkerId();
for (int m = 0; m < work.length; m++) { var work = ((ArrayResult) allResultData.get(workerId)).data;
for (var m = 0; m < work.length; m++) {
//m = row number, n = columns number //m = row number, n = columns number
for (int n = 0; n < work[0].length; n++) { System.arraycopy(work[m], 0, resultData[m], columnsDone, work[0].length);
resultData[m][columnsDone + n] = work[m][n];
}
} }
columnsDone += work[0].length; columnsDone += work[0].length;
} }

View File

@ -26,8 +26,8 @@ package com.iluwatar.masterworker.system.systemmaster;
import com.iluwatar.masterworker.Input; import com.iluwatar.masterworker.Input;
import com.iluwatar.masterworker.Result; import com.iluwatar.masterworker.Result;
import com.iluwatar.masterworker.system.systemworkers.Worker; import com.iluwatar.masterworker.system.systemworkers.Worker;
import java.util.ArrayList;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List;
/** /**
* The abstract Master class which contains private fields numOfWorkers (number of workers), workers * The abstract Master class which contains private fields numOfWorkers (number of workers), workers
@ -38,24 +38,24 @@ import java.util.Hashtable;
public abstract class Master { public abstract class Master {
private final int numOfWorkers; private final int numOfWorkers;
private final ArrayList<Worker> workers; private final List<Worker> workers;
private final Hashtable<Integer, Result<?>> allResultData;
private int expectedNumResults; private int expectedNumResults;
private final Hashtable<Integer, Result> allResultData; private Result<?> finalResult;
private Result finalResult;
Master(int numOfWorkers) { Master(int numOfWorkers) {
this.numOfWorkers = numOfWorkers; this.numOfWorkers = numOfWorkers;
this.workers = setWorkers(numOfWorkers); this.workers = setWorkers(numOfWorkers);
this.expectedNumResults = 0; this.expectedNumResults = 0;
this.allResultData = new Hashtable<Integer, Result>(numOfWorkers); this.allResultData = new Hashtable<>(numOfWorkers);
this.finalResult = null; this.finalResult = null;
} }
public Result getFinalResult() { public Result<?> getFinalResult() {
return this.finalResult; return this.finalResult;
} }
Hashtable<Integer, Result> getAllResultData() { Hashtable<Integer, Result<?>> getAllResultData() {
return this.allResultData; return this.allResultData;
} }
@ -63,34 +63,41 @@ public abstract class Master {
return this.expectedNumResults; return this.expectedNumResults;
} }
ArrayList<Worker> getWorkers() { List<Worker> getWorkers() {
return this.workers; return this.workers;
} }
abstract ArrayList<Worker> setWorkers(int num); abstract List<Worker> setWorkers(int num);
public void doWork(Input input) { public void doWork(Input<?> input) {
divideWork(input); divideWork(input);
} }
private void divideWork(Input input) { private void divideWork(Input<?> input) {
ArrayList<Input> dividedInput = input.divideData(numOfWorkers); var dividedInput = input.divideData(numOfWorkers);
if (dividedInput != null) { if (dividedInput != null) {
this.expectedNumResults = dividedInput.size(); this.expectedNumResults = dividedInput.size();
for (int i = 0; i < this.expectedNumResults; i++) { for (var i = 0; i < this.expectedNumResults; i++) {
//ith division given to ith worker in this.workers //ith division given to ith worker in this.workers
this.workers.get(i).setReceivedData(this, dividedInput.get(i)); this.workers.get(i).setReceivedData(this, dividedInput.get(i));
this.workers.get(i).run(); this.workers.get(i).start();
}
for (var i = 0; i < this.expectedNumResults; i++) {
try {
this.workers.get(i).join();
} catch (InterruptedException e) {
System.err.println("Error while executing thread");
}
} }
} }
} }
public void receiveData(Result data, Worker w) { public void receiveData(Result<?> data, Worker w) {
//check if can receive..if yes: //check if can receive..if yes:
collectResult(data, w.getWorkerId()); collectResult(data, w.getWorkerId());
} }
private void collectResult(Result data, int workerId) { private void collectResult(Result<?> data, int workerId) {
this.allResultData.put(workerId, data); this.allResultData.put(workerId, data);
if (this.allResultData.size() == this.expectedNumResults) { if (this.allResultData.size() == this.expectedNumResults) {
//all data received //all data received
@ -98,5 +105,5 @@ public abstract class Master {
} }
} }
abstract Result aggregateData(); abstract Result<?> aggregateData();
} }

View File

@ -41,12 +41,12 @@ public class ArrayTransposeWorker extends Worker {
@Override @Override
ArrayResult executeOperation() { ArrayResult executeOperation() {
//number of rows in result matrix is equal to number of columns in input matrix and vice versa //number of rows in result matrix is equal to number of columns in input matrix and vice versa
ArrayInput arrayInput = (ArrayInput) this.getReceivedData(); var arrayInput = (ArrayInput) this.getReceivedData();
final int rows = arrayInput.data[0].length; final var rows = arrayInput.data[0].length;
final int cols = arrayInput.data.length; final var cols = arrayInput.data.length;
int[][] resultData = new int[rows][cols]; var resultData = new int[rows][cols];
for (int i = 0; i < cols; i++) { for (var i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) { for (var j = 0; j < rows; j++) {
//flipping element positions along diagonal //flipping element positions along diagonal
resultData[j][i] = arrayInput.data[i][j]; resultData[j][i] = arrayInput.data[i][j];
} }

View File

@ -35,7 +35,7 @@ import com.iluwatar.masterworker.system.systemmaster.Master;
public abstract class Worker extends Thread { public abstract class Worker extends Thread {
private final Master master; private final Master master;
private final int workerId; private final int workerId;
private Input receivedData; private Input<?> receivedData;
Worker(Master master, int id) { Worker(Master master, int id) {
this.master = master; this.master = master;
@ -47,23 +47,23 @@ public abstract class Worker extends Thread {
return this.workerId; return this.workerId;
} }
Input getReceivedData() { Input<?> getReceivedData() {
return this.receivedData; return this.receivedData;
} }
public void setReceivedData(Master m, Input i) { public void setReceivedData(Master m, Input<?> i) {
//check if ready to receive..if yes: //check if ready to receive..if yes:
this.receivedData = i; this.receivedData = i;
} }
abstract Result executeOperation(); abstract Result<?> executeOperation();
private void sendToMaster(Result data) { private void sendToMaster(Result<?> data) {
this.master.receiveData(data, this); this.master.receiveData(data, this);
} }
public void run() { //from Thread class public void run() { //from Thread class
Result work = executeOperation(); var work = executeOperation();
sendToMaster(work); sendToMaster(work);
} }
} }

View File

@ -23,38 +23,39 @@
package com.iluwatar.masterworker; package com.iluwatar.masterworker;
import static org.junit.jupiter.api.Assertions.*; import static com.iluwatar.masterworker.ArrayUtilityMethods.matricesSame;
import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Random; import java.util.Random;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
* Testing divideData method in {@link ArrayInput} class. * Testing divideData method in {@link ArrayInput} class.
*/ */
class ArrayInputTest { class ArrayInputTest {
@Test @Test
void divideDataTest() { void divideDataTest() {
int rows = 10; var rows = 10;
int columns = 10; var columns = 10;
int[][] inputMatrix = new int[rows][columns]; var inputMatrix = new int[rows][columns];
Random rand = new Random(); var rand = new Random();
for (int i = 0; i < rows; i++) { for (var i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) { for (var j = 0; j < columns; j++) {
inputMatrix[i][j] = rand.nextInt(10); inputMatrix[i][j] = rand.nextInt(10);
} }
} }
ArrayInput i = new ArrayInput(inputMatrix); var i = new ArrayInput(inputMatrix);
ArrayList<Input> table = i.divideData(4); var table = i.divideData(4);
int[][] division1 = new int[][] {inputMatrix[0], inputMatrix[1], inputMatrix[2]}; var division1 = new int[][]{inputMatrix[0], inputMatrix[1], inputMatrix[2]};
int[][] division2 = new int[][] {inputMatrix[3], inputMatrix[4], inputMatrix[5]}; var division2 = new int[][]{inputMatrix[3], inputMatrix[4], inputMatrix[5]};
int[][] division3 = new int[][] {inputMatrix[6], inputMatrix[7]}; var division3 = new int[][]{inputMatrix[6], inputMatrix[7]};
int[][] division4 = new int[][] {inputMatrix[8], inputMatrix[9]}; var division4 = new int[][]{inputMatrix[8], inputMatrix[9]};
assertTrue(ArrayUtilityMethods.matricesSame((int[][]) table.get(0).data, division1) assertTrue(matricesSame(table.get(0).data, division1)
&& ArrayUtilityMethods.matricesSame((int[][]) table.get(1).data, division2) && matricesSame(table.get(1).data, division2)
&& ArrayUtilityMethods.matricesSame((int[][]) table.get(2).data, division3) && matricesSame(table.get(2).data, division3)
&& ArrayUtilityMethods.matricesSame((int[][]) table.get(3).data, division4)); && matricesSame(table.get(3).data, division4));
} }
} }

View File

@ -23,27 +23,27 @@
package com.iluwatar.masterworker; package com.iluwatar.masterworker;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
* Testing utility methods in {@link ArrayUtilityMethods} class. * Testing utility methods in {@link ArrayUtilityMethods} class.
*/ */
class ArrayUtilityMethodsTest { class ArrayUtilityMethodsTest {
@Test @Test
void arraysSameTest() { void arraysSameTest() {
int[] arr1 = new int[] {1,4,2,6}; var arr1 = new int[]{1, 4, 2, 6};
int[] arr2 = new int[] {1,4,2,6}; var arr2 = new int[]{1, 4, 2, 6};
assertTrue(ArrayUtilityMethods.arraysSame(arr1, arr2)); assertTrue(ArrayUtilityMethods.arraysSame(arr1, arr2));
} }
@Test @Test
void matricesSameTest() { void matricesSameTest() {
int[][] matrix1 = new int[][] {{1,4,2,6},{5,8,6,7}}; var matrix1 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}};
int[][] matrix2 = new int[][] {{1,4,2,6},{5,8,6,7}}; var matrix2 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}};
assertTrue(ArrayUtilityMethods.matricesSame(matrix1, matrix2)); assertTrue(ArrayUtilityMethods.matricesSame(matrix1, matrix2));
} }

View File

@ -23,25 +23,38 @@
package com.iluwatar.masterworker.system; package com.iluwatar.masterworker.system;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.iluwatar.masterworker.ArrayUtilityMethods;
import com.iluwatar.masterworker.ArrayInput; import com.iluwatar.masterworker.ArrayInput;
import com.iluwatar.masterworker.ArrayResult; import com.iluwatar.masterworker.ArrayResult;
import com.iluwatar.masterworker.ArrayUtilityMethods;
import org.junit.jupiter.api.Test;
/** /**
* Testing getResult method in {@link ArrayTransposeMasterWorker} class. * Testing getResult method in {@link ArrayTransposeMasterWorker} class.
*/ */
class ArrayTransposeMasterWorkerTest { class ArrayTransposeMasterWorkerTest {
@Test @Test
void getResultTest() { void getResultTest() {
ArrayTransposeMasterWorker atmw = new ArrayTransposeMasterWorker(); var atmw = new ArrayTransposeMasterWorker();
int[][] matrix = new int[][] {{1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}}; var matrix = new int[][]{
int[][] matrixTranspose = new int[][] {{1,1,1,1,1}, {2,2,2,2,2}, {3,3,3,3,3}, {4,4,4,4,4}, {5,5,5,5,5}}; {1, 2, 3, 4, 5},
ArrayInput i = new ArrayInput(matrix); {1, 2, 3, 4, 5},
ArrayResult r = (ArrayResult) atmw.getResult(i); {1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5}
};
var matrixTranspose = new int[][]{
{1, 1, 1, 1, 1},
{2, 2, 2, 2, 2},
{3, 3, 3, 3, 3},
{4, 4, 4, 4, 4},
{5, 5, 5, 5, 5}
};
var i = new ArrayInput(matrix);
var r = (ArrayResult) atmw.getResult(i);
assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose)); assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose));
} }
} }

View File

@ -23,29 +23,29 @@
package com.iluwatar.masterworker.system.systemworkers; package com.iluwatar.masterworker.system.systemworkers;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.iluwatar.masterworker.ArrayUtilityMethods;
import com.iluwatar.masterworker.ArrayInput; import com.iluwatar.masterworker.ArrayInput;
import com.iluwatar.masterworker.ArrayResult; import com.iluwatar.masterworker.ArrayUtilityMethods;
import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster; import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster;
import org.junit.jupiter.api.Test;
/** /**
* Testing executeOperation method in {@link ArrayTransposeWorker} class. * Testing executeOperation method in {@link ArrayTransposeWorker} class.
*/ */
class ArrayTransposeWorkerTest { class ArrayTransposeWorkerTest {
@Test @Test
void executeOperationTest() { void executeOperationTest() {
ArrayTransposeMaster atm = new ArrayTransposeMaster(1); var atm = new ArrayTransposeMaster(1);
ArrayTransposeWorker atw = new ArrayTransposeWorker(atm, 1); var atw = new ArrayTransposeWorker(atm, 1);
int[][] matrix = new int[][] {{2,4}, {3,5}}; var matrix = new int[][]{{2, 4}, {3, 5}};
int[][] matrixTranspose = new int[][] {{2,3}, {4,5}}; var matrixTranspose = new int[][]{{2, 3}, {4, 5}};
ArrayInput i = new ArrayInput(matrix); var i = new ArrayInput(matrix);
atw.setReceivedData(atm, i); atw.setReceivedData(atm, i);
ArrayResult r = atw.executeOperation(); var r = atw.executeOperation();
assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose)); assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose));
} }
} }

View File

@ -27,7 +27,6 @@ package com.iluwatar.mediator;
* Action enumeration. * Action enumeration.
*/ */
public enum Action { public enum Action {
HUNT("hunted a rabbit", "arrives for dinner"), HUNT("hunted a rabbit", "arrives for dinner"),
TALE("tells a tale", "comes to listen"), TALE("tells a tale", "comes to listen"),
GOLD("found gold", "takes his share of the gold"), GOLD("found gold", "takes his share of the gold"),

View File

@ -55,10 +55,10 @@ public class App {
// create party and members // create party and members
Party party = new PartyImpl(); Party party = new PartyImpl();
Hobbit hobbit = new Hobbit(); var hobbit = new Hobbit();
Wizard wizard = new Wizard(); var wizard = new Wizard();
Rogue rogue = new Rogue(); var rogue = new Rogue();
Hunter hunter = new Hunter(); var hunter = new Hunter();
// add party members // add party members
party.addMember(hobbit); party.addMember(hobbit);

View File

@ -39,7 +39,7 @@ public class PartyImpl implements Party {
@Override @Override
public void act(PartyMember actor, Action action) { public void act(PartyMember actor, Action action) {
for (PartyMember member : members) { for (var member : members) {
if (!member.equals(actor)) { if (!member.equals(actor)) {
member.partyAction(action); member.partyAction(action);
} }

View File

@ -26,15 +26,12 @@ package com.iluwatar.mediator;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -43,10 +43,10 @@ public class PartyImplTest {
*/ */
@Test @Test
public void testPartyAction() { public void testPartyAction() {
final PartyMember partyMember1 = mock(PartyMember.class); final var partyMember1 = mock(PartyMember.class);
final PartyMember partyMember2 = mock(PartyMember.class); final var partyMember2 = mock(PartyMember.class);
final PartyImpl party = new PartyImpl(); final var party = new PartyImpl();
party.addMember(partyMember1); party.addMember(partyMember1);
party.addMember(partyMember2); party.addMember(partyMember2);
@ -58,7 +58,6 @@ public class PartyImplTest {
verify(partyMember2).partyAction(Action.GOLD); verify(partyMember2).partyAction(Action.GOLD);
verifyNoMoreInteractions(partyMember1, partyMember2); verifyNoMoreInteractions(partyMember1, partyMember2);
} }
} }

View File

@ -23,24 +23,24 @@
package com.iluwatar.mediator; package com.iluwatar.mediator;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.LoggerFactory;
/** /**
* Date: 12/19/15 - 10:13 PM * Date: 12/19/15 - 10:13 PM
* *
@ -48,12 +48,12 @@ import static org.mockito.Mockito.verify;
*/ */
public class PartyMemberTest { public class PartyMemberTest {
static Collection<Supplier<PartyMember>[]> dataProvider() { static Stream<Arguments> dataProvider() {
return List.of( return Stream.of(
new Supplier[]{Hobbit::new}, Arguments.of((Supplier<PartyMember>) Hobbit::new),
new Supplier[]{Hunter::new}, Arguments.of((Supplier<PartyMember>) Hunter::new),
new Supplier[]{Rogue::new}, Arguments.of((Supplier<PartyMember>) Rogue::new),
new Supplier[]{Wizard::new} Arguments.of((Supplier<PartyMember>) Wizard::new)
); );
} }
@ -75,9 +75,9 @@ public class PartyMemberTest {
@ParameterizedTest @ParameterizedTest
@MethodSource("dataProvider") @MethodSource("dataProvider")
public void testPartyAction(Supplier<PartyMember> memberSupplier) { public void testPartyAction(Supplier<PartyMember> memberSupplier) {
final PartyMember member = memberSupplier.get(); final var member = memberSupplier.get();
for (final Action action : Action.values()) { for (final var action : Action.values()) {
member.partyAction(action); member.partyAction(action);
assertEquals(member.toString() + " " + action.getDescription(), appender.getLastMessage()); assertEquals(member.toString() + " " + action.getDescription(), appender.getLastMessage());
} }
@ -91,16 +91,16 @@ public class PartyMemberTest {
@ParameterizedTest @ParameterizedTest
@MethodSource("dataProvider") @MethodSource("dataProvider")
public void testAct(Supplier<PartyMember> memberSupplier) { public void testAct(Supplier<PartyMember> memberSupplier) {
final PartyMember member = memberSupplier.get(); final var member = memberSupplier.get();
member.act(Action.GOLD); member.act(Action.GOLD);
assertEquals(0, appender.getLogSize()); assertEquals(0, appender.getLogSize());
final Party party = mock(Party.class); final var party = mock(Party.class);
member.joinedParty(party); member.joinedParty(party);
assertEquals(member.toString() + " joins the party", appender.getLastMessage()); assertEquals(member.toString() + " joins the party", appender.getLastMessage());
for (final Action action : Action.values()) { for (final var action : Action.values()) {
member.act(action); member.act(action);
assertEquals(member.toString() + " " + action.toString(), appender.getLastMessage()); assertEquals(member.toString() + " " + action.toString(), appender.getLastMessage());
verify(party).act(member, action); verify(party).act(member, action);
@ -114,16 +114,16 @@ public class PartyMemberTest {
*/ */
@ParameterizedTest @ParameterizedTest
@MethodSource("dataProvider") @MethodSource("dataProvider")
public void testToString(Supplier<PartyMember> memberSupplier) throws Exception { public void testToString(Supplier<PartyMember> memberSupplier) {
final PartyMember member = memberSupplier.get(); final var member = memberSupplier.get();
final Class<? extends PartyMember> memberClass = member.getClass(); final var memberClass = member.getClass();
assertEquals(memberClass.getSimpleName(), member.toString()); assertEquals(memberClass.getSimpleName(), member.toString());
} }
private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private static class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private final List<ILoggingEvent> log = new LinkedList<>(); private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) { public InMemoryAppender(Class<?> clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start(); start();
} }

View File

@ -34,9 +34,12 @@ Let's first define the types of stars we are capable to handle.
```java ```java
public enum StarType { public enum StarType {
SUN("sun"),
SUN("sun"), RED_GIANT("red giant"), WHITE_DWARF("white dwarf"), SUPERNOVA("supernova"), DEAD( RED_GIANT("red giant"),
"dead star"), UNDEFINED(""); WHITE_DWARF("white dwarf"),
SUPERNOVA("supernova"),
DEAD("dead star"),
UNDEFINED("");
private final String title; private final String title;
@ -95,8 +98,7 @@ public class Star {
} }
StarMemento getMemento() { StarMemento getMemento() {
var state = new StarMementoInternal();
StarMementoInternal state = new StarMementoInternal();
state.setAgeYears(ageYears); state.setAgeYears(ageYears);
state.setMassTons(massTons); state.setMassTons(massTons);
state.setType(type); state.setType(type);
@ -104,8 +106,7 @@ public class Star {
} }
void setMemento(StarMemento memento) { void setMemento(StarMemento memento) {
var state = (StarMementoInternal) memento;
StarMementoInternal state = (StarMementoInternal) memento;
this.type = state.getType(); this.type = state.getType();
this.ageYears = state.getAgeYears(); this.ageYears = state.getAgeYears();
this.massTons = state.getMassTons(); this.massTons = state.getMassTons();
@ -152,8 +153,8 @@ public class Star {
And finally here's how we use the mementos to store and restore star states. And finally here's how we use the mementos to store and restore star states.
```java ```java
Stack<StarMemento> states = new Stack<>(); var states = new Stack<>();
Star star = new Star(StarType.SUN, 10000000, 500000); var star = new Star(StarType.SUN, 10000000, 500000);
LOGGER.info(star.toString()); LOGGER.info(star.toString());
states.add(star.getMemento()); states.add(star.getMemento());
star.timePasses(); star.timePasses();

View File

@ -52,9 +52,9 @@ public class App {
* Program entry point. * Program entry point.
*/ */
public static void main(String[] args) { public static void main(String[] args) {
Stack<StarMemento> states = new Stack<>(); var states = new Stack<StarMemento>();
Star star = new Star(StarType.SUN, 10000000, 500000); var star = new Star(StarType.SUN, 10000000, 500000);
LOGGER.info(star.toString()); LOGGER.info(star.toString());
states.add(star.getMemento()); states.add(star.getMemento());
star.timePasses(); star.timePasses();

View File

@ -70,22 +70,18 @@ public class Star {
} }
StarMemento getMemento() { StarMemento getMemento() {
var state = new StarMementoInternal();
StarMementoInternal state = new StarMementoInternal();
state.setAgeYears(ageYears); state.setAgeYears(ageYears);
state.setMassTons(massTons); state.setMassTons(massTons);
state.setType(type); state.setType(type);
return state; return state;
} }
void setMemento(StarMemento memento) { void setMemento(StarMemento memento) {
var state = (StarMementoInternal) memento;
StarMementoInternal state = (StarMementoInternal) memento;
this.type = state.getType(); this.type = state.getType();
this.ageYears = state.getAgeYears(); this.ageYears = state.getAgeYears();
this.massTons = state.getMassTons(); this.massTons = state.getMassTons();
} }
@Override @Override

View File

@ -27,9 +27,12 @@ package com.iluwatar.memento;
* StarType enumeration. * StarType enumeration.
*/ */
public enum StarType { public enum StarType {
SUN("sun"),
SUN("sun"), RED_GIANT("red giant"), WHITE_DWARF("white dwarf"), SUPERNOVA("supernova"), DEAD( RED_GIANT("red giant"),
"dead star"), UNDEFINED(""); WHITE_DWARF("white dwarf"),
SUPERNOVA("supernova"),
DEAD("dead star"),
UNDEFINED("");
private final String title; private final String title;

View File

@ -26,15 +26,12 @@ package com.iluwatar.memento;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,10 +23,10 @@
package com.iluwatar.memento; package com.iluwatar.memento;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/20/15 - 10:08 AM * Date: 12/20/15 - 10:08 AM
* *
@ -39,7 +39,7 @@ public class StarTest {
*/ */
@Test @Test
public void testTimePasses() { public void testTimePasses() {
final Star star = new Star(StarType.SUN, 1, 2); final var star = new Star(StarType.SUN, 1, 2);
assertEquals("sun age: 1 years mass: 2 tons", star.toString()); assertEquals("sun age: 1 years mass: 2 tons", star.toString());
star.timePasses(); star.timePasses();
@ -66,16 +66,16 @@ public class StarTest {
*/ */
@Test @Test
public void testSetMemento() { public void testSetMemento() {
final Star star = new Star(StarType.SUN, 1, 2); final var star = new Star(StarType.SUN, 1, 2);
final StarMemento firstMemento = star.getMemento(); final var firstMemento = star.getMemento();
assertEquals("sun age: 1 years mass: 2 tons", star.toString()); assertEquals("sun age: 1 years mass: 2 tons", star.toString());
star.timePasses(); star.timePasses();
final StarMemento secondMemento = star.getMemento(); final var secondMemento = star.getMemento();
assertEquals("red giant age: 2 years mass: 16 tons", star.toString()); assertEquals("red giant age: 2 years mass: 16 tons", star.toString());
star.timePasses(); star.timePasses();
final StarMemento thirdMemento = star.getMemento(); final var thirdMemento = star.getMemento();
assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString()); assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString());
star.timePasses(); star.timePasses();

View File

@ -47,9 +47,9 @@ public class App {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// create model, view and controller // create model, view and controller
GiantModel giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); var giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
GiantView view = new GiantView(); var view = new GiantView();
GiantController controller = new GiantController(giant, view); var controller = new GiantController(giant, view);
// initial display // initial display
controller.updateView(); controller.updateView();
// controller receives some interactions that affect the giant // controller receives some interactions that affect the giant

View File

@ -27,8 +27,9 @@ package com.iluwatar.model.view.controller;
* Fatigue enumeration. * Fatigue enumeration.
*/ */
public enum Fatigue { public enum Fatigue {
ALERT("alert"),
ALERT("alert"), TIRED("tired"), SLEEPING("sleeping"); TIRED("tired"),
SLEEPING("sleeping");
private final String title; private final String title;

View File

@ -36,6 +36,7 @@ public class GiantController {
this.view = view; this.view = view;
} }
@SuppressWarnings("UnusedReturnValue")
public Health getHealth() { public Health getHealth() {
return giant.getHealth(); return giant.getHealth();
} }
@ -44,6 +45,7 @@ public class GiantController {
this.giant.setHealth(health); this.giant.setHealth(health);
} }
@SuppressWarnings("UnusedReturnValue")
public Fatigue getFatigue() { public Fatigue getFatigue() {
return giant.getFatigue(); return giant.getFatigue();
} }
@ -52,6 +54,7 @@ public class GiantController {
this.giant.setFatigue(fatigue); this.giant.setFatigue(fatigue);
} }
@SuppressWarnings("UnusedReturnValue")
public Nourishment getNourishment() { public Nourishment getNourishment() {
return giant.getNourishment(); return giant.getNourishment();
} }

View File

@ -27,8 +27,9 @@ package com.iluwatar.model.view.controller;
* Health enumeration. * Health enumeration.
*/ */
public enum Health { public enum Health {
HEALTHY("healthy"),
HEALTHY("healthy"), WOUNDED("wounded"), DEAD("dead"); WOUNDED("wounded"),
DEAD("dead");
private final String title; private final String title;

View File

@ -27,8 +27,9 @@ package com.iluwatar.model.view.controller;
* Nourishment enumeration. * Nourishment enumeration.
*/ */
public enum Nourishment { public enum Nourishment {
SATURATED("saturated"),
SATURATED("saturated"), HUNGRY("hungry"), STARVING("starving"); HUNGRY("hungry"),
STARVING("starving");
private final String title; private final String title;

View File

@ -26,15 +26,12 @@ package com.iluwatar.model.view.controller;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,13 +23,13 @@
package com.iluwatar.model.view.controller; package com.iluwatar.model.view.controller;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/20/15 - 2:19 PM * Date: 12/20/15 - 2:19 PM
* *
@ -42,19 +42,20 @@ public class GiantControllerTest {
*/ */
@Test @Test
public void testSetHealth() { public void testSetHealth() {
final GiantModel model = mock(GiantModel.class); final var model = mock(GiantModel.class);
final GiantView view = mock(GiantView.class); final var view = mock(GiantView.class);
final GiantController controller = new GiantController(model, view); final var controller = new GiantController(model, view);
verifyZeroInteractions(model, view); verifyZeroInteractions(model, view);
for (final Health health : Health.values()) { for (final var health : Health.values()) {
controller.setHealth(health); controller.setHealth(health);
verify(model).setHealth(health); verify(model).setHealth(health);
verifyZeroInteractions(view); verifyZeroInteractions(view);
} }
controller.getHealth(); controller.getHealth();
//noinspection ResultOfMethodCallIgnored
verify(model).getHealth(); verify(model).getHealth();
verifyNoMoreInteractions(model, view); verifyNoMoreInteractions(model, view);
@ -65,19 +66,20 @@ public class GiantControllerTest {
*/ */
@Test @Test
public void testSetFatigue() { public void testSetFatigue() {
final GiantModel model = mock(GiantModel.class); final var model = mock(GiantModel.class);
final GiantView view = mock(GiantView.class); final var view = mock(GiantView.class);
final GiantController controller = new GiantController(model, view); final var controller = new GiantController(model, view);
verifyZeroInteractions(model, view); verifyZeroInteractions(model, view);
for (final Fatigue fatigue : Fatigue.values()) { for (final var fatigue : Fatigue.values()) {
controller.setFatigue(fatigue); controller.setFatigue(fatigue);
verify(model).setFatigue(fatigue); verify(model).setFatigue(fatigue);
verifyZeroInteractions(view); verifyZeroInteractions(view);
} }
controller.getFatigue(); controller.getFatigue();
//noinspection ResultOfMethodCallIgnored
verify(model).getFatigue(); verify(model).getFatigue();
verifyNoMoreInteractions(model, view); verifyNoMoreInteractions(model, view);
@ -88,19 +90,20 @@ public class GiantControllerTest {
*/ */
@Test @Test
public void testSetNourishment() { public void testSetNourishment() {
final GiantModel model = mock(GiantModel.class); final var model = mock(GiantModel.class);
final GiantView view = mock(GiantView.class); final var view = mock(GiantView.class);
final GiantController controller = new GiantController(model, view); final var controller = new GiantController(model, view);
verifyZeroInteractions(model, view); verifyZeroInteractions(model, view);
for (final Nourishment nourishment : Nourishment.values()) { for (final var nourishment : Nourishment.values()) {
controller.setNourishment(nourishment); controller.setNourishment(nourishment);
verify(model).setNourishment(nourishment); verify(model).setNourishment(nourishment);
verifyZeroInteractions(view); verifyZeroInteractions(view);
} }
controller.getNourishment(); controller.getNourishment();
//noinspection ResultOfMethodCallIgnored
verify(model).getNourishment(); verify(model).getNourishment();
verifyNoMoreInteractions(model, view); verifyNoMoreInteractions(model, view);
@ -108,9 +111,9 @@ public class GiantControllerTest {
@Test @Test
public void testUpdateView() { public void testUpdateView() {
final GiantModel model = mock(GiantModel.class); final var model = mock(GiantModel.class);
final GiantView view = mock(GiantView.class); final var view = mock(GiantView.class);
final GiantController controller = new GiantController(model, view); final var controller = new GiantController(model, view);
verifyZeroInteractions(model, view); verifyZeroInteractions(model, view);

View File

@ -23,10 +23,10 @@
package com.iluwatar.model.view.controller; package com.iluwatar.model.view.controller;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/20/15 - 2:10 PM * Date: 12/20/15 - 2:10 PM
* *
@ -39,12 +39,13 @@ public class GiantModelTest {
*/ */
@Test @Test
public void testSetHealth() { public void testSetHealth() {
final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
assertEquals(Health.HEALTHY, model.getHealth()); assertEquals(Health.HEALTHY, model.getHealth());
for (final Health health : Health.values()) { var messageFormat = "The giant looks %s, alert and saturated.";
for (final var health : Health.values()) {
model.setHealth(health); model.setHealth(health);
assertEquals(health, model.getHealth()); assertEquals(health, model.getHealth());
assertEquals("The giant looks " + health.toString() + ", alert and saturated.", model.toString()); assertEquals(String.format(messageFormat, health), model.toString());
} }
} }
@ -53,12 +54,13 @@ public class GiantModelTest {
*/ */
@Test @Test
public void testSetFatigue() { public void testSetFatigue() {
final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
assertEquals(Fatigue.ALERT, model.getFatigue()); assertEquals(Fatigue.ALERT, model.getFatigue());
for (final Fatigue fatigue : Fatigue.values()) { var messageFormat = "The giant looks healthy, %s and saturated.";
for (final var fatigue : Fatigue.values()) {
model.setFatigue(fatigue); model.setFatigue(fatigue);
assertEquals(fatigue, model.getFatigue()); assertEquals(fatigue, model.getFatigue());
assertEquals("The giant looks healthy, " + fatigue.toString() + " and saturated.", model.toString()); assertEquals(String.format(messageFormat, fatigue), model.toString());
} }
} }
@ -67,12 +69,13 @@ public class GiantModelTest {
*/ */
@Test @Test
public void testSetNourishment() { public void testSetNourishment() {
final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
assertEquals(Nourishment.SATURATED, model.getNourishment()); assertEquals(Nourishment.SATURATED, model.getNourishment());
for (final Nourishment nourishment : Nourishment.values()) { var messageFormat = "The giant looks healthy, alert and %s.";
for (final var nourishment : Nourishment.values()) {
model.setNourishment(nourishment); model.setNourishment(nourishment);
assertEquals(nourishment, model.getNourishment()); assertEquals(nourishment, model.getNourishment());
assertEquals("The giant looks healthy, alert and " + nourishment.toString() + ".", model.toString()); assertEquals(String.format(messageFormat, nourishment), model.toString());
} }
} }

View File

@ -31,7 +31,6 @@ import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase; import ch.qos.logback.core.AppenderBase;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -62,9 +61,9 @@ public class GiantViewTest {
*/ */
@Test @Test
public void testDisplayGiant() { public void testDisplayGiant() {
final GiantView view = new GiantView(); final var view = new GiantView();
final GiantModel model = mock(GiantModel.class); final var model = mock(GiantModel.class);
view.displayGiant(model); view.displayGiant(model);
assertEquals(model.toString(), appender.getLastMessage()); assertEquals(model.toString(), appender.getLastMessage());
@ -74,10 +73,10 @@ public class GiantViewTest {
/** /**
* Logging Appender Implementation * Logging Appender Implementation
*/ */
public class InMemoryAppender extends AppenderBase<ILoggingEvent> { public static class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private final List<ILoggingEvent> log = new LinkedList<>(); private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) { public InMemoryAppender(Class<?> clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start(); start();
} }

View File

@ -44,9 +44,9 @@ public class App {
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
FileLoader loader = new FileLoader(); var loader = new FileLoader();
FileSelectorJFrame frame = new FileSelectorJFrame(); var frame = new FileSelectorJFrame();
FileSelectorPresenter presenter = new FileSelectorPresenter(frame); var presenter = new FileSelectorPresenter(frame);
presenter.setLoader(loader); presenter.setLoader(loader);
presenter.start(); presenter.start();
} }

View File

@ -27,6 +27,7 @@ import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.Serializable; import java.io.Serializable;
import java.util.stream.Collectors;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -59,18 +60,11 @@ public class FileLoader implements Serializable {
* Loads the data of the file specified. * Loads the data of the file specified.
*/ */
public String loadData() { public String loadData() {
String dataFileName = this.fileName; var dataFileName = this.fileName;
try (BufferedReader br = new BufferedReader(new FileReader(new File(dataFileName)))) { try (var br = new BufferedReader(new FileReader(new File(dataFileName)))) {
StringBuilder sb = new StringBuilder(); var result = br.lines().collect(Collectors.joining("\n"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append('\n');
}
this.loaded = true; this.loaded = true;
return result;
return sb.toString();
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("File {} does not exist", dataFileName); LOGGER.error("File {} does not exist", dataFileName);
} }

View File

@ -55,16 +55,6 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
*/ */
private final JButton cancel; private final JButton cancel;
/**
* The information label.
*/
private final JLabel info;
/**
* The contents label.
*/
private final JLabel contents;
/** /**
* The text field for giving the name of the file that we want to open. * The text field for giving the name of the file that we want to open.
*/ */
@ -75,11 +65,6 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
*/ */
private final JTextArea area; private final JTextArea area;
/**
* The panel that will hold our widgets.
*/
private final JPanel panel;
/** /**
* The Presenter component that the frame will interact with. * The Presenter component that the frame will interact with.
*/ */
@ -102,7 +87,7 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
/* /*
* Add the panel. * Add the panel.
*/ */
this.panel = new JPanel(); var panel = new JPanel();
panel.setLayout(null); panel.setLayout(null);
this.add(panel); this.add(panel);
panel.setBounds(0, 0, 500, 200); panel.setBounds(0, 0, 500, 200);
@ -111,32 +96,32 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
/* /*
* Add the info label. * Add the info label.
*/ */
this.info = new JLabel("File Name :"); var info = new JLabel("File Name :");
this.panel.add(info); panel.add(info);
info.setBounds(30, 10, 100, 30); info.setBounds(30, 10, 100, 30);
/* /*
* Add the contents label. * Add the contents label.
*/ */
this.contents = new JLabel("File contents :"); var contents = new JLabel("File contents :");
this.panel.add(contents); panel.add(contents);
this.contents.setBounds(30, 100, 120, 30); contents.setBounds(30, 100, 120, 30);
/* /*
* Add the text field. * Add the text field.
*/ */
this.input = new JTextField(100); this.input = new JTextField(100);
this.panel.add(input); panel.add(input);
this.input.setBounds(150, 15, 200, 20); this.input.setBounds(150, 15, 200, 20);
/* /*
* Add the text area. * Add the text area.
*/ */
this.area = new JTextArea(100, 100); this.area = new JTextArea(100, 100);
JScrollPane pane = new JScrollPane(area); var pane = new JScrollPane(area);
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.panel.add(pane); panel.add(pane);
this.area.setEditable(false); this.area.setEditable(false);
pane.setBounds(150, 100, 250, 80); pane.setBounds(150, 100, 250, 80);
@ -144,7 +129,7 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
* Add the OK button. * Add the OK button.
*/ */
this.ok = new JButton("OK"); this.ok = new JButton("OK");
this.panel.add(ok); panel.add(ok);
this.ok.setBounds(250, 50, 100, 25); this.ok.setBounds(250, 50, 100, 25);
this.ok.addActionListener(this); this.ok.addActionListener(this);
@ -152,7 +137,7 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
* Add the cancel button. * Add the cancel button.
*/ */
this.cancel = new JButton("Cancel"); this.cancel = new JButton("Cancel");
this.panel.add(this.cancel); panel.add(this.cancel);
this.cancel.setBounds(380, 50, 100, 25); this.cancel.setBounds(380, 50, 100, 25);
this.cancel.addActionListener(this); this.cancel.addActionListener(this);

View File

@ -91,7 +91,7 @@ public class FileSelectorPresenter implements Serializable {
} }
if (loader.fileExists()) { if (loader.fileExists()) {
String data = loader.loadData(); var data = loader.loadData();
view.displayData(data); view.displayData(data);
} else { } else {
view.showMessage("The file specified does not exist."); view.showMessage("The file specified does not exist.");

View File

@ -26,16 +26,13 @@ package com.iluwatar.model.view.presenter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,10 +23,10 @@
package com.iluwatar.model.view.presenter; package com.iluwatar.model.view.presenter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/21/15 - 12:12 PM * Date: 12/21/15 - 12:12 PM
* *
@ -35,8 +35,8 @@ import static org.junit.jupiter.api.Assertions.assertNull;
public class FileLoaderTest { public class FileLoaderTest {
@Test @Test
public void testLoadData() throws Exception { public void testLoadData() {
final FileLoader fileLoader = new FileLoader(); final var fileLoader = new FileLoader();
fileLoader.setFileName("non-existing-file"); fileLoader.setFileName("non-existing-file");
assertNull(fileLoader.loadData()); assertNull(fileLoader.loadData());
} }

View File

@ -23,14 +23,14 @@
package com.iluwatar.model.view.presenter; package com.iluwatar.model.view.presenter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** /**
* This test case is responsible for testing our application by taking advantage of the * This test case is responsible for testing our application by taking advantage of the
* Model-View-Controller architectural pattern. * Model-View-Controller architectural pattern.
@ -79,7 +79,7 @@ public class FileSelectorPresenterTest {
*/ */
@Test @Test
public void updateFileNameToLoader() { public void updateFileNameToLoader() {
String expectedFile = "Stamatis"; var expectedFile = "Stamatis";
stub.setFileName(expectedFile); stub.setFileName(expectedFile);
presenter.start(); presenter.start();

View File

@ -23,38 +23,39 @@
THE SOFTWARE. THE SOFTWARE.
--> -->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <project 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> xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId> <parent>
<artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId>
<version>1.23.0-SNAPSHOT</version> <artifactId>java-design-patterns</artifactId>
</parent> <version>1.23.0-SNAPSHOT</version>
<artifactId>module</artifactId> </parent>
<dependencies> <artifactId>module</artifactId>
<dependency> <dependencies>
<groupId>org.junit.jupiter</groupId> <dependency>
<artifactId>junit-jupiter-engine</artifactId> <groupId>org.junit.jupiter</groupId>
<scope>test</scope> <artifactId>junit-jupiter-engine</artifactId>
</dependency> <scope>test</scope>
</dependencies> </dependency>
<build> </dependencies>
<plugins> <build>
<plugin> <plugins>
<groupId>org.apache.maven.plugins</groupId> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<executions> <artifactId>maven-assembly-plugin</artifactId>
<execution> <executions>
<configuration> <execution>
<archive> <configuration>
<manifest> <archive>
<mainClass>com.iluwatar.module.App</mainClass> <manifest>
</manifest> <mainClass>com.iluwatar.module.App</mainClass>
</archive> </manifest>
</configuration> </archive>
</execution> </configuration>
</executions> </execution>
</plugin> </executions>
</plugins> </plugin>
</build> </plugins>
</build>
</project> </project>

View File

@ -67,10 +67,8 @@ public class App {
/** /**
* Following method is main executor. * Following method is main executor.
*
* @param args for providing default program arguments
*/ */
public static void execute(final String... args) { public static void execute() {
/* Send logs on file system */ /* Send logs on file system */
fileLoggerModule.printString(MESSAGE); fileLoggerModule.printString(MESSAGE);
@ -90,7 +88,7 @@ public class App {
*/ */
public static void main(final String... args) throws FileNotFoundException { public static void main(final String... args) throws FileNotFoundException {
prepare(); prepare();
execute(args); execute();
unprepare(); unprepare();
} }
} }

View File

@ -23,9 +23,8 @@
package com.iluwatar.module; package com.iluwatar.module;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import org.junit.jupiter.api.Test;
/** /**
* Tests that Module example runs without errors. * Tests that Module example runs without errors.
@ -34,7 +33,6 @@ public final class AppTest {
@Test @Test
public void test() throws FileNotFoundException { public void test() throws FileNotFoundException {
final String[] args = {}; App.main();
App.main(args);
} }
} }

View File

@ -23,17 +23,16 @@
package com.iluwatar.module; package com.iluwatar.module;
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.slf4j.Logger; import static org.junit.jupiter.api.Assertions.assertNull;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import org.slf4j.Logger;
import static org.junit.jupiter.api.Assertions.assertNull; import org.slf4j.LoggerFactory;
/** /**
* The Module pattern can be considered a Creational pattern and a Structural pattern. It manages * The Module pattern can be considered a Creational pattern and a Structural pattern. It manages
@ -58,7 +57,7 @@ public final class FileLoggerModuleTest {
/** /**
* This test verify that 'MESSAGE' is perfectly printed in output file * This test verify that 'MESSAGE' is perfectly printed in output file
* *
* @throws IOException if program is not able to find log files (output.txt and error.txt) * @throws IOException if program is not able to find log files (output.txt and error.txt)
*/ */
@Test @Test
@ -82,13 +81,13 @@ public final class FileLoggerModuleTest {
/** /**
* This test verify that nothing is printed in output file * This test verify that nothing is printed in output file
* *
* @throws IOException if program is not able to find log files (output.txt and error.txt) * @throws IOException if program is not able to find log files (output.txt and error.txt)
*/ */
@Test @Test
public void testNoFileMessage() throws IOException { public void testNoFileMessage() throws IOException {
/* Get singletong instance of File Logger Module */ /* Get singleton instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton(); final var fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */ /* Prepare the essential sub modules, to perform the sequence of jobs */
@ -103,9 +102,9 @@ public final class FileLoggerModuleTest {
/** /**
* This test verify that 'ERROR' is perfectly printed in error file * This test verify that 'ERROR' is perfectly printed in error file
* *
* @throws FileNotFoundException if program is not able to find log files (output.txt and * @throws FileNotFoundException if program is not able to find log files (output.txt and
* error.txt) * error.txt)
*/ */
@Test @Test
public void testFileErrorMessage() throws FileNotFoundException { public void testFileErrorMessage() throws FileNotFoundException {
@ -122,15 +121,15 @@ public final class FileLoggerModuleTest {
/* Test if 'Message' is printed in file */ /* Test if 'Message' is printed in file */
assertEquals(ERROR, readFirstLine(ERROR_FILE)); assertEquals(ERROR, readFirstLine(ERROR_FILE));
/* Unprepare to cleanup the modules */ /* Un-prepare to cleanup the modules */
fileLoggerModule.unprepare(); fileLoggerModule.unprepare();
} }
/** /**
* This test verify that nothing is printed in error file * This test verify that nothing is printed in error file
* *
* @throws FileNotFoundException if program is not able to find log files (output.txt and * @throws FileNotFoundException if program is not able to find log files (output.txt and
* error.txt) * error.txt)
*/ */
@Test @Test
public void testNoFileErrorMessage() throws FileNotFoundException { public void testNoFileErrorMessage() throws FileNotFoundException {
@ -150,11 +149,11 @@ public final class FileLoggerModuleTest {
/** /**
* Utility method to read first line of a file * Utility method to read first line of a file
* *
* @param file as file name to be read * @param file as file name to be read
* @return a string value as first line in file * @return a string value as first line in file
*/ */
private static final String readFirstLine(final String file) { private static String readFirstLine(final String file) {
String firstLine = null; String firstLine = null;
try (var bufferedReader = new BufferedReader(new FileReader(file))) { try (var bufferedReader = new BufferedReader(new FileReader(file))) {

View File

@ -41,9 +41,8 @@ import org.slf4j.LoggerFactory;
* instance of a plain object with {@link Validator#of(Object)} and validates it {@link * instance of a plain object with {@link Validator#of(Object)} and validates it {@link
* Validator#validate(Function, Predicate, String)} against given predicates. * Validator#validate(Function, Predicate, String)} against given predicates.
* *
* <p>As a validation result {@link Validator#get()} it either returns valid object {@link * <p>As a validation result {@link Validator#get()} either returns valid object
* Validator#t} or throws a list of exceptions {@link Validator#exceptions} collected during * or throws {@link IllegalStateException} with list of exceptions collected during validation.
* validation.
*/ */
public class App { public class App {
@ -55,10 +54,10 @@ public class App {
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
User user = new User("user", 24, Sex.FEMALE, "foobar.com"); var user = new User("user", 24, Sex.FEMALE, "foobar.com");
LOGGER.info(Validator.of(user).validate(User::getName, Objects::nonNull, "name is null") LOGGER.info(Validator.of(user).validate(User::getName, Objects::nonNull, "name is null")
.validate(User::getName, name -> !name.isEmpty(), "name is empty") .validate(User::getName, name -> !name.isEmpty(), "name is empty")
.validate(User::getEmail, email -> !email.contains("@"), "email doesn't containt '@'") .validate(User::getEmail, email -> !email.contains("@"), "email doesn't contains '@'")
.validate(User::getAge, age -> age > 20 && age < 30, "age isn't between...").get() .validate(User::getAge, age -> age > 20 && age < 30, "age isn't between...").get()
.toString()); .toString());
} }

View File

@ -85,18 +85,21 @@ public class Validator<T> {
} }
/** /**
* Extension for the {@link Validator#validate(Function, Predicate, String)} method, dedicated for * Extension for the {@link Validator#validate(Predicate, String)} method, dedicated for objects,
* objects, that need to be projected before requested validation. * that need to be projected before requested validation.
* *
* @param projection function that gets an objects, and returns projection representing element to * @param projection function that gets an objects, and returns projection representing element to
* be validated. * be validated.
* @param validation see {@link Validator#validate(Function, Predicate, String)} * @param validation see {@link Validator#validate(Predicate, String)}
* @param message see {@link Validator#validate(Function, Predicate, String)} * @param message see {@link Validator#validate(Predicate, String)}
* @param <U> see {@link Validator#validate(Function, Predicate, String)} * @param <U> see {@link Validator#validate(Predicate, String)}
* @return this * @return this
*/ */
public <U> Validator<T> validate(Function<T, U> projection, Predicate<U> validation, public <U> Validator<T> validate(
String message) { Function<T, U> projection,
Predicate<U> validation,
String message
) {
return validate(projection.andThen(validation::test)::apply, message); return validate(projection.andThen(validation::test)::apply, message);
} }
@ -110,7 +113,7 @@ public class Validator<T> {
if (exceptions.isEmpty()) { if (exceptions.isEmpty()) {
return obj; return obj;
} }
IllegalStateException e = new IllegalStateException(); var e = new IllegalStateException();
exceptions.forEach(e::addSuppressed); exceptions.forEach(e::addSuppressed);
throw e; throw e;
} }

View File

@ -32,8 +32,7 @@ public class AppTest {
@Test @Test
public void testMain() { public void testMain() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,13 +23,12 @@
package com.iluwatar.monad; package com.iluwatar.monad;
import org.junit.jupiter.api.Test;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Objects;
import org.junit.jupiter.api.Test;
/** /**
* Test for Monad Pattern * Test for Monad Pattern
*/ */
@ -37,27 +36,33 @@ public class MonadTest {
@Test @Test
public void testForInvalidName() { public void testForInvalidName() {
User tom = new User(null, 21, Sex.MALE, "tom@foo.bar"); var tom = new User(null, 21, Sex.MALE, "tom@foo.bar");
assertThrows(IllegalStateException.class, () -> { assertThrows(
Validator.of(tom).validate(User::getName, Objects::nonNull, "name cannot be null").get(); IllegalStateException.class,
}); () -> Validator.of(tom)
.validate(User::getName, Objects::nonNull, "name cannot be null")
.get()
);
} }
@Test @Test
public void testForInvalidAge() { public void testForInvalidAge() {
User john = new User("John", 17, Sex.MALE, "john@qwe.bar"); var john = new User("John", 17, Sex.MALE, "john@qwe.bar");
assertThrows(IllegalStateException.class, () -> { assertThrows(
Validator.of(john).validate(User::getName, Objects::nonNull, "name cannot be null") IllegalStateException.class,
.validate(User::getAge, age -> age > 21, "user is underaged") () -> Validator.of(john)
.get(); .validate(User::getName, Objects::nonNull, "name cannot be null")
}); .validate(User::getAge, age -> age > 21, "user is underage")
.get()
);
} }
@Test @Test
public void testForValid() { public void testForValid() {
User sarah = new User("Sarah", 42, Sex.FEMALE, "sarah@det.org"); var sarah = new User("Sarah", 42, Sex.FEMALE, "sarah@det.org");
User validated = Validator.of(sarah).validate(User::getName, Objects::nonNull, "name cannot be null") var validated = Validator.of(sarah)
.validate(User::getAge, age -> age > 21, "user is underaged") .validate(User::getName, Objects::nonNull, "name cannot be null")
.validate(User::getAge, age -> age > 21, "user is underage")
.validate(User::getSex, sex -> sex == Sex.FEMALE, "user is not female") .validate(User::getSex, sex -> sex == Sex.FEMALE, "user is not female")
.validate(User::getEmail, email -> email.contains("@"), "email does not contain @ sign") .validate(User::getEmail, email -> email.contains("@"), "email does not contain @ sign")
.get(); .get();

View File

@ -30,7 +30,7 @@ package com.iluwatar.monostate;
* *
* <p>In the following example, The {@link LoadBalancer} class represents the app's logic. It * <p>In the following example, The {@link LoadBalancer} class represents the app's logic. It
* contains a series of Servers, which can handle requests of type {@link Request}. Two instances of * contains a series of Servers, which can handle requests of type {@link Request}. Two instances of
* LoadBalacer are created. When a request is made to a server via the first LoadBalancer the state * LoadBalancer are created. When a request is made to a server via the first LoadBalancer the state
* change in the first load balancer affects the second. So if the first LoadBalancer selects the * change in the first load balancer affects the second. So if the first LoadBalancer selects the
* Server 1, the second LoadBalancer on a new request will select the Second server. If a third * Server 1, the second LoadBalancer on a new request will select the Second server. If a third
* LoadBalancer is created and a new request is made to it, then it will select the third server as * LoadBalancer is created and a new request is made to it, then it will select the third server as
@ -43,8 +43,8 @@ public class App {
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
LoadBalancer loadBalancer1 = new LoadBalancer(); var loadBalancer1 = new LoadBalancer();
LoadBalancer loadBalancer2 = new LoadBalancer(); var loadBalancer2 = new LoadBalancer();
loadBalancer1.serverRequest(new Request("Hello")); loadBalancer1.serverRequest(new Request("Hello"));
loadBalancer2.serverRequest(new Request("Hello World")); loadBalancer2.serverRequest(new Request("Hello World"));
} }

View File

@ -38,8 +38,8 @@ public class LoadBalancer {
private static int lastServedId; private static int lastServedId;
static { static {
int id = 0; var id = 0;
for (int port : new int[]{8080, 8081, 8082, 8083, 8084}) { for (var port : new int[]{8080, 8081, 8082, 8083, 8084}) {
SERVERS.add(new Server("localhost", port, ++id)); SERVERS.add(new Server("localhost", port, ++id));
} }
} }
@ -69,7 +69,7 @@ public class LoadBalancer {
if (lastServedId >= SERVERS.size()) { if (lastServedId >= SERVERS.size()) {
lastServedId = 0; lastServedId = 0;
} }
Server server = SERVERS.get(lastServedId++); var server = SERVERS.get(lastServedId++);
server.serve(request); server.serve(request);
} }

View File

@ -32,8 +32,7 @@ public class AppTest {
@Test @Test
public void testMain() { public void testMain() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -44,8 +44,8 @@ public class LoadBalancerTest {
@Test @Test
public void testSameStateAmongstAllInstances() { public void testSameStateAmongstAllInstances() {
final LoadBalancer firstBalancer = new LoadBalancer(); final var firstBalancer = new LoadBalancer();
final LoadBalancer secondBalancer = new LoadBalancer(); final var secondBalancer = new LoadBalancer();
firstBalancer.addServer(new Server("localhost", 8085, 6)); firstBalancer.addServer(new Server("localhost", 8085, 6));
// Both should have the same number of servers. // Both should have the same number of servers.
assertEquals(firstBalancer.getNoOfServers(), secondBalancer.getNoOfServers()); assertEquals(firstBalancer.getNoOfServers(), secondBalancer.getNoOfServers());
@ -55,18 +55,18 @@ public class LoadBalancerTest {
@Test @Test
public void testServe() { public void testServe() {
final Server server = mock(Server.class); final var server = mock(Server.class);
when(server.getHost()).thenReturn("testhost"); when(server.getHost()).thenReturn("testhost");
when(server.getPort()).thenReturn(1234); when(server.getPort()).thenReturn(1234);
doNothing().when(server).serve(any(Request.class)); doNothing().when(server).serve(any(Request.class));
final LoadBalancer loadBalancer = new LoadBalancer(); final var loadBalancer = new LoadBalancer();
loadBalancer.addServer(server); loadBalancer.addServer(server);
verifyZeroInteractions(server); verifyZeroInteractions(server);
final Request request = new Request("test"); final var request = new Request("test");
for (int i = 0; i < loadBalancer.getNoOfServers() * 2; i++) { for (var i = 0; i < loadBalancer.getNoOfServers() * 2; i++) {
loadBalancer.serverRequest(request); loadBalancer.serverRequest(request);
} }

View File

@ -27,7 +27,13 @@ package com.iluwatar.multiton;
* enum based multiton implementation. * enum based multiton implementation.
*/ */
public enum NazgulEnum { public enum NazgulEnum {
KHAMUL,
KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA MURAZOR,
DWAR,
JI_INDUR,
AKHORAHIL,
HOARMURATH,
ADUNAPHEL,
REN,
UVATHA
} }

View File

@ -27,7 +27,13 @@ package com.iluwatar.multiton;
* Each Nazgul has different {@link NazgulName}. * Each Nazgul has different {@link NazgulName}.
*/ */
public enum NazgulName { public enum NazgulName {
KHAMUL,
KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA MURAZOR,
DWAR,
JI_INDUR,
AKHORAHIL,
HOARMURATH,
ADUNAPHEL,
REN,
UVATHA
} }

View File

@ -26,15 +26,12 @@ package com.iluwatar.multiton;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -39,10 +39,10 @@ class NazgulEnumTest {
*/ */
@Test @Test
public void testTheSameObjectIsReturnedWithMultipleCalls() { public void testTheSameObjectIsReturnedWithMultipleCalls() {
for (int i = 0; i < NazgulEnum.values().length; i++) { for (var i = 0; i < NazgulEnum.values().length; i++) {
NazgulEnum instance1 = NazgulEnum.values()[i]; var instance1 = NazgulEnum.values()[i];
NazgulEnum instance2 = NazgulEnum.values()[i]; var instance2 = NazgulEnum.values()[i];
NazgulEnum instance3 = NazgulEnum.values()[i]; var instance3 = NazgulEnum.values()[i];
assertSame(instance1, instance2); assertSame(instance1, instance2);
assertSame(instance1, instance3); assertSame(instance1, instance3);
assertSame(instance2, instance3); assertSame(instance2, instance3);

View File

@ -41,8 +41,8 @@ public class NazgulTest {
*/ */
@Test @Test
public void testGetInstance() { public void testGetInstance() {
for (final NazgulName name : NazgulName.values()) { for (final var name : NazgulName.values()) {
final Nazgul nazgul = Nazgul.getInstance(name); final var nazgul = Nazgul.getInstance(name);
assertNotNull(nazgul); assertNotNull(nazgul);
assertSame(nazgul, Nazgul.getInstance(name)); assertSame(nazgul, Nazgul.getInstance(name));
assertEquals(name, nazgul.getName()); assertEquals(name, nazgul.getName());

View File

@ -25,7 +25,7 @@ package com.iluwatar.mute;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.sql.SQLException; import java.util.Optional;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -52,9 +52,8 @@ public class App {
* Program entry point. * Program entry point.
* *
* @param args command line args. * @param args command line args.
* @throws Exception if any exception occurs
*/ */
public static void main(String[] args) throws Exception { public static void main(String[] args) {
useOfLoggedMute(); useOfLoggedMute();
@ -68,17 +67,17 @@ public class App {
* exception occurs. * exception occurs.
*/ */
private static void useOfMute() { private static void useOfMute() {
ByteArrayOutputStream out = new ByteArrayOutputStream(); var out = new ByteArrayOutputStream();
Mute.mute(() -> out.write("Hello".getBytes())); Mute.mute(() -> out.write("Hello".getBytes()));
} }
private static void useOfLoggedMute() throws SQLException { private static void useOfLoggedMute() {
Resource resource = null; Optional<Resource> resource = Optional.empty();
try { try {
resource = acquireResource(); resource = Optional.of(acquireResource());
utilizeResource(resource); utilizeResource(resource.get());
} finally { } finally {
closeResource(resource); resource.ifPresent(App::closeResource);
} }
} }
@ -86,14 +85,14 @@ public class App {
* All we can do while failed close of a resource is to log it. * All we can do while failed close of a resource is to log it.
*/ */
private static void closeResource(Resource resource) { private static void closeResource(Resource resource) {
Mute.loggedMute(() -> resource.close()); Mute.loggedMute(resource::close);
} }
private static void utilizeResource(Resource resource) throws SQLException { private static void utilizeResource(Resource resource) {
LOGGER.info("Utilizing acquired resource: {}", resource); LOGGER.info("Utilizing acquired resource: {}", resource);
} }
private static Resource acquireResource() throws SQLException { private static Resource acquireResource() {
return new Resource() { return new Resource() {
@Override @Override

View File

@ -27,12 +27,11 @@ import org.junit.jupiter.api.Test;
/** /**
* Tests that Mute idiom example runs without errors. * Tests that Mute idiom example runs without errors.
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() throws Exception { public void test() {
App.main(null); App.main(new String[]{});
} }
} }

View File

@ -23,17 +23,15 @@
package com.iluwatar.mute; package com.iluwatar.mute;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Test for the mute-idiom pattern * Test for the mute-idiom pattern
*/ */
@ -50,9 +48,7 @@ public class MuteTest {
@Test @Test
public void muteShouldRethrowUnexpectedExceptionAsAssertionError() { public void muteShouldRethrowUnexpectedExceptionAsAssertionError() {
assertThrows(AssertionError.class, () -> { assertThrows(AssertionError.class, () -> Mute.mute(this::methodThrowingException));
Mute.mute(this::methodThrowingException);
});
} }
@Test @Test
@ -62,7 +58,7 @@ public class MuteTest {
@Test @Test
public void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() { public void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() {
ByteArrayOutputStream stream = new ByteArrayOutputStream(); var stream = new ByteArrayOutputStream();
System.setErr(new PrintStream(stream)); System.setErr(new PrintStream(stream));
Mute.loggedMute(this::methodThrowingException); Mute.loggedMute(this::methodThrowingException);

View File

@ -38,10 +38,10 @@ public class App {
* main method. * main method.
*/ */
public static void main(String[] args) { public static void main(String[] args) {
Mutex mutex = new Mutex(); var mutex = new Mutex();
Jar jar = new Jar(1000, mutex); var jar = new Jar(1000, mutex);
Thief peter = new Thief("Peter", jar); var peter = new Thief("Peter", jar);
Thief john = new Thief("John", jar); var john = new Thief("John", jar);
peter.start(); peter.start();
john.start(); john.start();
} }

View File

@ -48,7 +48,7 @@ public class Jar {
* Method for a thief to take a bean. * Method for a thief to take a bean.
*/ */
public boolean takeBean() { public boolean takeBean() {
boolean success = false; var success = false;
try { try {
lock.acquire(); lock.acquire();
success = beans > 0; success = beans > 0;

View File

@ -54,7 +54,7 @@ public class Thief extends Thread {
*/ */
@Override @Override
public void run() { public void run() {
int beans = 0; var beans = 0;
while (jar.takeBean()) { while (jar.takeBean()) {
beans = beans + 1; beans = beans + 1;

View File

@ -25,15 +25,12 @@ package com.iluwatar.mutex;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
/** /**
* Application Test Entrypoint * Application Test Entrypoint
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() throws IOException { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,10 +23,11 @@
package com.iluwatar.mutex; package com.iluwatar.mutex;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/** /**
* Test case for taking beans from a Jar * Test case for taking beans from a Jar
@ -35,12 +36,10 @@ public class JarTest {
@Test @Test
public void testTakeBeans() { public void testTakeBeans() {
Mutex mutex = new Mutex(); var mutex = new Mutex();
Jar jar = new Jar(10, mutex); var jar = new Jar(10, mutex);
for (int i = 0; i < 10; i++) { IntStream.range(0, 10).mapToObj(i -> jar.takeBean()).forEach(Assertions::assertTrue);
assertTrue(jar.takeBean());
}
assertFalse(jar.takeBean()); assertFalse(jar.takeBean());
} }
} }

View File

@ -23,12 +23,12 @@
package com.iluwatar.mutex; package com.iluwatar.mutex;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
/** /**
* Test case for acquiring and releasing a Mutex * Test case for acquiring and releasing a Mutex
*/ */
@ -36,7 +36,7 @@ public class MutexTest {
@Test @Test
public void acquireReleaseTest() { public void acquireReleaseTest() {
Mutex mutex = new Mutex(); var mutex = new Mutex();
assertNull(mutex.getOwner()); assertNull(mutex.getOwner());
try { try {
mutex.acquire(); mutex.acquire();