#1021 enforce Checkstyle rules in the build

This commit is contained in:
Ilkka Seppälä 2019-11-16 16:00:24 +02:00
parent 9e58edf05e
commit 8747f1fd7a
17 changed files with 239 additions and 208 deletions

View File

@ -32,7 +32,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
* Test for abstract factory * Test for abstract factory.
*/ */
public class AbstractFactoryTest { public class AbstractFactoryTest {

View File

@ -37,6 +37,10 @@ public class Word extends LetterComposite {
letters.forEach(this::add); letters.forEach(this::add);
} }
/**
* Constructor.
* @param letters to include
*/
public Word(char... letters) { public Word(char... letters) {
for (char letter : letters) { for (char letter : letters) {
this.add(new Letter(letter)); this.add(new Letter(letter));

View File

@ -23,12 +23,12 @@
package com.iluwatar.layers.service; package com.iluwatar.layers.service;
import com.iluwatar.layers.dto.CakeInfo;
import com.iluwatar.layers.dto.CakeLayerInfo;
import com.iluwatar.layers.dto.CakeToppingInfo;
import com.iluwatar.layers.dao.CakeDao; import com.iluwatar.layers.dao.CakeDao;
import com.iluwatar.layers.dao.CakeLayerDao; import com.iluwatar.layers.dao.CakeLayerDao;
import com.iluwatar.layers.dao.CakeToppingDao; import com.iluwatar.layers.dao.CakeToppingDao;
import com.iluwatar.layers.dto.CakeInfo;
import com.iluwatar.layers.dto.CakeLayerInfo;
import com.iluwatar.layers.dto.CakeToppingInfo;
import com.iluwatar.layers.entity.Cake; import com.iluwatar.layers.entity.Cake;
import com.iluwatar.layers.entity.CakeLayer; import com.iluwatar.layers.entity.CakeLayer;
import com.iluwatar.layers.entity.CakeTopping; import com.iluwatar.layers.entity.CakeTopping;
@ -40,7 +40,6 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;

View File

@ -70,12 +70,13 @@ public final class App {
File applicationFile = File applicationFile =
new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath()); new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath());
// should work for unix like OS (mac, unix etc...) // Should work for unix like OS (mac, unix etc...)
if (Desktop.isDesktopSupported()) { if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(applicationFile); Desktop.getDesktop().open(applicationFile);
} else { } else {
// java Desktop not supported - above unlikely to work for Windows so try following instead... // Java Desktop not supported - above unlikely to work for Windows so try the
// following instead...
Runtime.getRuntime().exec("cmd.exe start " + applicationFile); Runtime.getRuntime().exec("cmd.exe start " + applicationFile);
} }

View File

@ -384,9 +384,6 @@
</pluginManagement> </pluginManagement>
<plugins> <plugins>
<!--checkstyle plug-in. checking against googles styles
see config at checkstyle.xml
-->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId> <artifactId>maven-checkstyle-plugin</artifactId>
@ -403,7 +400,8 @@
<suppressionsLocation>checkstyle-suppressions.xml</suppressionsLocation> <suppressionsLocation>checkstyle-suppressions.xml</suppressionsLocation>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<failOnViolation>true</failOnViolation> <failOnViolation>true</failOnViolation>
<includeTestSourceDirectory>true</includeTestSourceDirectory> <violationSeverity>warning</violationSeverity>
<includeTestSourceDirectory>false</includeTestSourceDirectory>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>

View File

@ -23,20 +23,22 @@
package com.iluwatar.producer.consumer; package com.iluwatar.producer.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between * Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces
* Producer and Consumer by separating Identification of work with Execution of Work. * coupling between Producer and Consumer by separating Identification of work with
* <p> * Execution of Work.
* In producer consumer design pattern a shared queue is used to control the flow and this separation allows you to code *
* producer and consumer separately. It also addresses the issue of different timing require to produce item or * <p>In producer consumer design pattern a shared queue is used to control the flow and this
* consuming item. by using producer consumer pattern both Producer and Consumer Thread can work with different speed. * separation allows you to code producer and consumer separately. It also addresses the issue
* of different timing require to produce item or consuming item. by using producer consumer
* pattern both Producer and Consumer Thread can work with different speed.
* *
*/ */
public class App { public class App {
@ -44,7 +46,7 @@ public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class); private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Program entry point * Program entry point.
* *
* @param args * @param args
* command line args * command line args

View File

@ -27,7 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* Class responsible for consume the {@link Item} produced by {@link Producer} * Class responsible for consume the {@link Item} produced by {@link Producer}.
*/ */
public class Consumer { public class Consumer {
@ -43,12 +43,13 @@ public class Consumer {
} }
/** /**
* Consume item from the queue * Consume item from the queue.
*/ */
public void consume() throws InterruptedException { public void consume() throws InterruptedException {
Item item = queue.take(); Item item = queue.take();
LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name, item.getId(), item.getProducer()); LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name,
item.getId(), item.getProducer());
} }
} }

View File

@ -27,7 +27,7 @@ import java.util.Random;
/** /**
* Class responsible for producing unit of work that can be expressed as {@link Item} and submitted * Class responsible for producing unit of work that can be expressed as {@link Item} and submitted
* to queue * to queue.
*/ */
public class Producer { public class Producer {
@ -45,7 +45,7 @@ public class Producer {
} }
/** /**
* Put item in the queue * Put item in the queue.
*/ */
public void produce() throws InterruptedException { public void produce() throws InterruptedException {

View File

@ -22,8 +22,6 @@
*/ */
package com.iluwatar.promise; package com.iluwatar.promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -32,10 +30,12 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* * The Promise object is used for asynchronous computations. A Promise represents an operation
* The Promise object is used for asynchronous computations. A Promise represents an operation * that hasn't completed yet, but is expected in the future.
* that hasn't completed yet, but is expected in the future.
* *
* <p>A Promise represents a proxy for a value not necessarily known when the promise is created. It * <p>A Promise represents a proxy for a value not necessarily known when the promise is created. It
* allows you to associate dependent promises to an asynchronous action's eventual success value or * allows you to associate dependent promises to an asynchronous action's eventual success value or
@ -49,15 +49,14 @@ import java.util.concurrent.Executors;
* <li> Prevents callback hell and provides callback aggregation * <li> Prevents callback hell and provides callback aggregation
* </ul> * </ul>
* *
* <p> * <p>In this application the usage of promise is demonstrated with two examples:
* In this application the usage of promise is demonstrated with two examples:
* <ul> * <ul>
* <li>Count Lines: In this example a file is downloaded and its line count is calculated. * <li>Count Lines: In this example a file is downloaded and its line count is calculated.
* The calculated line count is then consumed and printed on console. * The calculated line count is then consumed and printed on console.
* <li>Lowest Character Frequency: In this example a file is downloaded and its lowest frequency * <li>Lowest Character Frequency: In this example a file is downloaded and its lowest frequency
* character is found and printed on console. This happens via a chain of promises, we start with * character is found and printed on console. This happens via a chain of promises, we start with
* a file download promise, then a promise of character frequency, then a promise of lowest frequency * a file download promise, then a promise of character frequency, then a promise of lowest
* character which is finally consumed and result is printed on console. * frequency character which is finally consumed and result is printed on console.
* </ul> * </ul>
* *
* @see CompletableFuture * @see CompletableFuture
@ -76,7 +75,7 @@ public class App {
} }
/** /**
* Program entry point * Program entry point.
* @param args arguments * @param args arguments
* @throws InterruptedException if main thread is interrupted. * @throws InterruptedException if main thread is interrupted.
* @throws ExecutionException if an execution error occurs. * @throws ExecutionException if an execution error occurs.

View File

@ -23,9 +23,6 @@
package com.iluwatar.promise; package com.iluwatar.promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
@ -39,8 +36,11 @@ import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Utility to perform various operations * Utility to perform various operations.
*/ */
public class Utility { public class Utility {
@ -71,7 +71,8 @@ public class Utility {
} }
/** /**
* @return the character with lowest frequency if it exists, {@code Optional.empty()} otherwise. * Return the character with the lowest frequency, if exists.
* @return the character, {@code Optional.empty()} otherwise.
*/ */
public static Character lowestFrequencyChar(Map<Character, Integer> charFrequency) { public static Character lowestFrequencyChar(Map<Character, Integer> charFrequency) {
Character lowestFrequencyChar = null; Character lowestFrequencyChar = null;
@ -92,7 +93,8 @@ public class Utility {
} }
/** /**
* @return number of lines in the file at provided location. 0 if file does not exist. * Count the number of lines in a file.
* @return number of lines, 0 if file does not exist.
*/ */
public static Integer countLines(String fileLocation) { public static Integer countLines(String fileLocation) {
int lineCount = 0; int lineCount = 0;

View File

@ -20,13 +20,15 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.roleobject; package com.iluwatar.roleobject;
import static com.iluwatar.roleobject.Role.Borrower;
import static com.iluwatar.roleobject.Role.Investor;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static com.iluwatar.roleobject.Role.*;
/** /**
* The Role Object pattern suggests to model context-specific views * The Role Object pattern suggests to model context-specific views
* of an object as separate role objects which are * of an object as separate role objects which are
@ -39,55 +41,60 @@ import static com.iluwatar.roleobject.Role.*;
* investor, respectively. Both roles could as well be played by a single {@link Customer} object. * investor, respectively. Both roles could as well be played by a single {@link Customer} object.
* The common superclass for customer-specific roles is provided by {@link CustomerRole}, * The common superclass for customer-specific roles is provided by {@link CustomerRole},
* which also supports the {@link Customer} interface. * which also supports the {@link Customer} interface.
* <p> *
* The {@link CustomerRole} class is abstract and not meant to be instantiated. * <p>The {@link CustomerRole} class is abstract and not meant to be instantiated.
* Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole} or {@link InvestorRole}, * Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole}
* define and implement the interface for specific roles. It is only * or {@link InvestorRole}, define and implement the interface for specific roles. It is only
* these subclasses which are instantiated at runtime. * these subclasses which are instantiated at runtime.
* The {@link BorrowerRole} class defines the context-specific view of {@link Customer} objects as needed by the loan department. * The {@link BorrowerRole} class defines the context-specific view of {@link Customer}
* objects as needed by the loan department.
* It defines additional operations to manage the customers * It defines additional operations to manage the customers
* credits and securities. Similarly, the {@link InvestorRole} class adds operations specific * credits and securities. Similarly, the {@link InvestorRole} class adds operations specific
* to the investment departments view of customers. * to the investment departments view of customers.
* A client like the loan application may either work with objects of the {@link CustomerRole} class, using the interface class * A client like the loan application may either work with objects of the {@link CustomerRole}
* {@link Customer}, or with objects of concrete {@link CustomerRole} subclasses. Suppose the loan application knows a particular * class, using the interface class {@link Customer}, or with objects of concrete
* {@link Customer} instance through its {@link Customer} interface. The loan application may want to check whether the {@link Customer} * {@link CustomerRole} subclasses. Suppose the loan application knows a particular
* object plays the role of Borrower. * {@link Customer} instance through its {@link Customer} interface. The loan application
* To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For the purpose of * may want to check whether the {@link Customer} object plays the role of Borrower.
* our example, lets assume we can name roles with enum. * To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For
* If the {@link Customer} object can play the role named Borrower, the loan application will ask it * the purpose of our example, lets assume we can name roles with enum.
* to return a reference to the corresponding object. * If the {@link Customer} object can play the role named Borrower, the loan application will
* ask it to return a reference to the corresponding object.
* The loan application may now use this reference to call Borrower-specific operations. * The loan application may now use this reference to call Borrower-specific operations.
*/ */
public class ApplicationRoleObject { public class ApplicationRoleObject {
private static final Logger logger = LoggerFactory.getLogger(Role.class); private static final Logger logger = LoggerFactory.getLogger(Role.class);
public static void main(String[] args) { /**
Customer customer = Customer.newCustomer(Borrower, Investor); * Main entry point.
*
* @param args program arguments
*/
public static void main(String[] args) {
Customer customer = Customer.newCustomer(Borrower, Investor);
logger.info(" the new customer created : {}", customer); logger.info(" the new customer created : {}", customer);
boolean hasBorrowerRole = customer.hasRole(Borrower); boolean hasBorrowerRole = customer.hasRole(Borrower);
logger.info(" customer has a borrowed role - {}", hasBorrowerRole); logger.info(" customer has a borrowed role - {}", hasBorrowerRole);
boolean hasInvestorRole = customer.hasRole(Investor); boolean hasInvestorRole = customer.hasRole(Investor);
logger.info(" customer has an investor role - {}", hasInvestorRole); logger.info(" customer has an investor role - {}", hasInvestorRole);
customer.getRole(Investor, InvestorRole.class) customer.getRole(Investor, InvestorRole.class)
.ifPresent(inv -> { .ifPresent(inv -> {
inv.setAmountToInvest(1000); inv.setAmountToInvest(1000);
inv.setName("Billy"); inv.setName("Billy");
}); });
customer.getRole(Borrower, BorrowerRole.class) customer.getRole(Borrower, BorrowerRole.class)
.ifPresent(inv -> inv.setName("Johny")); .ifPresent(inv -> inv.setName("Johny"));
customer.getRole(Investor, InvestorRole.class)
.map(InvestorRole::invest)
.ifPresent(logger::info);
customer.getRole(Borrower, BorrowerRole.class)
.map(BorrowerRole::borrow)
.ifPresent(logger::info);
}
customer.getRole(Investor, InvestorRole.class)
.map(InvestorRole::invest)
.ifPresent(logger::info);
customer.getRole(Borrower, BorrowerRole.class)
.map(BorrowerRole::borrow)
.ifPresent(logger::info);
}
} }

View File

@ -20,21 +20,23 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.roleobject; package com.iluwatar.roleobject;
public class BorrowerRole extends CustomerRole{ public class BorrowerRole extends CustomerRole {
private String name;
public String getName() { private String name;
return name;
}
public void setName(String name) { public String getName() {
this.name = name; return name;
} }
public String borrow(){ public void setName(String name) {
return String.format("Borrower %s wants to get some money.",name); this.name = name;
} }
public String borrow() {
return String.format("Borrower %s wants to get some money.", name);
}
} }

View File

@ -20,6 +20,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.roleobject; package com.iluwatar.roleobject;
import java.util.Optional; import java.util.Optional;
@ -29,51 +30,52 @@ import java.util.Optional;
*/ */
public abstract class Customer { public abstract class Customer {
/** /**
* Add specific role @see {@link Role} * Add specific role @see {@link Role}.
* * @param role to add
* @param role to add * @return true if the operation has been successful otherwise false
* @return true if the operation has been successful otherwise false */
*/ public abstract boolean addRole(Role role);
public abstract boolean addRole(Role role);
/** /**
* Check specific role @see {@link Role} * Check specific role @see {@link Role}.
* * @param role to check
* @param role to check * @return true if the role exists otherwise false
* @return true if the role exists otherwise false */
*/
public abstract boolean hasRole(Role role); public abstract boolean hasRole(Role role);
/** /**
* Remove specific role @see {@link Role} * Remove specific role @see {@link Role}.
* * @param role to remove
* @param role to remove * @return true if the operation has been successful otherwise false
* @return true if the operation has been successful otherwise false */
*/ public abstract boolean remRole(Role role);
public abstract boolean remRole(Role role);
/** /**
* Get specific instance associated with this role @see {@link Role} * Get specific instance associated with this role @see {@link Role}.
* * @param role to get
* @param role to get * @param expectedRole instance class expected to get
* @param expectedRole instance class expected to get * @return optional with value if the instance exists and corresponds expected class
* @return optional with value if the instance exists and corresponds expected class */
*/ public abstract <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole);
public abstract <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole);
public static Customer newCustomer() { public static Customer newCustomer() {
return new CustomerCore(); return new CustomerCore();
} }
public static Customer newCustomer(Role... role) { /**
Customer customer = newCustomer(); * Create {@link Customer} with given roles.
for (Role r : role) { * @param role roles
customer.addRole(r); * @return Customer
} */
return customer; public static Customer newCustomer(Role... role) {
Customer customer = newCustomer();
for (Role r : role) {
customer.addRole(r);
} }
return customer;
}
} }

View File

@ -20,56 +20,60 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.roleobject; package com.iluwatar.roleobject;
import java.util.*; import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/** /**
* Core class to store different customer roles * Core class to store different customer roles.
* *
* @see CustomerRole * @see CustomerRole Note: not thread safe
* Note: not thread safe
*/ */
public class CustomerCore extends Customer { public class CustomerCore extends Customer {
private Map<Role, CustomerRole> roles; private Map<Role, CustomerRole> roles;
public CustomerCore() { public CustomerCore() {
roles = new HashMap<>(); roles = new HashMap<>();
} }
@Override @Override
public boolean addRole(Role role) { public boolean addRole(Role role) {
return role return role
.instance() .instance()
.map(inst -> { .map(inst -> {
roles.put(role, inst); roles.put(role, inst);
return true; return true;
}) })
.orElse(false); .orElse(false);
} }
@Override @Override
public boolean hasRole(Role role) { public boolean hasRole(Role role) {
return roles.containsKey(role); return roles.containsKey(role);
} }
@Override @Override
public boolean remRole(Role role) { public boolean remRole(Role role) {
return Objects.nonNull(roles.remove(role)); return Objects.nonNull(roles.remove(role));
} }
@Override @Override
public <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole) { public <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole) {
return Optional return Optional
.ofNullable(roles.get(role)) .ofNullable(roles.get(role))
.filter(expectedRole::isInstance) .filter(expectedRole::isInstance)
.map(expectedRole::cast); .map(expectedRole::cast);
} }
@Override @Override
public String toString() { public String toString() {
String roles = Arrays.toString(this.roles.keySet().toArray()); String roles = Arrays.toString(this.roles.keySet().toArray());
return "Customer{roles=" + roles + "}"; return "Customer{roles=" + roles + "}";
} }
} }

View File

@ -20,9 +20,11 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.roleobject; package com.iluwatar.roleobject;
/** /**
* Key abstraction for segregated roles * Key abstraction for segregated roles.
*/ */
public abstract class CustomerRole extends CustomerCore{} public abstract class CustomerRole extends CustomerCore{
}

View File

@ -20,29 +20,32 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.roleobject; package com.iluwatar.roleobject;
public class InvestorRole extends CustomerRole { public class InvestorRole extends CustomerRole {
private String name;
private long amountToInvest;
public String getName() { private String name;
return name;
}
public void setName(String name) { private long amountToInvest;
this.name = name;
}
public long getAmountToInvest() { public String getName() {
return amountToInvest; return name;
} }
public void setAmountToInvest(long amountToInvest) { public void setName(String name) {
this.amountToInvest = amountToInvest; this.name = name;
} }
public String invest() { public long getAmountToInvest() {
return String.format("Investor %s has invested %d dollars", name, amountToInvest); return amountToInvest;
} }
public void setAmountToInvest(long amountToInvest) {
this.amountToInvest = amountToInvest;
}
public String invest() {
return String.format("Investor %s has invested %d dollars", name, amountToInvest);
}
} }

View File

@ -20,36 +20,41 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.roleobject; package com.iluwatar.roleobject;
import java.util.Optional;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Optional;
/** /**
* Possible roles * Possible roles.
*/ */
public enum Role { public enum Role {
Borrower(BorrowerRole.class), Investor(InvestorRole.class);
private Class<? extends CustomerRole> typeCst; Borrower(BorrowerRole.class), Investor(InvestorRole.class);
Role(Class<? extends CustomerRole> typeCst) { private Class<? extends CustomerRole> typeCst;
this.typeCst = typeCst;
} Role(Class<? extends CustomerRole> typeCst) {
this.typeCst = typeCst;
private static final Logger logger = LoggerFactory.getLogger(Role.class); }
@SuppressWarnings("unchecked") private static final Logger logger = LoggerFactory.getLogger(Role.class);
public <T extends CustomerRole> Optional<T> instance() {
Class<? extends CustomerRole> typeCst = this.typeCst; /**
try { * Get instance.
return (Optional<T>) Optional.of(typeCst.newInstance()); */
} catch (InstantiationException | IllegalAccessException e) { @SuppressWarnings("unchecked")
logger.error("error creating an object", e); public <T extends CustomerRole> Optional<T> instance() {
} Class<? extends CustomerRole> typeCst = this.typeCst;
return Optional.empty(); try {
return (Optional<T>) Optional.of(typeCst.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
logger.error("error creating an object", e);
} }
return Optional.empty();
}
} }