From dda09535e657ef6b4e2fde8f0c72e1f93b1429ac Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 22:31:32 +0530 Subject: [PATCH] Resolves checkstyle errors for guarded-suspension, half-sync-half-async, hexagonal (#1064) * Reduces checkstyle errors in guarded-suspension * Reduces checkstyle errors in half-sync-half-async * Reduces checkstyle errors in hexagonal --- .../com/iluwatar/guarded/suspension/App.java | 25 +++-- .../guarded/suspension/GuardedQueue.java | 16 ++- .../com/iluwatar/halfsynchalfasync/App.java | 64 +++++------ .../iluwatar/halfsynchalfasync/AsyncTask.java | 4 +- .../AsynchronousService.java | 20 ++-- .../main/java/com/iluwatar/hexagonal/App.java | 57 +++++----- .../administration/ConsoleAdministration.java | 10 +- .../ConsoleAdministrationSrv.java | 8 +- .../ConsoleAdministrationSrvImpl.java | 7 +- .../hexagonal/banking/InMemoryBank.java | 22 ++-- .../iluwatar/hexagonal/banking/MongoBank.java | 30 ++--- .../hexagonal/banking/WireTransfers.java | 10 +- .../database/InMemoryTicketRepository.java | 9 +- .../database/LotteryTicketRepository.java | 17 ++- .../database/MongoTicketRepository.java | 22 ++-- .../domain/LotteryAdministration.java | 22 ++-- .../hexagonal/domain/LotteryConstants.java | 6 +- .../hexagonal/domain/LotteryNumbers.java | 32 +++--- .../hexagonal/domain/LotteryService.java | 16 +-- .../hexagonal/domain/LotteryTicket.java | 12 +- .../domain/LotteryTicketCheckResult.java | 14 ++- .../hexagonal/domain/LotteryTicketId.java | 6 +- .../hexagonal/domain/LotteryUtils.java | 19 ++-- .../hexagonal/domain/PlayerDetails.java | 12 +- .../hexagonal/eventlog/LotteryEventLog.java | 14 +-- .../hexagonal/eventlog/MongoEventLog.java | 29 +++-- .../hexagonal/eventlog/StdOutEventLog.java | 17 +-- .../hexagonal/module/LotteryModule.java | 2 +- .../module/LotteryTestingModule.java | 2 +- .../MongoConnectionPropertiesLoader.java | 5 +- .../hexagonal/sampledata/SampleData.java | 83 +++++++------- .../hexagonal/service/ConsoleLottery.java | 9 +- .../service/LotteryConsoleService.java | 15 ++- .../service/LotteryConsoleServiceImpl.java | 105 ++++++++++-------- 34 files changed, 382 insertions(+), 359 deletions(-) diff --git a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java index 922e36602..7c9bc1429 100644 --- a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java +++ b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java @@ -21,15 +21,6 @@ * THE SOFTWARE. */ -/** - * Guarded-suspension is a concurrent design pattern for handling situation when to execute some action we need - * condition to be satisfied. - *

- * Implementation is based on GuardedQueue, which has two methods: get and put, - * the condition is that we cannot get from empty queue so when thread attempt - * to break the condition we invoke Object's wait method on him and when other thread put an element - * to the queue he notify the waiting one that now he can get from queue. - */ package com.iluwatar.guarded.suspension; import java.util.concurrent.ExecutorService; @@ -38,10 +29,18 @@ import java.util.concurrent.TimeUnit; /** * Created by robertt240 on 1/26/17. + * + *

Guarded-suspension is a concurrent design pattern for handling situation when to execute some + * action we need condition to be satisfied. + * + *

Implementation is based on GuardedQueue, which has two methods: get and put, the condition is + * that we cannot get from empty queue so when thread attempt to break the condition we invoke + * Object's wait method on him and when other thread put an element to the queue he notify the + * waiting one that now he can get from queue. */ public class App { /** - * Example pattern execution + * Example pattern execution. * * @param args - command line args */ @@ -55,13 +54,15 @@ public class App { } ); - //here we wait two seconds to show that the thread which is trying to get from guardedQueue will be waiting + // here we wait two seconds to show that the thread which is trying + // to get from guardedQueue will be waiting try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } - //now we execute second thread which will put number to guardedQueue and notify first thread that it could get + // now we execute second thread which will put number to guardedQueue + // and notify first thread that it could get executorService.execute(() -> { guardedQueue.put(20); } diff --git a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java index e516a8699..0102c5253 100644 --- a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java +++ b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java @@ -23,16 +23,16 @@ package com.iluwatar.guarded.suspension; +import java.util.LinkedList; +import java.util.Queue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.Queue; - /** - * Guarded Queue is an implementation for Guarded Suspension Pattern - * Guarded suspension pattern is used to handle a situation when you want to execute a method - * on an object which is not in a proper state. + * Guarded Queue is an implementation for Guarded Suspension Pattern Guarded suspension pattern is + * used to handle a situation when you want to execute a method on an object which is not in a + * proper state. + * * @see http://java-design-patterns.com/patterns/guarded-suspension/ */ public class GuardedQueue { @@ -44,6 +44,8 @@ public class GuardedQueue { } /** + * Get the last element of the queue is exists. + * * @return last element of a queue if queue is not empty */ public synchronized Integer get() { @@ -60,6 +62,8 @@ public class GuardedQueue { } /** + * Put a value in the queue. + * * @param e number which we want to put to our queue */ public synchronized void put(Integer e) { diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java index 6287cf9bf..c559fca59 100644 --- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java +++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java @@ -23,42 +23,35 @@ package com.iluwatar.halfsynchalfasync; +import java.util.concurrent.LinkedBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.LinkedBlockingQueue; - /** - * - * This application demonstrates Half-Sync/Half-Async pattern. Key parts of the pattern are - * {@link AsyncTask} and {@link AsynchronousService}. - * - *

- * PROBLEM
+ * This application demonstrates Half-Sync/Half-Async pattern. Key parts of the pattern are {@link + * AsyncTask} and {@link AsynchronousService}. + * + *

PROBLEM
* A concurrent system have a mixture of short duration, mid duration and long duration tasks. Mid * or long duration tasks should be performed asynchronously to meet quality of service * requirements. - * - *

- * INTENT
+ * + *

INTENT
* The intent of this pattern is to separate the the synchronous and asynchronous processing in the * concurrent application by introducing two intercommunicating layers - one for sync and one for * async. This simplifies the programming without unduly affecting the performance. - * - *

- * APPLICABILITY
- * UNIX network subsystems - In operating systems network operations are carried out - * asynchronously with help of hardware level interrupts.
- * CORBA - At the asynchronous layer one thread is associated with each socket that is connected - * to the client. Thread blocks waiting for CORBA requests from the client. On receiving request it - * is inserted in the queuing layer which is then picked up by synchronous layer which processes the - * request and sends response back to the client.
- * Android AsyncTask framework - Framework provides a way to execute long running blocking - * calls, such as downloading a file, in background threads so that the UI thread remains free to - * respond to user inputs.
- * - *

- * IMPLEMENTATION
+ * + *

APPLICABILITY
+ * UNIX network subsystems - In operating systems network operations are carried out asynchronously + * with help of hardware level interrupts.
CORBA - At the asynchronous layer one thread is + * associated with each socket that is connected to the client. Thread blocks waiting for CORBA + * requests from the client. On receiving request it is inserted in the queuing layer which is then + * picked up by synchronous layer which processes the request and sends response back to the + * client.
Android AsyncTask framework - Framework provides a way to execute long running + * blocking calls, such as downloading a file, in background threads so that the UI thread remains + * free to respond to user inputs.
+ * + *

IMPLEMENTATION
* The main method creates an asynchronous service which does not block the main thread while the * task is being performed. The main thread continues its work which is similar to Async Method * Invocation pattern. The difference between them is that there is a queuing layer between @@ -66,15 +59,14 @@ import java.util.concurrent.LinkedBlockingQueue; * between both layers. Such as Priority Queue can be used as queuing layer to prioritize the way * tasks are executed. Our implementation is just one simple way of implementing this pattern, there * are many variants possible as described in its applications. - * */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { @@ -100,15 +92,13 @@ public class App { } /** - * - * ArithmeticSumTask - * + * ArithmeticSumTask. */ static class ArithmeticSumTask implements AsyncTask { - private long n; + private long numberOfElements; - public ArithmeticSumTask(long n) { - this.n = n; + public ArithmeticSumTask(long numberOfElements) { + this.numberOfElements = numberOfElements; } /* @@ -117,7 +107,7 @@ public class App { */ @Override public Long call() throws Exception { - return ap(n); + return ap(numberOfElements); } /* @@ -128,7 +118,7 @@ public class App { */ @Override public void onPreCall() { - if (n < 0) { + if (numberOfElements < 0) { throw new IllegalArgumentException("n is less than 0"); } } diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java index 0e2701a60..c310d8015 100644 --- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java +++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java @@ -30,7 +30,7 @@ import java.util.concurrent.Callable; * typically done is background threads and the result is posted back in form of callback. The * callback does not implement {@code isComplete}, {@code cancel} as it is out of scope of this * pattern. - * + * * @param type of result */ public interface AsyncTask extends Callable { @@ -53,7 +53,7 @@ public interface AsyncTask extends Callable { /** * A callback called if computing the task resulted in some exception. This method is called when * either of {@link #call()} or {@link #onPreCall()} throw any exception. - * + * * @param throwable error cause */ void onError(Throwable throwable); diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java index 1a6dc0449..3a3bb474c 100644 --- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java +++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java @@ -23,15 +23,14 @@ package com.iluwatar.halfsynchalfasync; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.FutureTask; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This is the asynchronous layer which does not block when a new request arrives. It just passes @@ -63,13 +62,14 @@ public class AsynchronousService { /** * A non-blocking method which performs the task provided in background and returns immediately. - *

- * On successful completion of task the result is posted back using callback method - * {@link AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally due to - * some exception then the reason for error is posted back using callback method - * {@link AsyncTask#onError(Throwable)}. - *

- * NOTE: The results are posted back in the context of background thread in this implementation. + * + *

On successful completion of task the result is posted back using callback method {@link + * AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally due to some + * exception then the reason for error is posted back using callback method {@link + * AsyncTask#onError(Throwable)}. + * + *

NOTE: The results are posted back in the context of background thread in this + * implementation. */ public void execute(final AsyncTask task) { try { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java index f61b3c2bd..4255b3359 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java @@ -31,40 +31,35 @@ import com.iluwatar.hexagonal.module.LotteryTestingModule; import com.iluwatar.hexagonal.sampledata.SampleData; /** - * - * Hexagonal Architecture pattern decouples the application core from the - * services it uses. This allows the services to be plugged in and the - * application will run with or without the services.

- * - * The core logic, or business logic, of an application consists of the - * algorithms that are essential to its purpose. They implement the use - * cases that are the heart of the application. When you change them, you - * change the essence of the application.

- * - * The services are not essential. They can be replaced without changing - * the purpose of the application. Examples: database access and other - * types of storage, user interface components, e-mail and other - * communication components, hardware devices.

- * - * This example demonstrates Hexagonal Architecture with a lottery system. - * The application core is separate from the services that drive it and - * from the services it uses.

- * - * The primary ports for the application are console interfaces - * {@link com.iluwatar.hexagonal.administration.ConsoleAdministration} through which the lottery round is - * initiated and run and {@link com.iluwatar.hexagonal.service.ConsoleLottery} that allows players to - * submit lottery tickets for the draw.

- * - * The secondary ports that application core uses are {@link com.iluwatar.hexagonal.banking.WireTransfers} - * which is a banking service, {@link com.iluwatar.hexagonal.eventlog.LotteryEventLog} that delivers - * eventlog as lottery events occur and {@link com.iluwatar.hexagonal.database.LotteryTicketRepository} - * that is the storage for the lottery tickets. + * Hexagonal Architecture pattern decouples the application core from the services it uses. This + * allows the services to be plugged in and the application will run with or without the services. * + *

The core logic, or business logic, of an application consists of the algorithms that are + * essential to its purpose. They implement the use cases that are the heart of the application. + * When you change them, you change the essence of the application. + * + *

The services are not essential. They can be replaced without changing the purpose of the + * application. Examples: database access and other types of storage, user interface components, + * e-mail and other communication components, hardware devices. + * + *

This example demonstrates Hexagonal Architecture with a lottery system. The application core + * is separate from the services that drive it and from the services it uses. + * + *

The primary ports for the application are console interfaces {@link + * com.iluwatar.hexagonal.administration.ConsoleAdministration} through which the lottery round is + * initiated and run and {@link com.iluwatar.hexagonal.service.ConsoleLottery} that allows players + * to submit lottery tickets for the draw. + * + *

The secondary ports that application core uses are{@link + * com.iluwatar.hexagonal.banking.WireTransfers} which is a banking service, {@link + * com.iluwatar.hexagonal.eventlog.LotteryEventLog} that delivers eventlog as lottery events occur + * and {@link com.iluwatar.hexagonal.database.LotteryTicketRepository} that is the storage for the + * lottery tickets. */ public class App { /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { @@ -73,11 +68,11 @@ public class App { // start new lottery round LotteryAdministration administration = injector.getInstance(LotteryAdministration.class); administration.resetLottery(); - + // submit some lottery tickets LotteryService service = injector.getInstance(LotteryService.class); SampleData.submitTickets(service, 20); - + // perform lottery administration.performLottery(); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java index 5db492636..ca61b7649 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java @@ -30,20 +30,19 @@ import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.module.LotteryModule; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; import com.iluwatar.hexagonal.sampledata.SampleData; +import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Scanner; - /** - * Console interface for lottery administration + * Console interface for lottery administration. */ public class ConsoleAdministration { private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleAdministration.class); /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); @@ -51,7 +50,8 @@ public class ConsoleAdministration { LotteryAdministration administration = injector.getInstance(LotteryAdministration.class); LotteryService service = injector.getInstance(LotteryService.class); SampleData.submitTickets(service, 20); - ConsoleAdministrationSrv consoleAdministration = new ConsoleAdministrationSrvImpl(administration, LOGGER); + ConsoleAdministrationSrv consoleAdministration = + new ConsoleAdministrationSrvImpl(administration, LOGGER); try (Scanner scanner = new Scanner(System.in)) { boolean exit = false; while (!exit) { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java index 70f24739f..ec6f815c3 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java @@ -24,22 +24,22 @@ package com.iluwatar.hexagonal.administration; /** - * Console interface for lottery administration + * Console interface for lottery administration. */ public interface ConsoleAdministrationSrv { /** - * Get all submitted tickets + * Get all submitted tickets. */ void getAllSubmittedTickets(); /** - * Draw lottery numbers + * Draw lottery numbers. */ void performLottery(); /** - * Begin new lottery round + * Begin new lottery round. */ void resetLottery(); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java index d4c154797..fbd00aa1f 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java @@ -28,14 +28,14 @@ import com.iluwatar.hexagonal.domain.LotteryNumbers; import org.slf4j.Logger; /** - * Console implementation for lottery administration + * Console implementation for lottery administration. */ public class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv { private final LotteryAdministration administration; private final Logger logger; /** - * Constructor + * Constructor. */ public ConsoleAdministrationSrvImpl(LotteryAdministration administration, Logger logger) { this.administration = administration; @@ -44,7 +44,8 @@ public class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv { @Override public void getAllSubmittedTickets() { - administration.getAllSubmittedTickets().forEach((k, v) -> logger.info("Key: {}, Value: {}", k, v)); + administration.getAllSubmittedTickets() + .forEach((k, v) -> logger.info("Key: {}, Value: {}", k, v)); } @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java index 94ad542ff..1a0fdb6b0 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java @@ -23,24 +23,22 @@ package com.iluwatar.hexagonal.banking; +import com.iluwatar.hexagonal.domain.LotteryConstants; import java.util.HashMap; import java.util.Map; -import com.iluwatar.hexagonal.domain.LotteryConstants; - /** - * - * Banking implementation - * + * Banking implementation. */ public class InMemoryBank implements WireTransfers { private static Map accounts = new HashMap<>(); - + static { - accounts.put(LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE); + accounts + .put(LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE); } - + @Override public void setFunds(String bankAccount, int amount) { accounts.put(bankAccount, amount); @@ -52,10 +50,10 @@ public class InMemoryBank implements WireTransfers { } @Override - public boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount) { - if (accounts.getOrDefault(sourceBackAccount, 0) >= amount) { - accounts.put(sourceBackAccount, accounts.get(sourceBackAccount) - amount); - accounts.put(destinationBankAccount, accounts.get(destinationBankAccount) + amount); + public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) { + if (accounts.getOrDefault(sourceAccount, 0) >= amount) { + accounts.put(sourceAccount, accounts.get(sourceAccount) - amount); + accounts.put(destinationAccount, accounts.get(destinationAccount) + amount); return true; } else { return false; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java index 4cdb431f3..e1c720c11 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java @@ -27,13 +27,12 @@ import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; -import org.bson.Document; - import java.util.ArrayList; import java.util.List; +import org.bson.Document; /** - * Mongo based banking adapter + * Mongo based banking adapter. */ public class MongoBank implements WireTransfers { @@ -45,28 +44,28 @@ public class MongoBank implements WireTransfers { private MongoCollection accountsCollection; /** - * Constructor + * Constructor. */ public MongoBank() { connect(); } /** - * Constructor accepting parameters + * Constructor accepting parameters. */ public MongoBank(String dbName, String accountsCollectionName) { connect(dbName, accountsCollectionName); } /** - * Connect to database with default parameters + * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_ACCOUNTS_COLLECTION); } /** - * Connect to database with given parameters + * Connect to database with given parameters. */ public void connect(String dbName, String accountsCollectionName) { if (mongoClient != null) { @@ -79,6 +78,8 @@ public class MongoBank implements WireTransfers { } /** + * Get mongo client. + * * @return mongo client */ public MongoClient getMongoClient() { @@ -86,6 +87,7 @@ public class MongoBank implements WireTransfers { } /** + * Get mongo database. * * @return mongo database */ @@ -94,6 +96,7 @@ public class MongoBank implements WireTransfers { } /** + * Get accounts collection. * * @return accounts collection */ @@ -106,7 +109,8 @@ public class MongoBank implements WireTransfers { public void setFunds(String bankAccount, int amount) { Document search = new Document("_id", bankAccount); Document update = new Document("_id", bankAccount).append("funds", amount); - accountsCollection.updateOne(search, new Document("$set", update), new UpdateOptions().upsert(true)); + accountsCollection + .updateOne(search, new Document("$set", update), new UpdateOptions().upsert(true)); } @Override @@ -121,14 +125,14 @@ public class MongoBank implements WireTransfers { } @Override - public boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount) { - int sourceFunds = getFunds(sourceBackAccount); + public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) { + int sourceFunds = getFunds(sourceAccount); if (sourceFunds < amount) { return false; } else { - int destFunds = getFunds(destinationBankAccount); - setFunds(sourceBackAccount, sourceFunds - amount); - setFunds(destinationBankAccount, destFunds + amount); + int destFunds = getFunds(destinationAccount); + setFunds(sourceAccount, sourceFunds - amount); + setFunds(destinationAccount, destFunds + amount); return true; } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java index 4283c6ef2..fad455b9b 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java @@ -24,25 +24,23 @@ package com.iluwatar.hexagonal.banking; /** - * * Interface to bank accounts. - * */ public interface WireTransfers { /** - * Set amount of funds for bank account + * Set amount of funds for bank account. */ void setFunds(String bankAccount, int amount); /** - * Get amount of funds for bank account + * Get amount of funds for bank account. */ int getFunds(String bankAccount); /** - * Transfer funds from one bank account to another + * Transfer funds from one bank account to another. */ boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount); - + } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java index b5cd526f3..a580a7cf5 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java @@ -23,20 +23,17 @@ package com.iluwatar.hexagonal.database; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; import java.util.HashMap; import java.util.Map; import java.util.Optional; -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketId; - /** - * * Mock database for lottery tickets. - * */ public class InMemoryTicketRepository implements LotteryTicketRepository { - + private static Map tickets = new HashMap<>(); @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java index 1beef3cd7..e307004ed 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java @@ -23,37 +23,34 @@ package com.iluwatar.hexagonal.database; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; import java.util.Map; import java.util.Optional; -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketId; - /** - * * Interface for accessing lottery tickets in database. - * */ public interface LotteryTicketRepository { /** - * Find lottery ticket by id + * Find lottery ticket by id. */ Optional findById(LotteryTicketId id); /** - * Save lottery ticket + * Save lottery ticket. */ Optional save(LotteryTicket ticket); /** - * Get all lottery tickets + * Get all lottery tickets. */ Map findAll(); /** - * Delete all lottery tickets + * Delete all lottery tickets. */ void deleteAll(); - + } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java index 91cf0c2a8..794cd363f 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java @@ -30,8 +30,6 @@ import com.iluwatar.hexagonal.domain.PlayerDetails; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; -import org.bson.Document; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -40,9 +38,10 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import org.bson.Document; /** - * Mongo lottery ticket database + * Mongo lottery ticket database. */ public class MongoTicketRepository implements LotteryTicketRepository { @@ -56,14 +55,14 @@ public class MongoTicketRepository implements LotteryTicketRepository { private MongoCollection countersCollection; /** - * Constructor + * Constructor. */ public MongoTicketRepository() { connect(); } /** - * Constructor accepting parameters + * Constructor accepting parameters. */ public MongoTicketRepository(String dbName, String ticketsCollectionName, String countersCollectionName) { @@ -71,14 +70,14 @@ public class MongoTicketRepository implements LotteryTicketRepository { } /** - * Connect to database with default parameters + * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_TICKETS_COLLECTION, DEFAULT_COUNTERS_COLLECTION); } /** - * Connect to database with given parameters + * Connect to database with given parameters. */ public void connect(String dbName, String ticketsCollectionName, String countersCollectionName) { @@ -101,6 +100,8 @@ public class MongoTicketRepository implements LotteryTicketRepository { } /** + * Get next ticket id. + * * @return next ticket id */ public int getNextId() { @@ -112,6 +113,7 @@ public class MongoTicketRepository implements LotteryTicketRepository { } /** + * Get tickets collection. * * @return tickets collection */ @@ -120,6 +122,7 @@ public class MongoTicketRepository implements LotteryTicketRepository { } /** + * Get counters collection. * * @return counters collection */ @@ -155,7 +158,7 @@ public class MongoTicketRepository implements LotteryTicketRepository { public Map findAll() { Map map = new HashMap<>(); List docs = ticketsCollection.find(new Document()).into(new ArrayList<>()); - for (Document doc: docs) { + for (Document doc : docs) { LotteryTicket lotteryTicket = docToTicket(doc); map.put(lotteryTicket.getId(), lotteryTicket); } @@ -174,6 +177,7 @@ public class MongoTicketRepository implements LotteryTicketRepository { .map(Integer::parseInt) .collect(Collectors.toSet()); LotteryNumbers lotteryNumbers = LotteryNumbers.create(numbers); - return new LotteryTicket(new LotteryTicketId(doc.getInteger("ticketId")), playerDetails, lotteryNumbers); + return new LotteryTicket(new LotteryTicketId(doc + .getInteger("ticketId")), playerDetails, lotteryNumbers); } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java index 965f1fc72..b9ebff446 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java @@ -27,13 +27,10 @@ import com.google.inject.Inject; import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; - import java.util.Map; /** - * - * Lottery administration implementation - * + * Lottery administration implementation. */ public class LotteryAdministration { @@ -42,7 +39,7 @@ public class LotteryAdministration { private final WireTransfers wireTransfers; /** - * Constructor + * Constructor. */ @Inject public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications, @@ -53,14 +50,14 @@ public class LotteryAdministration { } /** - * Get all the lottery tickets submitted for lottery + * Get all the lottery tickets submitted for lottery. */ public Map getAllSubmittedTickets() { return repository.findAll(); } /** - * Draw lottery numbers + * Draw lottery numbers. */ public LotteryNumbers performLottery() { LotteryNumbers numbers = LotteryNumbers.createRandom(); @@ -69,11 +66,14 @@ public class LotteryAdministration { LotteryTicketCheckResult result = LotteryUtils.checkTicketForPrize(repository, id, numbers); if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { boolean transferred = wireTransfers.transferFunds(LotteryConstants.PRIZE_AMOUNT, - LotteryConstants.SERVICE_BANK_ACCOUNT, tickets.get(id).getPlayerDetails().getBankAccount()); + LotteryConstants.SERVICE_BANK_ACCOUNT, tickets.get(id).getPlayerDetails() + .getBankAccount()); if (transferred) { - notifications.ticketWon(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); + notifications + .ticketWon(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); } else { - notifications.prizeError(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); + notifications + .prizeError(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); } } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { notifications.ticketDidNotWin(tickets.get(id).getPlayerDetails()); @@ -83,7 +83,7 @@ public class LotteryAdministration { } /** - * Begin new lottery round + * Begin new lottery round. */ public void resetLottery() { repository.deleteAll(); diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java index f33aa9ad8..06bf294ee 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java @@ -24,9 +24,7 @@ package com.iluwatar.hexagonal.domain; /** - * - * Lottery domain constants - * + * Lottery domain constants. */ public class LotteryConstants { @@ -38,5 +36,5 @@ public class LotteryConstants { public static final int TICKET_PRIZE = 3; public static final int SERVICE_BANK_ACCOUNT_BALANCE = 150000; public static final int PLAYER_MAX_BALANCE = 100; - + } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java index 32f39e4cf..9dc00ec76 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java @@ -24,7 +24,6 @@ package com.iluwatar.hexagonal.domain; import com.google.common.base.Joiner; - import java.util.Collections; import java.util.HashSet; import java.util.PrimitiveIterator; @@ -32,15 +31,13 @@ import java.util.Random; import java.util.Set; /** - * - * Value object representing lottery numbers. This lottery uses sets of 4 numbers. The numbers must be unique and - * between 1 and 20. - * + * Value object representing lottery numbers. This lottery uses sets of 4 numbers. The numbers must + * be unique and between 1 and 20. */ public class LotteryNumbers { private final Set numbers; - + public static final int MIN_NUMBER = 1; public static final int MAX_NUMBER = 20; public static final int NUM_NUMBERS = 4; @@ -62,6 +59,8 @@ public class LotteryNumbers { } /** + * Creates a random lottery number. + * * @return random LotteryNumbers */ public static LotteryNumbers createRandom() { @@ -69,13 +68,17 @@ public class LotteryNumbers { } /** + * Creates lottery number from given set of numbers. + * * @return given LotteryNumbers */ public static LotteryNumbers create(Set givenNumbers) { return new LotteryNumbers(givenNumbers); } - + /** + * Get numbers. + * * @return lottery numbers */ public Set getNumbers() { @@ -83,12 +86,14 @@ public class LotteryNumbers { } /** + * Get numbers as string. + * * @return numbers as comma separated string */ public String getNumbersAsString() { return Joiner.on(',').join(numbers); } - + /** * Generates 4 unique random numbers between 1-20 into numbers set. */ @@ -107,17 +112,16 @@ public class LotteryNumbers { } /** - * * Helper class for generating random numbers. - * */ private static class RandomNumberGenerator { private PrimitiveIterator.OfInt randomIterator; /** - * Initialize a new random number generator that generates random numbers in the range [min, max] - * + * Initialize a new random number generator that generates random numbers in the range [min, + * max]. + * * @param min the min value (inclusive) * @param max the max value (inclusive) */ @@ -126,13 +130,15 @@ public class LotteryNumbers { } /** + * Gets next random integer in [min, max] range. + * * @return a random number in the range (min, max) */ public int nextInt() { return randomIterator.nextInt(); } } - + @Override public int hashCode() { final int prime = 31; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java index 8839ccc96..212671d77 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java @@ -27,13 +27,10 @@ import com.google.inject.Inject; import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; - import java.util.Optional; /** - * - * Implementation for lottery service - * + * Implementation for lottery service. */ public class LotteryService { @@ -42,7 +39,7 @@ public class LotteryService { private final WireTransfers wireTransfers; /** - * Constructor + * Constructor. */ @Inject public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications, @@ -53,7 +50,7 @@ public class LotteryService { } /** - * Submit lottery ticket to participate in the lottery + * Submit lottery ticket to participate in the lottery. */ public Optional submitTicket(LotteryTicket ticket) { boolean result = wireTransfers.transferFunds(LotteryConstants.TICKET_PRIZE, @@ -70,9 +67,12 @@ public class LotteryService { } /** - * Check if lottery ticket has won + * Check if lottery ticket has won. */ - public LotteryTicketCheckResult checkTicketForPrize(LotteryTicketId id, LotteryNumbers winningNumbers) { + public LotteryTicketCheckResult checkTicketForPrize( + LotteryTicketId id, + LotteryNumbers winningNumbers + ) { return LotteryUtils.checkTicketForPrize(repository, id, winningNumbers); } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java index fbac5bff3..91c041273 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java @@ -24,9 +24,7 @@ package com.iluwatar.hexagonal.domain; /** - * * Immutable value object representing lottery ticket. - * */ public class LotteryTicket { @@ -44,13 +42,17 @@ public class LotteryTicket { } /** + * Get player details. + * * @return player details */ public PlayerDetails getPlayerDetails() { return playerDetails; } - + /** + * Get lottery numbers. + * * @return lottery numbers */ public LotteryNumbers getNumbers() { @@ -58,6 +60,8 @@ public class LotteryTicket { } /** + * Get ticket id. + * * @return id */ public LotteryTicketId getId() { @@ -65,7 +69,7 @@ public class LotteryTicket { } /** - * set id + * Set ticket id. */ public void setId(LotteryTicketId id) { this.id = id; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java index e5c05301c..c7f07c1df 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java @@ -24,16 +24,18 @@ package com.iluwatar.hexagonal.domain; /** - * * Represents lottery ticket check result. - * */ public class LotteryTicketCheckResult { /** - * Enumeration of Type of Outcomes of a Lottery + * Enumeration of Type of Outcomes of a Lottery. */ - public enum CheckResult { WIN_PRIZE, NO_PRIZE, TICKET_NOT_SUBMITTED } + public enum CheckResult { + WIN_PRIZE, + NO_PRIZE, + TICKET_NOT_SUBMITTED + } private final CheckResult checkResult; private final int prizeAmount; @@ -55,6 +57,8 @@ public class LotteryTicketCheckResult { } /** + * Get result. + * * @return check result */ public CheckResult getResult() { @@ -62,6 +66,8 @@ public class LotteryTicketCheckResult { } /** + * Get prize amount. + * * @return prize amount */ public int getPrizeAmount() { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java index 29fd6b145..d4c036ece 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java @@ -26,13 +26,13 @@ package com.iluwatar.hexagonal.domain; import java.util.concurrent.atomic.AtomicInteger; /** - * Lottery ticked id + * Lottery ticked id. */ public class LotteryTicketId { private static AtomicInteger numAllocated = new AtomicInteger(0); private final int id; - + public LotteryTicketId() { this.id = numAllocated.incrementAndGet(); } @@ -40,7 +40,7 @@ public class LotteryTicketId { public LotteryTicketId(int id) { this.id = id; } - + public int getId() { return id; } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java index ec070429d..84f9af9e8 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java @@ -24,11 +24,11 @@ package com.iluwatar.hexagonal.domain; import com.iluwatar.hexagonal.database.LotteryTicketRepository; - +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; import java.util.Optional; /** - * Lottery utilities + * Lottery utilities. */ public class LotteryUtils { @@ -36,19 +36,22 @@ public class LotteryUtils { } /** - * Checks if lottery ticket has won + * Checks if lottery ticket has won. */ - public static LotteryTicketCheckResult checkTicketForPrize(LotteryTicketRepository repository, LotteryTicketId id, - LotteryNumbers winningNumbers) { + public static LotteryTicketCheckResult checkTicketForPrize( + LotteryTicketRepository repository, + LotteryTicketId id, + LotteryNumbers winningNumbers + ) { Optional optional = repository.findById(id); if (optional.isPresent()) { if (optional.get().getNumbers().equals(winningNumbers)) { - return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.WIN_PRIZE, 1000); + return new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 1000); } else { - return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.NO_PRIZE); + return new LotteryTicketCheckResult(CheckResult.NO_PRIZE); } } else { - return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.TICKET_NOT_SUBMITTED); + return new LotteryTicketCheckResult(CheckResult.TICKET_NOT_SUBMITTED); } } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java index 67b925e73..f2c09744c 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java @@ -24,9 +24,7 @@ package com.iluwatar.hexagonal.domain; /** - * * Immutable value object containing lottery player details. - * */ public class PlayerDetails { @@ -44,20 +42,26 @@ public class PlayerDetails { } /** + * Get email. + * * @return email */ public String getEmail() { return emailAddress; } - + /** + * Get back account number. + * * @return bank account number */ public String getBankAccount() { return bankAccountNumber; } - + /** + * Get phone number. + * * @return phone number */ public String getPhoneNumber() { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java index e13dbfab5..993f2a344 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java @@ -26,34 +26,32 @@ package com.iluwatar.hexagonal.eventlog; import com.iluwatar.hexagonal.domain.PlayerDetails; /** - * - * Event log for lottery events - * + * Event log for lottery events. */ public interface LotteryEventLog { /** - * lottery ticket submitted + * lottery ticket submitted. */ void ticketSubmitted(PlayerDetails details); /** - * error submitting lottery ticket + * error submitting lottery ticket. */ void ticketSubmitError(PlayerDetails details); /** - * lottery ticket did not win + * lottery ticket did not win. */ void ticketDidNotWin(PlayerDetails details); /** - * lottery ticket won + * lottery ticket won. */ void ticketWon(PlayerDetails details, int prizeAmount); /** - * error paying the prize + * error paying the prize. */ void prizeError(PlayerDetails details, int prizeAmount); diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java index 1eda775c0..f979506e4 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java @@ -30,7 +30,7 @@ import com.mongodb.client.MongoDatabase; import org.bson.Document; /** - * Mongo based event log + * Mongo based event log. */ public class MongoEventLog implements LotteryEventLog { @@ -44,28 +44,28 @@ public class MongoEventLog implements LotteryEventLog { private StdOutEventLog stdOutEventLog = new StdOutEventLog(); /** - * Constructor + * Constructor. */ public MongoEventLog() { connect(); } /** - * Constructor accepting parameters + * Constructor accepting parameters. */ public MongoEventLog(String dbName, String eventsCollectionName) { connect(dbName, eventsCollectionName); } /** - * Connect to database with default parameters + * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_EVENTS_COLLECTION); } /** - * Connect to database with given parameters + * Connect to database with given parameters. */ public void connect(String dbName, String eventsCollectionName) { if (mongoClient != null) { @@ -78,6 +78,8 @@ public class MongoEventLog implements LotteryEventLog { } /** + * Get mongo client. + * * @return mongo client */ public MongoClient getMongoClient() { @@ -85,6 +87,7 @@ public class MongoEventLog implements LotteryEventLog { } /** + * Get mongo database. * * @return mongo database */ @@ -93,8 +96,9 @@ public class MongoEventLog implements LotteryEventLog { } /** + * Get events collection. * - * @return accounts collection + * @return events collection */ public MongoCollection getEventsCollection() { return eventsCollection; @@ -106,7 +110,8 @@ public class MongoEventLog implements LotteryEventLog { Document document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); - document.put("message", "Lottery ticket was submitted and bank account was charged for 3 credits."); + document + .put("message", "Lottery ticket was submitted and bank account was charged for 3 credits."); eventsCollection.insertOne(document); stdOutEventLog.ticketSubmitted(details); } @@ -136,8 +141,9 @@ public class MongoEventLog implements LotteryEventLog { Document document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); - document.put("message", String.format("Lottery ticket won! The bank account was deposited with %d credits.", - prizeAmount)); + document.put("message", String + .format("Lottery ticket won! The bank account was deposited with %d credits.", + prizeAmount)); eventsCollection.insertOne(document); stdOutEventLog.ticketWon(details, prizeAmount); } @@ -147,8 +153,9 @@ public class MongoEventLog implements LotteryEventLog { Document document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); - document.put("message", String.format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", - prizeAmount)); + document.put("message", String + .format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", + prizeAmount)); eventsCollection.insertOne(document); stdOutEventLog.prizeError(details, prizeAmount); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java index e236acf69..284fc4d1c 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java @@ -28,7 +28,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Standard output event log + * Standard output event log. */ public class StdOutEventLog implements LotteryEventLog { @@ -42,24 +42,27 @@ public class StdOutEventLog implements LotteryEventLog { @Override public void ticketDidNotWin(PlayerDetails details) { - LOGGER.info("Lottery ticket for {} was checked and unfortunately did not win this time.", details.getEmail()); + LOGGER + .info("Lottery ticket for {} was checked and unfortunately did not win this time.", details + .getEmail()); } @Override public void ticketWon(PlayerDetails details, int prizeAmount) { LOGGER.info("Lottery ticket for {} has won! The bank account {} was deposited with {} credits.", - details.getEmail(), details.getBankAccount(), prizeAmount); + details.getEmail(), details.getBankAccount(), prizeAmount); } @Override public void prizeError(PlayerDetails details, int prizeAmount) { - LOGGER.error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of {} failed.", - details.getEmail(), prizeAmount); + LOGGER + .error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of" + + " {} failed.", details.getEmail(), prizeAmount); } @Override public void ticketSubmitError(PlayerDetails details) { - LOGGER.error("Lottery ticket for {} could not be submitted because the credit transfer of 3 credits failed.", - details.getEmail()); + LOGGER.error("Lottery ticket for {} could not be submitted because the credit transfer" + + " of 3 credits failed.", details.getEmail()); } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java index a8a10b69c..73cf16805 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java @@ -32,7 +32,7 @@ import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import com.iluwatar.hexagonal.eventlog.MongoEventLog; /** - * Guice module for binding production dependencies + * Guice module for binding production dependencies. */ public class LotteryModule extends AbstractModule { @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java index 4fd8262de..f416ffcc2 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java @@ -32,7 +32,7 @@ import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import com.iluwatar.hexagonal.eventlog.StdOutEventLog; /** - * Guice module for testing dependencies + * Guice module for testing dependencies. */ public class LotteryTestingModule extends AbstractModule { @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java index f9edbad99..2d8463f7f 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java @@ -27,7 +27,7 @@ import java.io.FileInputStream; import java.util.Properties; /** - * Mongo connection properties loader + * Mongo connection properties loader. */ public class MongoConnectionPropertiesLoader { @@ -35,8 +35,7 @@ public class MongoConnectionPropertiesLoader { private static final int DEFAULT_PORT = 27017; /** - * Try to load connection properties from file. - * Fall back to default connection properties. + * Try to load connection properties from file. Fall back to default connection properties. */ public static void load() { String host = DEFAULT_HOST; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java index 8189303eb..ccda4a208 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java @@ -30,12 +30,11 @@ import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; - import java.util.List; import java.util.Random; /** - * Utilities for creating sample lottery tickets + * Utilities for creating sample lottery tickets. */ public class SampleData { @@ -44,45 +43,45 @@ public class SampleData { static { PLAYERS = List.of( - new PlayerDetails("john@google.com", "312-342", "+3242434242"), - new PlayerDetails("mary@google.com", "234-987", "+23452346"), - new PlayerDetails("steve@google.com", "833-836", "+63457543"), - new PlayerDetails("wayne@google.com", "319-826", "+24626"), - new PlayerDetails("johnie@google.com", "983-322", "+3635635"), - new PlayerDetails("andy@google.com", "934-734", "+0898245"), - new PlayerDetails("richard@google.com", "536-738", "+09845325"), - new PlayerDetails("kevin@google.com", "453-936", "+2423532"), - new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), - new PlayerDetails("ian@google.com", "663-765", "+928394235"), - new PlayerDetails("robin@google.com", "334-763", "+35448"), - new PlayerDetails("ted@google.com", "735-964", "+98752345"), - new PlayerDetails("larry@google.com", "734-853", "+043842423"), - new PlayerDetails("calvin@google.com", "334-746", "+73294135"), - new PlayerDetails("jacob@google.com", "444-766", "+358042354"), - new PlayerDetails("edwin@google.com", "895-345", "+9752435"), - new PlayerDetails("mary@google.com", "760-009", "+34203542"), - new PlayerDetails("lolita@google.com", "425-907", "+9872342"), - new PlayerDetails("bruno@google.com", "023-638", "+673824122"), - new PlayerDetails("peter@google.com", "335-886", "+5432503945"), - new PlayerDetails("warren@google.com", "225-946", "+9872341324"), - new PlayerDetails("monica@google.com", "265-748", "+134124"), - new PlayerDetails("ollie@google.com", "190-045", "+34453452"), - new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), - new PlayerDetails("lars@google.com", "746-936", "+42345298345"), - new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), - new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), - new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), - new PlayerDetails("nadja@google.com", "000-346", "+498723"), - new PlayerDetails("wendy@google.com", "994-989", "+987324454"), - new PlayerDetails("luke@google.com", "546-634", "+987642435"), - new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), - new PlayerDetails("lisa@google.com", "024-653", "+980742154"), - new PlayerDetails("anton@google.com", "834-935", "+876423145"), - new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), - new PlayerDetails("ray@google.com", "843-073", "+678324123"), - new PlayerDetails("ron@google.com", "637-738", "+09842354"), - new PlayerDetails("xavier@google.com", "143-947", "+375245"), - new PlayerDetails("harriet@google.com", "842-404", "+131243252") + new PlayerDetails("john@google.com", "312-342", "+3242434242"), + new PlayerDetails("mary@google.com", "234-987", "+23452346"), + new PlayerDetails("steve@google.com", "833-836", "+63457543"), + new PlayerDetails("wayne@google.com", "319-826", "+24626"), + new PlayerDetails("johnie@google.com", "983-322", "+3635635"), + new PlayerDetails("andy@google.com", "934-734", "+0898245"), + new PlayerDetails("richard@google.com", "536-738", "+09845325"), + new PlayerDetails("kevin@google.com", "453-936", "+2423532"), + new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), + new PlayerDetails("ian@google.com", "663-765", "+928394235"), + new PlayerDetails("robin@google.com", "334-763", "+35448"), + new PlayerDetails("ted@google.com", "735-964", "+98752345"), + new PlayerDetails("larry@google.com", "734-853", "+043842423"), + new PlayerDetails("calvin@google.com", "334-746", "+73294135"), + new PlayerDetails("jacob@google.com", "444-766", "+358042354"), + new PlayerDetails("edwin@google.com", "895-345", "+9752435"), + new PlayerDetails("mary@google.com", "760-009", "+34203542"), + new PlayerDetails("lolita@google.com", "425-907", "+9872342"), + new PlayerDetails("bruno@google.com", "023-638", "+673824122"), + new PlayerDetails("peter@google.com", "335-886", "+5432503945"), + new PlayerDetails("warren@google.com", "225-946", "+9872341324"), + new PlayerDetails("monica@google.com", "265-748", "+134124"), + new PlayerDetails("ollie@google.com", "190-045", "+34453452"), + new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), + new PlayerDetails("lars@google.com", "746-936", "+42345298345"), + new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), + new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), + new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), + new PlayerDetails("nadja@google.com", "000-346", "+498723"), + new PlayerDetails("wendy@google.com", "994-989", "+987324454"), + new PlayerDetails("luke@google.com", "546-634", "+987642435"), + new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), + new PlayerDetails("lisa@google.com", "024-653", "+980742154"), + new PlayerDetails("anton@google.com", "834-935", "+876423145"), + new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), + new PlayerDetails("ray@google.com", "843-073", "+678324123"), + new PlayerDetails("ron@google.com", "637-738", "+09842354"), + new PlayerDetails("xavier@google.com", "143-947", "+375245"), + new PlayerDetails("harriet@google.com", "842-404", "+131243252") ); InMemoryBank wireTransfers = new InMemoryBank(); for (PlayerDetails player : PLAYERS) { @@ -92,7 +91,7 @@ public class SampleData { } /** - * Inserts lottery tickets into the database based on the sample data + * Inserts lottery tickets into the database based on the sample data. */ public static void submitTickets(LotteryService lotteryService, int numTickets) { for (int i = 0; i < numTickets; i++) { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java index b452a4f5d..dccbf68eb 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java @@ -29,25 +29,24 @@ import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.module.LotteryModule; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Scanner; - /** - * Console interface for lottery players + * Console interface for lottery players. */ public class ConsoleLottery { private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleLottery.class); /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); Injector injector = Guice.createInjector(new LotteryModule()); - LotteryService service = injector.getInstance( LotteryService.class); + LotteryService service = injector.getInstance(LotteryService.class); WireTransfers bank = injector.getInstance(WireTransfers.class); try (Scanner scanner = new Scanner(System.in)) { boolean exit = false; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java index dec414ee4..b5bd01a66 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java @@ -25,31 +25,30 @@ package com.iluwatar.hexagonal.service; import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.domain.LotteryService; - import java.util.Scanner; /** - * Console interface for lottery service + * Console interface for lottery service. */ public interface LotteryConsoleService { void checkTicket(LotteryService service, Scanner scanner); /** - * Submit lottery ticket to participate in the lottery - */ + * Submit lottery ticket to participate in the lottery. + */ void submitTicket(LotteryService service, Scanner scanner); /** - * Add funds to lottery account - */ + * Add funds to lottery account. + */ void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner); /** - * Recovery funds from lottery account - */ + * Recovery funds from lottery account. + */ void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java index 3641b9a5c..d100dba03 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java @@ -24,22 +24,29 @@ package com.iluwatar.hexagonal.service; import com.iluwatar.hexagonal.banking.WireTransfers; -import com.iluwatar.hexagonal.domain.*; +import com.iluwatar.hexagonal.domain.LotteryNumbers; +import com.iluwatar.hexagonal.domain.LotteryService; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.domain.PlayerDetails; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Optional; +import java.util.Scanner; +import java.util.Set; +import java.util.stream.Collectors; import org.slf4j.Logger; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - /** - * Console implementation for lottery console service + * Console implementation for lottery console service. */ public class LotteryConsoleServiceImpl implements LotteryConsoleService { private final Logger logger; /** - * Constructor + * Constructor. */ public LotteryConsoleServiceImpl(Logger logger) { this.logger = logger; @@ -47,79 +54,81 @@ public class LotteryConsoleServiceImpl implements LotteryConsoleService { @Override public void checkTicket(LotteryService service, Scanner scanner) { - logger.info( "What is the ID of the lottery ticket?" ); - String id = readString( scanner ); - logger.info( "Give the 4 comma separated winning numbers?" ); - String numbers = readString( scanner ); + logger.info("What is the ID of the lottery ticket?"); + String id = readString(scanner); + logger.info("Give the 4 comma separated winning numbers?"); + String numbers = readString(scanner); try { - String[] parts = numbers.split( "," ); + String[] parts = numbers.split(","); Set winningNumbers = new HashSet<>(); for (int i = 0; i < 4; i++) { - winningNumbers.add( Integer.parseInt( parts[i] ) ); + winningNumbers.add(Integer.parseInt(parts[i])); } - final LotteryTicketId lotteryTicketId = new LotteryTicketId( Integer.parseInt( id ) ); - final LotteryNumbers lotteryNumbers = LotteryNumbers.create( winningNumbers ); - LotteryTicketCheckResult result = service.checkTicketForPrize( lotteryTicketId, lotteryNumbers ); + final LotteryTicketId lotteryTicketId = new LotteryTicketId(Integer.parseInt(id)); + final LotteryNumbers lotteryNumbers = LotteryNumbers.create(winningNumbers); + LotteryTicketCheckResult result = + service.checkTicketForPrize(lotteryTicketId, lotteryNumbers); - if (result.getResult().equals( LotteryTicketCheckResult.CheckResult.WIN_PRIZE )) { - logger.info( "Congratulations! The lottery ticket has won!" ); - } else if (result.getResult().equals( LotteryTicketCheckResult.CheckResult.NO_PRIZE )) { - logger.info( "Unfortunately the lottery ticket did not win." ); + if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { + logger.info("Congratulations! The lottery ticket has won!"); + } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { + logger.info("Unfortunately the lottery ticket did not win."); } else { - logger.info( "Such lottery ticket has not been submitted." ); + logger.info("Such lottery ticket has not been submitted."); } } catch (Exception e) { - logger.info( "Failed checking the lottery ticket - please try again." ); + logger.info("Failed checking the lottery ticket - please try again."); } } @Override public void submitTicket(LotteryService service, Scanner scanner) { - logger.info( "What is your email address?" ); - String email = readString( scanner ); - logger.info( "What is your bank account number?" ); - String account = readString( scanner ); - logger.info( "What is your phone number?" ); - String phone = readString( scanner ); - PlayerDetails details = new PlayerDetails( email, account, phone ); - logger.info( "Give 4 comma separated lottery numbers?" ); - String numbers = readString( scanner ); + logger.info("What is your email address?"); + String email = readString(scanner); + logger.info("What is your bank account number?"); + String account = readString(scanner); + logger.info("What is your phone number?"); + String phone = readString(scanner); + PlayerDetails details = new PlayerDetails(email, account, phone); + logger.info("Give 4 comma separated lottery numbers?"); + String numbers = readString(scanner); try { - String[] parts = numbers.split( "," ); + String[] parts = numbers.split(","); Set chosen = Arrays.stream(parts).map(Integer::parseInt).collect(Collectors.toSet()); - LotteryNumbers lotteryNumbers = LotteryNumbers.create( chosen ); - LotteryTicket lotteryTicket = new LotteryTicket( new LotteryTicketId(), details, lotteryNumbers ); - Optional id = service.submitTicket( lotteryTicket ); + LotteryNumbers lotteryNumbers = LotteryNumbers.create(chosen); + LotteryTicket lotteryTicket = + new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); + Optional id = service.submitTicket(lotteryTicket); if (id.isPresent()) { - logger.info( "Submitted lottery ticket with id: {}", id.get() ); + logger.info("Submitted lottery ticket with id: {}", id.get()); } else { - logger.info( "Failed submitting lottery ticket - please try again." ); + logger.info("Failed submitting lottery ticket - please try again."); } } catch (Exception e) { - logger.info( "Failed submitting lottery ticket - please try again." ); + logger.info("Failed submitting lottery ticket - please try again."); } } @Override public void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) { - logger.info( "What is the account number?" ); - String account = readString( scanner ); - logger.info( "How many credits do you want to deposit?" ); - String amount = readString( scanner ); - bank.setFunds( account, Integer.parseInt( amount ) ); - logger.info( "The account {} now has {} credits.", account, bank.getFunds( account ) ); + logger.info("What is the account number?"); + String account = readString(scanner); + logger.info("How many credits do you want to deposit?"); + String amount = readString(scanner); + bank.setFunds(account, Integer.parseInt(amount)); + logger.info("The account {} now has {} credits.", account, bank.getFunds(account)); } @Override public void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner) { - logger.info( "What is the account number?" ); - String account = readString( scanner ); - logger.info( "The account {} has {} credits.", account, bank.getFunds( account ) ); + logger.info("What is the account number?"); + String account = readString(scanner); + logger.info("The account {} has {} credits.", account, bank.getFunds(account)); } private String readString(Scanner scanner) { - logger.info( "> " ); + logger.info("> "); return scanner.next(); } }