#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;
/**
* Test for abstract factory
* Test for abstract factory.
*/
public class AbstractFactoryTest {

View File

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

View File

@ -23,12 +23,12 @@
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.CakeLayerDao;
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.CakeLayer;
import com.iluwatar.layers.entity.CakeTopping;
@ -40,7 +40,6 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

View File

@ -70,12 +70,13 @@ public final class App {
File applicationFile =
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()) {
Desktop.getDesktop().open(applicationFile);
} 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);
}

View File

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

View File

@ -23,20 +23,22 @@
package com.iluwatar.producer.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
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 and Consumer by separating Identification of work with Execution of Work.
* <p>
* 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
* consuming item. by using producer consumer pattern both Producer and Consumer Thread can work with different speed.
* Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces
* coupling between Producer and Consumer by separating Identification of work with
* Execution of Work.
*
* <p>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 consuming item. by using producer consumer
* pattern both Producer and Consumer Thread can work with different speed.
*
*/
public class App {
@ -44,7 +46,7 @@ public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program entry point
* Program entry point.
*
* @param args
* command line args

View File

@ -27,7 +27,7 @@ import org.slf4j.Logger;
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 {
@ -43,12 +43,13 @@ public class Consumer {
}
/**
* Consume item from the queue
* Consume item from the queue.
*/
public void consume() throws InterruptedException {
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
* to queue
* to queue.
*/
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 {

View File

@ -22,8 +22,6 @@
*/
package com.iluwatar.promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@ -32,10 +30,12 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
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
* that hasn't completed yet, but is expected in the future.
* The Promise object is used for asynchronous computations. A Promise represents an operation
* 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
* 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
* </ul>
*
* <p>
* In this application the usage of promise is demonstrated with two examples:
* <p>In this application the usage of promise is demonstrated with two examples:
* <ul>
* <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.
* <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
* a file download promise, then a promise of character frequency, then a promise of lowest frequency
* character which is finally consumed and result is printed on console.
* a file download promise, then a promise of character frequency, then a promise of lowest
* frequency character which is finally consumed and result is printed on console.
* </ul>
*
* @see CompletableFuture
@ -76,7 +75,7 @@ public class App {
}
/**
* Program entry point
* Program entry point.
* @param args arguments
* @throws InterruptedException if main thread is interrupted.
* @throws ExecutionException if an execution error occurs.

View File

@ -23,9 +23,6 @@
package com.iluwatar.promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
@ -39,8 +36,11 @@ import java.util.Iterator;
import java.util.Map;
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 {
@ -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) {
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) {
int lineCount = 0;

View File

@ -20,13 +20,15 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
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.LoggerFactory;
import static com.iluwatar.roleobject.Role.*;
/**
* The Role Object pattern suggests to model context-specific views
* 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.
* The common superclass for customer-specific roles is provided by {@link CustomerRole},
* which also supports the {@link Customer} interface.
* <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},
* define and implement the interface for specific roles. It is only
*
* <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}, define and implement the interface for specific roles. It is only
* 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
* credits and securities. Similarly, the {@link InvestorRole} class adds operations specific
* 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
* {@link Customer}, or with objects of concrete {@link CustomerRole} subclasses. Suppose the loan application knows a particular
* {@link Customer} instance through its {@link Customer} interface. The loan application may want to check whether the {@link Customer}
* object plays the role of Borrower.
* To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For the purpose of
* our example, lets assume we can name roles with enum.
* 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.
* A client like the loan application may either work with objects of the {@link CustomerRole}
* class, using the interface class {@link Customer}, or with objects of concrete
* {@link CustomerRole} subclasses. Suppose the loan application knows a particular
* {@link Customer} instance through its {@link Customer} interface. The loan application
* may want to check whether the {@link Customer} object plays the role of Borrower.
* To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For
* the purpose of our example, lets assume we can name roles with enum.
* 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.
*/
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);
logger.info(" customer has a borrowed role - {}", hasBorrowerRole);
boolean hasInvestorRole = customer.hasRole(Investor);
logger.info(" customer has an investor role - {}", hasInvestorRole);
boolean hasBorrowerRole = customer.hasRole(Borrower);
logger.info(" customer has a borrowed role - {}", hasBorrowerRole);
boolean hasInvestorRole = customer.hasRole(Investor);
logger.info(" customer has an investor role - {}", hasInvestorRole);
customer.getRole(Investor, InvestorRole.class)
.ifPresent(inv -> {
inv.setAmountToInvest(1000);
inv.setName("Billy");
});
customer.getRole(Borrower, BorrowerRole.class)
.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)
.ifPresent(inv -> {
inv.setAmountToInvest(1000);
inv.setName("Billy");
});
customer.getRole(Borrower, BorrowerRole.class)
.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);
}
}

View File

@ -20,21 +20,23 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.roleobject;
public class BorrowerRole extends CustomerRole{
private String name;
public class BorrowerRole extends CustomerRole {
public String getName() {
return name;
}
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String borrow(){
return String.format("Borrower %s wants to get some money.",name);
}
public void setName(String 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
* THE SOFTWARE.
*/
package com.iluwatar.roleobject;
import java.util.Optional;
@ -29,51 +30,52 @@ import java.util.Optional;
*/
public abstract class Customer {
/**
* Add specific role @see {@link Role}
*
* @param role to add
* @return true if the operation has been successful otherwise false
*/
public abstract boolean addRole(Role role);
/**
* Add specific role @see {@link Role}.
* @param role to add
* @return true if the operation has been successful otherwise false
*/
public abstract boolean addRole(Role role);
/**
* Check specific role @see {@link Role}
*
* @param role to check
* @return true if the role exists otherwise false
*/
/**
* Check specific role @see {@link Role}.
* @param role to check
* @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}
*
* @param role to remove
* @return true if the operation has been successful otherwise false
*/
public abstract boolean remRole(Role role);
/**
* Remove specific role @see {@link Role}.
* @param role to remove
* @return true if the operation has been successful otherwise false
*/
public abstract boolean remRole(Role role);
/**
* Get specific instance associated with this role @see {@link Role}
*
* @param role to get
* @param expectedRole instance class expected to get
* @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);
/**
* Get specific instance associated with this role @see {@link Role}.
* @param role to get
* @param expectedRole instance class expected to get
* @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 static Customer newCustomer() {
return new CustomerCore();
}
public static Customer newCustomer(Role... role) {
Customer customer = newCustomer();
for (Role r : role) {
customer.addRole(r);
}
return customer;
public static Customer newCustomer() {
return new CustomerCore();
}
/**
* Create {@link Customer} with given roles.
* @param role roles
* @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
* THE SOFTWARE.
*/
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
* Note: not thread safe
* @see CustomerRole Note: not thread safe
*/
public class CustomerCore extends Customer {
private Map<Role, CustomerRole> roles;
private Map<Role, CustomerRole> roles;
public CustomerCore() {
roles = new HashMap<>();
}
public CustomerCore() {
roles = new HashMap<>();
}
@Override
public boolean addRole(Role role) {
return role
.instance()
.map(inst -> {
roles.put(role, inst);
return true;
})
.orElse(false);
}
@Override
public boolean addRole(Role role) {
return role
.instance()
.map(inst -> {
roles.put(role, inst);
return true;
})
.orElse(false);
}
@Override
public boolean hasRole(Role role) {
return roles.containsKey(role);
}
@Override
public boolean hasRole(Role role) {
return roles.containsKey(role);
}
@Override
public boolean remRole(Role role) {
return Objects.nonNull(roles.remove(role));
}
@Override
public boolean remRole(Role role) {
return Objects.nonNull(roles.remove(role));
}
@Override
public <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole) {
return Optional
.ofNullable(roles.get(role))
.filter(expectedRole::isInstance)
.map(expectedRole::cast);
}
@Override
public <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole) {
return Optional
.ofNullable(roles.get(role))
.filter(expectedRole::isInstance)
.map(expectedRole::cast);
}
@Override
public String toString() {
String roles = Arrays.toString(this.roles.keySet().toArray());
return "Customer{roles=" + roles + "}";
}
@Override
public String toString() {
String roles = Arrays.toString(this.roles.keySet().toArray());
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
* THE SOFTWARE.
*/
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
* THE SOFTWARE.
*/
package com.iluwatar.roleobject;
public class InvestorRole extends CustomerRole {
private String name;
private long amountToInvest;
public String getName() {
return name;
}
private String name;
public void setName(String name) {
this.name = name;
}
private long amountToInvest;
public long getAmountToInvest() {
return amountToInvest;
}
public String getName() {
return name;
}
public void setAmountToInvest(long amountToInvest) {
this.amountToInvest = amountToInvest;
}
public void setName(String name) {
this.name = name;
}
public String invest() {
return String.format("Investor %s has invested %d dollars", name, amountToInvest);
}
public long getAmountToInvest() {
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
* THE SOFTWARE.
*/
package com.iluwatar.roleobject;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
/**
* Possible roles
* Possible roles.
*/
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) {
this.typeCst = typeCst;
}
private static final Logger logger = LoggerFactory.getLogger(Role.class);
@SuppressWarnings("unchecked")
public <T extends CustomerRole> Optional<T> instance() {
Class<? extends CustomerRole> typeCst = this.typeCst;
try {
return (Optional<T>) Optional.of(typeCst.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
logger.error("error creating an object", e);
}
return Optional.empty();
private Class<? extends CustomerRole> typeCst;
Role(Class<? extends CustomerRole> typeCst) {
this.typeCst = typeCst;
}
private static final Logger logger = LoggerFactory.getLogger(Role.class);
/**
* Get instance.
*/
@SuppressWarnings("unchecked")
public <T extends CustomerRole> Optional<T> instance() {
Class<? extends CustomerRole> typeCst = this.typeCst;
try {
return (Optional<T>) Optional.of(typeCst.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
logger.error("error creating an object", e);
}
return Optional.empty();
}
}