diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000000..0155bcdcd2b3 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [iluwatar] diff --git a/.gitignore b/.gitignore index fd0bb7810faf..ada1e7d10ce5 100644 --- a/.gitignore +++ b/.gitignore @@ -16,5 +16,4 @@ datanucleus.log /bin/ /bin/ *.log -data-mapper/src/main/resources/log4j.xml event-sourcing/Journal.json diff --git a/.sonarcloud.properties b/.sonarcloud.properties deleted file mode 100644 index 1bd690065c42..000000000000 --- a/.sonarcloud.properties +++ /dev/null @@ -1,38 +0,0 @@ -# -# The MIT License -# Copyright (c) 2014 Ilkka Seppälä -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# - -# Path to sources -#sonar.sources=. -#sonar.exclusions= -#sonar.inclusions= - -# Path to tests -#sonar.tests= -#sonar.test.exclusions= -#sonar.test.inclusions= - -# Source encoding -#sonar.sourceEncoding=UTF-8 - -# Exclusions for copy-paste detection -#sonar.cpd.exclusions= diff --git a/.travis.yml b/.travis.yml index 58edddeb416e..0a5ac7709f2a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,31 +1,29 @@ language: java -dist: trusty # Xenial build environment won't allow installation of Java 8 +dist: bionic jdk: -- oraclejdk8 +- openjdk11 +sudo: required env: global: - - GH_REF: github.com/iluwatar/java-design-patterns.git - - secure: LxTDuNS/rBWIvKkaEqr79ImZAe48mCdoYCF41coxNXgNoippo4GIBArknqtv+XvdkiuRZ1yGyj6pn8GU33c/yn+krddTUkVCwTbVatbalW5jhQjDbHYym/JcxaK9ZS/3JTeGcWrBgiPqHEEDhCf26vPZsXoMSeVCEORVKTp1BSg= - - secure: "eoWlW9GyTJY04P8K3pxayXwU9/hmptQg/LfirispQkV9YvmziCfSzXnatnBhNfud98sCzY8BScXnb+OWLTnjLKpId4rtEqb0aJ40Jc32cUKzgzFAUn7cNcDAbUIfyPAGVqyQqfj/11wYSADwWMMOPlW97ExUtoyiH2WenXuRHso=" - -before_install: -- export DISPLAY=:99.0 -- sh -e /etc/init.d/xvfb start - -# default install command is just "mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V" -install: -- mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -e + - secure: "DCpazS3nkLnter3sguXEAS2fC/1ZWNfM+XLyif9MfNFxlZdpni2vCD/jA0Rdpga8puQWHNVLyAec+RPFH/2qSmJ1c1UTV5MaLv8tPqwUX0VFA+1I6XoSv6oX4ldHTBWHEWqQHkRFOLoil0h0edc0tTOWQwXF8U+DLAB+HkRb4gw=" -after_success: -- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=$SONAR_TOKEN -- bash update-ghpages.sh +services: +- xvfb -# use latest java version available instead of travis default addons: - apt: - packages: - - oracle-java8-installer + sonarcloud: + organization: "iluwatar" + token: + secure: "FpHwMYPMkdWU6CeIB7+O3qIeIM4vJMp47UjkKK53f0w0s6tPZofZZkab+gcL2TqKSil7sFVB/AQXU1cUubflRszwcLbNsc8H2yFehD79o0o0Mqd1Dd5ip/q0KQbHkkln+InFlVLfvrLB4Xd4mlQVxbGhqpULBhXjKzFzQlRFcuU=" +script: + # Because of Travis security restrictions, SonarCloud analysis cannot be run on pull requests originated from forks + # See https://docs.travis-ci.com/user/pull-requests/#pull-requests-and-security-restrictions + - 'if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then mvn clean verify; fi' + - 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then mvn clean verify sonar:sonar -Dsonar.projectKey=iluwatar_java-design-patterns -Dsonar.host.url=https://sonarcloud.io; fi' + +after_success: +- bash update-website.sh notifications: email: @@ -36,5 +34,3 @@ notifications: on_success: change # options: [always|never|change] default: always on_failure: always # options: [always|never|change] default: always on_start: never # options: [always|never|change] default: always - -sudo: required diff --git a/CODE_COVERAGE.md b/CODE_COVERAGE.md deleted file mode 100644 index 333ee199f8e0..000000000000 --- a/CODE_COVERAGE.md +++ /dev/null @@ -1,13 +0,0 @@ -# Code Coverage Report generation - -To generate the code coverage report, execute the following command: -> mvn clean verify jacoco:report - -This will generate code coverage report in each of the modules. In order to view the same, open the following file in your browser. -> target/site/jacoco/index.html - -Please note that the above folder is created under each of the modules. For example: -* adapter/target/site/jacoco/index.html -* business-delegate/target/site/jacoco/index.html - - diff --git a/README.md b/README.md index c41a48a8898d..1d8245d5dc7a 100644 --- a/README.md +++ b/README.md @@ -17,14 +17,21 @@ solve common problems when designing an application or system. Design patterns can speed up the development process by providing tested, proven development paradigms. -Reusing design patterns help prevent subtle issues which cause major +Reusing design patterns help prevent subtle issues that cause major problems, and it also improves code readability for coders and architects who are familiar with the patterns. # Getting started +This site showcases Java Design Patterns. The solutions have been developed by +experienced programmers and architects from the open source community. The +patterns can be browsed by their high level descriptions or by looking at their +source code. The source code examples are well commented and can be thought as +programming tutorials how to implement a specific pattern. We use the most +popular battle-proven open source Java technologies. + Before you dive into the material, you should be familiar with various -Programming/Software Design Principles. +software design principles. All designs should be as simple as possible. You should start with KISS, YAGNI, and Do The Simplest Thing That Could Possibly Work principles. Complexity and @@ -35,12 +42,17 @@ Once you are familiar with these concepts you can start drilling down into patterns by any of the following approaches - Using difficulty tags, `Difficulty-Beginner`, `Difficulty-Intermediate` & `Difficulty-Expert`. - - Using pattern categories, `Creational`, `Behavioral` and others. + - Using pattern categories, `Creational`, `Behavioral`, and others. - Search for a specific pattern. Can't find one? Please report a new pattern [here](https://github.com/iluwatar/java-design-patterns/issues). +Hopefully you find the object oriented solutions presented on this site useful +in your architectures and have as much fun learning them as we had developing them. + # How to contribute -If you are willing to contribute to the project you will find the relevant information in our [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). We will help you and answer your questions in the [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns). +If you are willing to contribute to the project you will find the relevant information in +our [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). We will help +you and answer your questions in the [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns). # License diff --git a/abstract-document/pom.xml b/abstract-document/pom.xml index c3f783184d33..ec1bd16dc633 100644 --- a/abstract-document/pom.xml +++ b/abstract-document/pom.xml @@ -2,7 +2,7 @@ - - - - Design Patterns - Abstract Factory Presentation - - - - - - - - - \ No newline at end of file diff --git a/abstract-factory/pom.xml b/abstract-factory/pom.xml index 402297ed9866..7e2613a0402f 100644 --- a/abstract-factory/pom.xml +++ b/abstract-factory/pom.xml @@ -2,7 +2,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/circuit-breaker/README.md b/circuit-breaker/README.md new file mode 100644 index 000000000000..db75ca58c0d0 --- /dev/null +++ b/circuit-breaker/README.md @@ -0,0 +1,188 @@ +--- +layout: pattern +title: CircuitBreaker +folder: circuit-breaker +permalink: /patterns/circuit-breaker/ +categories: Other +tags: + - Java + - Performance + - Difficulty-Intermediate +--- + +## Intent + +Handle costly remote *procedure/service* calls in such a way that the failure of a **single** service/component cannot bring the whole application down, and we can reconnect to the service as soon as possible. + +## Explanation + +Real world example + +> Imagine a Web App that has both local (example: files and images) and remote (example: database entries) to serve. The database might not be responding due to a variety of reasons, so if the application keeps trying to read from the database using multiple threads/processes, soon all of them will hang and our entire web application will crash. We should be able to detect this situation and show the user an appropriate message so that he/she can explore other parts of the app unaffected by the database failure without any problem. + +In plain words + +> Allows us to save resources when we know a remote service failed. Useful when all parts of our application are highly decoupled from each other, and failure of one component doesn't mean the other parts will stop working. + +Wikipedia says + +> **Circuit breaker** is a design pattern used in modern software development. It is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties. + +So, how does this all come together? + +## Programmatic Example +With the above example in mind we will imitate the functionality in a simple manner. We have two services: A *monitoring service* which will mimic the web app and will make both **local** and **remote** calls. + +The service architecture is as follows: + +![alt text](./etc/ServiceDiagram.PNG "Service Diagram") + +In terms of code, the End user application is: + +```java +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + public static void main(String[] args) { + var obj = new MonitoringService(); + var circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); + var serverStartTime = System.nanoTime(); + while (true) { + LOGGER.info(obj.localResourceResponse()); + LOGGER.info(obj.remoteResourceResponse(circuitBreaker, serverStartTime)); + LOGGER.info(circuitBreaker.getState()); + try { + Thread.sleep(5 * 1000); + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + } + } + } +} +``` + +The monitoring service is: + +``` java +public class MonitoringService { + + public String localResourceResponse() { + return "Local Service is working"; + } + + public String remoteResourceResponse(CircuitBreaker circuitBreaker, long serverStartTime) { + try { + return circuitBreaker.call("delayedService", serverStartTime); + } catch (Exception e) { + return e.getMessage(); + } + } +} +``` +As it can be seen, it does the call to get local resources directly, but it wraps the call to remote (costly) service in a circuit breaker object, which prevents faults as follows: + +```java +public class CircuitBreaker { + private final long timeout; + private final long retryTimePeriod; + long lastFailureTime; + int failureCount; + private final int failureThreshold; + private State state; + private final long futureTime = 1000 * 1000 * 1000 * 1000; + + CircuitBreaker(long timeout, int failureThreshold, long retryTimePeriod) { + this.state = State.CLOSED; + this.failureThreshold = failureThreshold; + this.timeout = timeout; + this.retryTimePeriod = retryTimePeriod; + this.lastFailureTime = System.nanoTime() + futureTime; + this.failureCount = 0; + } + + private void reset() { + this.failureCount = 0; + this.lastFailureTime = System.nanoTime() + futureTime; + this.state = State.CLOSED; + } + + private void recordFailure() { + failureCount = failureCount + 1; + this.lastFailureTime = System.nanoTime(); + } + + protected void setState() { + if (failureCount > failureThreshold) { + if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { + state = State.HALF_OPEN; + } else { + state = State.OPEN; + } + } else { + state = State.CLOSED; + } + } + + public String getState() { + return state.name(); + } + + public void setStateForBypass(State state) { + this.state = state; + } + + public String call(String serviceToCall, long serverStartTime) throws Exception { + setState(); + if (state == State.OPEN) { + return "This is stale response from API"; + } else { + if (serviceToCall.equals("delayedService")) { + var delayedService = new DelayedService(20); + var response = delayedService.response(serverStartTime); + if (response.split(" ")[3].equals("working")) { + reset(); + return response; + } else { + recordFailure(); + throw new Exception("Remote service not responding"); + } + } else { + throw new Exception("Unknown Service Name"); + } + } + } +} +``` + +How does the above pattern prevent failures? Let's understand via this finite state machine implemented by it. + +![alt text](./etc/StateDiagram.PNG "State Diagram") + +- We initialize the Circuit Breaker object with certain parameters: **timeout**, **failureThreshold** and **retryTimePeriod** which help determine how resilient the API is. +- Initially, we are in the **closed** state and the remote call to API happens. +- Every time the call succeeds, we reset the state to as it was in the beginning. +- If the number of failures cross a certain threshold, we move to the **open** state, which acts just like an open circuit and prevents remote service calls from being made, thus saving resources. (Here, we return the response called ```stale response from API```) +- Once we exceed the retry timeout period, we move to the **half-open** state and make another call to the remote service again to check if the service is working so that we can serve fresh content. A *failure* sets it back to **open** state and another attempt is made after retry timeout period, while a *success* sets it to **closed** state so that everything starts working normally again. + + +## Applicability +Use the Circuit Breaker pattern when + +- Building a fault-tolerant application where failure of some services shouldn't bring the entire application down. +- Building an continuously incremental/continuous delivery application, as some of it's components can be upgraded without shutting it down entirely. + +## Related Patterns + +- [Retry Pattern](https://github.com/iluwatar/java-design-patterns/tree/master/retry) + +## Real world examples +* [Spring Circuit Breaker module](https://spring.io/guides/gs/circuit-breaker) +* [Netflix Hystrix API](https://github.com/Netflix/Hystrix) + +## Credits + +* [Understanding Circuit Breaker Pattern](https://itnext.io/understand-circuitbreaker-design-pattern-with-simple-practical-example-92a752615b42) +* [Martin Fowler on Circuit Breaker](https://martinfowler.com/bliki/CircuitBreaker.html) +* [Fault tolerance in a high volume, distributed system](https://medium.com/netflix-techblog/fault-tolerance-in-a-high-volume-distributed-system-91ab4faae74a) +* [Microsoft docs](https://docs.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker) diff --git a/circuit-breaker/etc/ServiceDiagram.PNG b/circuit-breaker/etc/ServiceDiagram.PNG new file mode 100644 index 000000000000..661f1a105818 Binary files /dev/null and b/circuit-breaker/etc/ServiceDiagram.PNG differ diff --git a/circuit-breaker/etc/StateDiagram.PNG b/circuit-breaker/etc/StateDiagram.PNG new file mode 100644 index 000000000000..38485526d342 Binary files /dev/null and b/circuit-breaker/etc/StateDiagram.PNG differ diff --git a/dao/src/main/resources/log4j.xml b/circuit-breaker/pom.xml similarity index 60% rename from dao/src/main/resources/log4j.xml rename to circuit-breaker/pom.xml index 14f043ff7576..6ef7da2236a2 100644 --- a/dao/src/main/resources/log4j.xml +++ b/circuit-breaker/pom.xml @@ -1,8 +1,7 @@ - - - - - - - - - - - - - - - - \ No newline at end of file + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.22.0-SNAPSHOT + + circuit-breaker + + + org.junit.jupiter + junit-jupiter-engine + test + + + diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java new file mode 100644 index 000000000000..054158e9b6ae --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java @@ -0,0 +1,87 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + *

+ * The intention of the Circuit Builder pattern is to handle remote failures + * robustly, which is to mean that if a service is dependant on n number of + * other services, and m of them fail, we should be able to recover from that + * failure by ensuring that the user can still use the services that are actually + * functional, and resources are not tied up by uselessly by the services which + * are not working. However, we should also be able to detect when any of the m + * failing services become operational again, so that we can use it + *

+ *

+ * In this example, the circuit breaker pattern is demonstrated by using two services: + * {@link MonitoringService} and {@link DelayedService}. The monitoring service + * is responsible for calling two services: a local service and a remote service {@link DelayedService} + * , and by using the circuit breaker construction we ensure that if the call to + * remote service is going to fail, we are going to save our resources and not make the + * function call at all, by wrapping our call to the remote service in the circuit + * breaker object. + *

+ *

+ * This works as follows: The {@link CircuitBreaker} object can be in one of three + * states: Open, Closed and Half-Open, which represents the real + * world circuits. If the state is closed (initial), we assume everything is alright + * and perform the function call. However, every time the call fails, we note it + * and once it crosses a threshold, we set the state to Open, preventing any further + * calls to the remote server. Then, after a certain retry period (during which we + * expect thee service to recover), we make another call to the remote server and + * this state is called the Half-Open state, where it stays till the service is down, + * and once it recovers, it goes back to the closed state and the cycle continues. + *

+ */ +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** + * Program entry point + * + * @param args command line args + */ + @SuppressWarnings("squid:S2189") + public static void main(String[] args) { + //Create an object of monitoring service which makes both local and remote calls + var obj = new MonitoringService(); + //Set the circuit Breaker parameters + var circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); + var serverStartTime = System.nanoTime(); + while (true) { + LOGGER.info(obj.localResourceResponse()); + LOGGER.info(obj.remoteResourceResponse(circuitBreaker, serverStartTime)); + LOGGER.info(circuitBreaker.getState()); + try { + Thread.sleep(5 * 1000); + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + } + } + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java new file mode 100644 index 000000000000..005a000dff49 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java @@ -0,0 +1,128 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +/** + * The circuit breaker class with all configurations + */ +public class CircuitBreaker { + private final long timeout; + private final long retryTimePeriod; + long lastFailureTime; + int failureCount; + private final int failureThreshold; + private State state; + private final long futureTime = 1000 * 1000 * 1000 * 1000; + + /** + * Constructor to create an instance of Circuit Breaker + * @param timeout Timeout for the API request. Not necessary for this simple example + * @param failureThreshold Number of failures we receive from the depended service before changing state to 'OPEN' + * @param retryTimePeriod Time period after which a new request is made to remote service for status check. + */ + CircuitBreaker(long timeout, int failureThreshold, long retryTimePeriod) { + // We start in a closed state hoping that everything is fine + this.state = State.CLOSED; + this.failureThreshold = failureThreshold; + // Timeout for the API request. Used to break the calls made to remote resource if it exceeds the limit + this.timeout = timeout; + this.retryTimePeriod = retryTimePeriod; + //An absurd amount of time in future which basically indicates the last failure never happened + this.lastFailureTime = System.nanoTime() + futureTime; + this.failureCount = 0; + } + + //Reset everything to defaults + private void reset() { + this.failureCount = 0; + this.lastFailureTime = System.nanoTime() + futureTime; + this.state = State.CLOSED; + } + + private void recordFailure() { + failureCount = failureCount + 1; + this.lastFailureTime = System.nanoTime(); + } + + protected void setState() { + if (failureCount > failureThreshold) { //Then something is wrong with remote service + if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { + //We have waited long enough and should try checking if service is up + state = State.HALF_OPEN; + } else { + //Service would still probably be down + state = State.OPEN; + } + } else { + //Everything is working fine + state = State.CLOSED; + } + } + + public String getState() { + return state.name(); + } + + /** + * Break the circuit beforehand if it is known service is down + * Or connect the circuit manually if service comes online before expected + * @param state State at which circuit is in + */ + public void setStateForBypass(State state) { + this.state = state; + } + + /** + * @param serviceToCall The name of the service in String. Can be changed to data URLs in case of web applications + * @param serverStartTime Time at which actual server was started which makes calls to this service + * @return Value from the remote resource, stale response or a custom exception + */ + public String call(String serviceToCall, long serverStartTime) throws Exception { + setState(); + if (state == State.OPEN) { + // return cached response if no the circuit is in OPEN state + return "This is stale response from API"; + } else { + // Make the API request if the circuit is not OPEN + if (serviceToCall.equals("delayedService")) { + var delayedService = new DelayedService(20); + var response = delayedService.response(serverStartTime); + //In a real application, this would be run in a thread and the timeout + //parameter of the circuit breaker would be utilized to know if service + //is working. Here, we simulate that based on server response itself + if (response.split(" ")[3].equals("working")) { + // Yay!! the API responded fine. Let's reset everything. + reset(); + return response; + } else { + // Uh-oh!! the call still failed. Let's update that in our records. + recordFailure(); + throw new Exception("Remote service not responding"); + } + } else { + throw new Exception("Unknown Service Name"); + } + } + } +} \ No newline at end of file diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java new file mode 100644 index 000000000000..b291c3fe5bf3 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java @@ -0,0 +1,62 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +/** +* This simulates the remote service +* It responds only after a certain timeout period (default set to 20 seconds) +*/ +public class DelayedService { + private final int delay; + + /** + * Constructor to create an instance of DelayedService, which is down for first few seconds + * @param delay the delay after which service would behave properly, in seconds + */ + public DelayedService(int delay) { + this.delay = delay; + } + + public DelayedService() { + this.delay = 60; + } + + /** + * @param serverStartTime Time at which actual server was started which makes calls to this service + * @return The state of the service + */ + public String response(long serverStartTime) { + var currentTime = System.nanoTime(); + //Since currentTime and serverStartTime are both in nanoseconds, we convert it to + //seconds by diving by 10e9 and ensure floating point division by multiplying it + //with 1.0 first. We then check if it is greater or less than specified delay and then + //send the reply + if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000) < delay) { + //Can use Thread.sleep() here to block and simulate a hung server + return "Delayed service is down"; + } else { + return "Delayed service is working"; + } + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java new file mode 100644 index 000000000000..f46843766527 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java @@ -0,0 +1,50 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +/** + * The service class which makes local and remote calls + * Uses {@link CircuitBreaker} object to ensure remote calls don't use up resources + */ +public class MonitoringService { + + //Assumption: Local service won't fail, no need to wrap it in a circuit breaker logic + public String localResourceResponse() { + return "Local Service is working"; + } + + /** + * Try to get result from remote server + * @param circuitBreaker The circuitBreaker object with all parameters + * @param serverStartTime Time at which actual server was started which makes calls to this service + * @return result from the remote response or exception raised by it. + */ + public String remoteResourceResponse(CircuitBreaker circuitBreaker, long serverStartTime) { + try { + return circuitBreaker.call("delayedService", serverStartTime); + } catch (Exception e) { + return e.getMessage(); + } + } +} \ No newline at end of file diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java new file mode 100644 index 000000000000..92fe0f2546ef --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java @@ -0,0 +1,33 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +/** + * Enumeration for states the circuit breaker could be in + */ +public enum State { + CLOSED, + OPEN, + HALF_OPEN +} \ No newline at end of file diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/CircuitBreakerTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/CircuitBreakerTest.java new file mode 100644 index 000000000000..f4efcaaacfdb --- /dev/null +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/CircuitBreakerTest.java @@ -0,0 +1,80 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +/** + * + * Circuit Breaker test + * + */ +public class CircuitBreakerTest { + + //long timeout, int failureThreshold, long retryTimePeriod + @Test + public void testSetState() { + var circuitBreaker = new CircuitBreaker(1,1,100); + //Right now, failureCountfailureThreshold, and lastFailureTime is nearly equal to current time, + //state should be half-open + assertEquals(circuitBreaker.getState(), "HALF_OPEN"); + //Since failureCount>failureThreshold, and lastFailureTime is much lesser current time, + //state should be open + circuitBreaker.lastFailureTime = System.nanoTime() - 1000 * 1000 * 1000 * 1000; + circuitBreaker.setState(); + assertEquals(circuitBreaker.getState(), "OPEN"); + //Now set it back again to closed to test idempotency + circuitBreaker.failureCount = 0; + circuitBreaker.setState(); + assertEquals(circuitBreaker.getState(), "CLOSED"); + } + + @Test + public void testSetStateForBypass() { + var circuitBreaker = new CircuitBreaker(1,1,100); + //Right now, failureCount sedansOwnedImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); + + List sedansOwnedImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); LOGGER.info(sedansOwnedImperative.toString()); - List sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); + List sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); LOGGER.info(sedansOwnedFunctional.toString()); } } diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java index e3cb9e11fba1..314728797cfa 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.collectionpipeline; /** diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java index 031853fcab04..aee1e21932df 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.collectionpipeline; -import java.util.Arrays; import java.util.List; /** @@ -37,7 +37,7 @@ private CarFactory() { * @return {@link List} of {@link Car} */ public static List createCars() { - return Arrays.asList(new Car("Jeep", "Wrangler", 2011, Category.JEEP), + return List.of(new Car("Jeep", "Wrangler", 2011, Category.JEEP), new Car("Jeep", "Comanche", 1990, Category.JEEP), new Car("Dodge", "Avenger", 2010, Category.SEDAN), new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java index 456864fdbd22..170d4df33e65 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.collectionpipeline; /** diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java index 3cc24ce44cd1..2a72aa00848a 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.collectionpipeline; import java.util.Comparator; diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java index 7466462cc98c..01d095e96099 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.collectionpipeline; import java.util.ArrayList; diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java index c9114c125a45..9bf01052a667 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.collectionpipeline; import java.util.List; diff --git a/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java index 5a6821641308..6bc035920d88 100644 --- a/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java +++ b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,59 +20,61 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.collectionpipeline; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests that Collection Pipeline methods work as expected. */ public class AppTest { - + private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class); + private List cars = CarFactory.createCars(); @Test public void testGetModelsAfter2000UsingFor() { - List models = ImperativeProgramming.getModelsAfter2000(cars); - assertEquals(Arrays.asList("Avenger", "Wrangler", "Focus", "Cascada"), models); + var models = ImperativeProgramming.getModelsAfter2000(cars); + assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models); } @Test public void testGetModelsAfter2000UsingPipeline() { - List models = FunctionalProgramming.getModelsAfter2000(cars); - assertEquals(Arrays.asList("Avenger", "Wrangler", "Focus", "Cascada"), models); + var models = FunctionalProgramming.getModelsAfter2000(cars); + assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models); } @Test public void testGetGroupingOfCarsByCategory() { - Map> modelsExpected = new HashMap<>(); - modelsExpected.put(Category.CONVERTIBLE, Arrays.asList(new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), - new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE))); - modelsExpected.put(Category.SEDAN, Arrays.asList(new Car("Dodge", "Avenger", 2010, Category.SEDAN), - new Car("Ford", "Focus", 2012, Category.SEDAN))); - modelsExpected.put(Category.JEEP, Arrays.asList(new Car("Jeep", "Wrangler", 2011, Category.JEEP), - new Car("Jeep", "Comanche", 1990, Category.JEEP))); - Map> modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); - Map> modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); - System.out.println("Category " + modelsFunctional); + var modelsExpected = Map.of( + Category.CONVERTIBLE, List.of(new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), + new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)), + Category.SEDAN, List.of(new Car("Dodge", "Avenger", 2010, Category.SEDAN), + new Car("Ford", "Focus", 2012, Category.SEDAN)), + Category.JEEP, List.of(new Car("Jeep", "Wrangler", 2011, Category.JEEP), + new Car("Jeep", "Comanche", 1990, Category.JEEP))); + var modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); + var modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); + LOGGER.info("Category " + modelsFunctional); assertEquals(modelsExpected, modelsFunctional); assertEquals(modelsExpected, modelsImperative); } @Test public void testGetSedanCarsOwnedSortedByDate() { - Person john = new Person(cars); - List modelsExpected = Arrays.asList(new Car("Dodge", "Avenger", 2010, Category.SEDAN), + var john = new Person(cars); + var modelsExpected = List.of(new Car("Dodge", "Avenger", 2010, Category.SEDAN), new Car("Ford", "Focus", 2012, Category.SEDAN)); - List modelsFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); - List modelsImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); + var modelsFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); + var modelsImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); assertEquals(modelsExpected, modelsFunctional); assertEquals(modelsExpected, modelsImperative); } diff --git a/command/README.md b/command/README.md index cb9bd48a9608..41e8b78e1aaa 100644 --- a/command/README.md +++ b/command/README.md @@ -36,10 +36,6 @@ Use the Command pattern when you want to * implement callback functionality * implement the undo functionality -## Presentations - -* [Command Pattern](etc/presentation.html) - ## Real world examples * [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) diff --git a/command/etc/diagram.png b/command/etc/diagram.png deleted file mode 100644 index 1d3494292b82..000000000000 Binary files a/command/etc/diagram.png and /dev/null differ diff --git a/command/etc/presentation.html b/command/etc/presentation.html deleted file mode 100644 index 6a2ce7471cca..000000000000 --- a/command/etc/presentation.html +++ /dev/null @@ -1,243 +0,0 @@ - - - - - Design Patterns - Command Presentation - - - - - - - - - \ No newline at end of file diff --git a/command/pom.xml b/command/pom.xml index dc4f5edb92a0..d9fbd90d091d 100644 --- a/command/pom.xml +++ b/command/pom.xml @@ -2,7 +2,7 @@ + @@ -38,5 +47,18 @@ org.hibernate hibernate-core + + com.sun.xml.bind + jaxb-impl + 2.1.17 + test + + + javax.xml.bind + jaxb-api + test + + + diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java b/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java index 0f766e5c727f..0a805679f2b8 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.app; import java.math.BigInteger; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java index a15f8a45716d..e491e8990a7a 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.commandes; import org.hibernate.Query; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java index 1da3f6c42392..7e0a47bc3150 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.commandes; /** diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java b/cqrs/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java index 07a8b96190b3..c52a71401205 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.constants; /** diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java index 9825de9f7b25..0c0d4b65b285 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.domain.model; import javax.persistence.Entity; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java index 8a11fcdd4166..0524991f80a6 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.domain.model; import javax.persistence.Entity; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java index c5473354dd59..f20627ba9dea 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.dto; import java.util.Objects; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java index f121a2ca7c2c..47ee03581020 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.dto; import java.util.Objects; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java b/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java index 9c0252b0aeab..303b69e7c322 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.queries; import java.math.BigInteger; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java b/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java index 86eb4dd2f351..57895c945436 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.queries; import java.math.BigInteger; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java b/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java index a5b59e20dc27..7737ded33e9d 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.cqrs.util; import org.hibernate.SessionFactory; diff --git a/cqrs/src/main/resources/hibernate.cfg.xml b/cqrs/src/main/resources/hibernate.cfg.xml index 4ea1421667e1..019cd3917c84 100644 --- a/cqrs/src/main/resources/hibernate.cfg.xml +++ b/cqrs/src/main/resources/hibernate.cfg.xml @@ -2,7 +2,7 @@ - - - - src/main/resources - - - src/main/resources - - log4j.xml - - .. - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 - - - log4j.xml - - - - true - - - - - - - diff --git a/dao/src/main/java/com/iluwatar/dao/App.java b/dao/src/main/java/com/iluwatar/dao/App.java index b5e70f257ebb..78406208a77e 100644 --- a/dao/src/main/java/com/iluwatar/dao/App.java +++ b/dao/src/main/java/com/iluwatar/dao/App.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -32,8 +32,9 @@ import javax.sql.DataSource; -import org.apache.log4j.Logger; import org.h2.jdbcx.JdbcDataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Data Access Object (DAO) is an object that provides an abstract interface to some type of @@ -51,7 +52,7 @@ */ public class App { private static final String DB_URL = "jdbc:h2:~/dao"; - private static Logger log = Logger.getLogger(App.class); + private static Logger log = LoggerFactory.getLogger(App.class); private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): "; /** @@ -95,7 +96,7 @@ private static void performOperationsUsing(final CustomerDao customerDao) throws addCustomers(customerDao); log.info(ALL_CUSTOMERS); try (Stream customerStream = customerDao.getAll()) { - customerStream.forEach((customer) -> log.info(customer)); + customerStream.forEach((customer) -> log.info(customer.toString())); } log.info("customerDao.getCustomerById(2): " + customerDao.getById(2)); final Customer customer = new Customer(4, "Dan", "Danson"); @@ -106,7 +107,7 @@ private static void performOperationsUsing(final CustomerDao customerDao) throws customerDao.update(customer); log.info(ALL_CUSTOMERS); try (Stream customerStream = customerDao.getAll()) { - customerStream.forEach((cust) -> log.info(cust)); + customerStream.forEach((cust) -> log.info(cust.toString())); } customerDao.delete(customer); log.info(ALL_CUSTOMERS + customerDao.getAll()); @@ -127,10 +128,6 @@ public static List generateSampleCustomers() { final Customer customer1 = new Customer(1, "Adam", "Adamson"); final Customer customer2 = new Customer(2, "Bob", "Bobson"); final Customer customer3 = new Customer(3, "Carl", "Carlson"); - final List customers = new ArrayList<>(); - customers.add(customer1); - customers.add(customer2); - customers.add(customer3); - return customers; + return List.of(customer1, customer2, customer3); } } diff --git a/dao/src/main/java/com/iluwatar/dao/CustomException.java b/dao/src/main/java/com/iluwatar/dao/CustomException.java index fd291b605392..3c1ec7373869 100644 --- a/dao/src/main/java/com/iluwatar/dao/CustomException.java +++ b/dao/src/main/java/com/iluwatar/dao/CustomException.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.dao; /** diff --git a/dao/src/main/java/com/iluwatar/dao/Customer.java b/dao/src/main/java/com/iluwatar/dao/Customer.java index a133bf2b0ded..593aacaf359c 100644 --- a/dao/src/main/java/com/iluwatar/dao/Customer.java +++ b/dao/src/main/java/com/iluwatar/dao/Customer.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/dao/src/main/java/com/iluwatar/dao/CustomerDao.java b/dao/src/main/java/com/iluwatar/dao/CustomerDao.java index 6156bb8d7d95..7ff9a8e4e9cd 100644 --- a/dao/src/main/java/com/iluwatar/dao/CustomerDao.java +++ b/dao/src/main/java/com/iluwatar/dao/CustomerDao.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java b/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java index cce967dc8939..f05b9de217f7 100644 --- a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java +++ b/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.dao; /** diff --git a/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java b/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java index fa2e411dab56..12e3acb20ac4 100644 --- a/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java +++ b/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,6 +23,9 @@ package com.iluwatar.dao; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -36,15 +39,13 @@ import javax.sql.DataSource; -import org.apache.log4j.Logger; - /** * An implementation of {@link CustomerDao} that persists customers in RDBMS. * */ public class DbCustomerDao implements CustomerDao { - private static final Logger LOGGER = Logger.getLogger(DbCustomerDao.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DbCustomerDao.class); private final DataSource dataSource; diff --git a/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java b/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java index 947da23ca4a0..b6621ba392da 100644 --- a/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java +++ b/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/dao/src/test/java/com/iluwatar/dao/AppTest.java b/dao/src/test/java/com/iluwatar/dao/AppTest.java index 75ef59f18463..d15aceae246a 100644 --- a/dao/src/test/java/com/iluwatar/dao/AppTest.java +++ b/dao/src/test/java/com/iluwatar/dao/AppTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/dao/src/test/java/com/iluwatar/dao/CustomerTest.java b/dao/src/test/java/com/iluwatar/dao/CustomerTest.java index 6bc8689fd87d..c27905353d47 100644 --- a/dao/src/test/java/com/iluwatar/dao/CustomerTest.java +++ b/dao/src/test/java/com/iluwatar/dao/CustomerTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java index 23caf14ec28e..b7c0e5508bdd 100644 --- a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java +++ b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.dao; import org.h2.jdbcx.JdbcDataSource; diff --git a/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java index 0aa86576b1b2..e863324376ea 100644 --- a/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java +++ b/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/data-bus/pom.xml b/data-bus/pom.xml index e5a2946951aa..230fe6b84bde 100644 --- a/data-bus/pom.xml +++ b/data-bus/pom.xml @@ -2,7 +2,7 @@ - diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/App.java b/delegation/src/main/java/com/iluwatar/delegation/simple/App.java index 83e00fd1fb1c..af734bb41449 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/App.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/App.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.delegation.simple; import com.iluwatar.delegation.simple.printers.CanonPrinter; diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java b/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java index ee4d54938a86..bc6f50879798 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.delegation.simple; import com.iluwatar.delegation.simple.printers.CanonPrinter; diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java b/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java index c54f611ee213..315b6ee585a3 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.delegation.simple; /** diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java index 8f024122f15f..9188fc988509 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java index fb763d21a862..a29c0b224644 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java index d80bb7aa7c9f..cb0a8068d9ce 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; diff --git a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java index ffdc96b807bd..21040577e9ba 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.delegation.simple; import org.junit.jupiter.api.Test; diff --git a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java index 422da5685ffc..4c924a794f02 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.delegation.simple; import ch.qos.logback.classic.Logger; diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index 2347cb14f946..fd9584ed2ac8 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -2,7 +2,7 @@ + + + java-design-patterns + com.iluwatar + 1.22.0-SNAPSHOT + + 4.0.0 + + double-buffer + + + + junit + junit + + + org.apache.commons + commons-lang3 + + + + \ No newline at end of file diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java new file mode 100644 index 000000000000..2e69e6eb4e98 --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java @@ -0,0 +1,85 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.doublebuffer; + +import org.apache.commons.lang3.tuple.MutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * Double buffering is a term used to describe a device that has two buffers. + * The usage of multiple buffers increases the overall throughput of a device + * and helps prevents bottlenecks. This example shows using double buffer pattern + * on graphics. It is used to show one image or frame while a separate frame + * is being buffered to be shown next. This method makes animations and games + * look more realistic than the same done in a single buffer mode. + */ +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** + * Program main entry point. + * @param args runtime arguments + */ + public static void main(String[] args) { + var scene = new Scene(); + List> drawPixels = new ArrayList<>(); + Pair pixel1 = new MutablePair<>(1, 1); + Pair pixel2 = new MutablePair<>(5, 6); + Pair pixel3 = new MutablePair<>(3, 2); + drawPixels.add(pixel1); + drawPixels.add(pixel2); + drawPixels.add(pixel3); + scene.draw(drawPixels); + var buffer1 = scene.getBuffer(); + printBlackPixelCoordinate(buffer1); + + drawPixels.clear(); + Pair pixel4 = new MutablePair<>(3, 7); + Pair pixel5 = new MutablePair<>(6, 1); + drawPixels.add(pixel4); + drawPixels.add(pixel5); + scene.draw(drawPixels); + Buffer buffer2 = scene.getBuffer(); + printBlackPixelCoordinate(buffer2); + } + + private static void printBlackPixelCoordinate(Buffer buffer) { + var log = "Black Pixels: "; + Pixel[] pixels = buffer.getPixels(); + for (var i = 0; i < pixels.length; ++i) { + if (pixels[i] == Pixel.BLACK) { + var y = i / FrameBuffer.WIDTH; + var x = i % FrameBuffer.WIDTH; + log += " (" + x + ", " + y + ")"; + } + } + LOGGER.info(log); + } +} diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java new file mode 100644 index 000000000000..b0c7d998b2b5 --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java @@ -0,0 +1,56 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.doublebuffer; + +/** + * Buffer interface. + */ +public interface Buffer { + + /** + * Clear the pixel in (x, y). + * @param x X coordinate + * @param y Y coordinate + */ + void clear(int x, int y); + + /** + * Draw the pixel in (x, y). + * @param x X coordinate + * @param y Y coordinate + */ + void draw(int x, int y); + + /** + * Clear all the pixels. + */ + void clearAll(); + + /** + * Get all the pixels. + * @return pixel list + */ + Pixel[] getPixels(); + +} diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java new file mode 100644 index 000000000000..95925808ba1e --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java @@ -0,0 +1,68 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.doublebuffer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * FrameBuffer implementation class. + */ +public class FrameBuffer implements Buffer { + + public static final int WIDTH = 10; + public static final int HEIGHT = 8; + + private Pixel[] pixels = new Pixel[WIDTH * HEIGHT]; + + public FrameBuffer() { + clearAll(); + } + + @Override + public void clear(int x, int y) { + pixels[getIndex(x, y)] = Pixel.WHITE; + } + + @Override + public void draw(int x, int y) { + pixels[getIndex(x, y)] = Pixel.BLACK; + } + + @Override + public void clearAll() { + for (var i = 0; i < pixels.length; ++i) { + pixels[i] = Pixel.WHITE; + } + } + + @Override + public Pixel[] getPixels() { + return pixels; + } + + private int getIndex(int x, int y) { + return x + WIDTH * y; + } +} diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java new file mode 100644 index 000000000000..501797743e81 --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java @@ -0,0 +1,39 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.doublebuffer; + +/** + * Pixel enum. Each pixel can be white (not drawn) or black (drawn). + */ +public enum Pixel { + + WHITE(0), + BLACK(1); + + private int color; + + Pixel(int color) { + this.color = color; + } +} diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java new file mode 100644 index 000000000000..fe4a63fbfade --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java @@ -0,0 +1,86 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.doublebuffer; + +import org.apache.commons.lang3.tuple.Pair; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +/** + * Scene class. Render the output frame. + */ +public class Scene { + + private static final Logger LOGGER = LoggerFactory.getLogger(Scene.class); + + private Buffer[] frameBuffers; + + private int current; + + private int next; + + /** + * Constructor of Scene. + */ + public Scene() { + frameBuffers = new FrameBuffer[2]; + frameBuffers[0] = new FrameBuffer(); + frameBuffers[1] = new FrameBuffer(); + current = 0; + next = 1; + } + + /** + * Draw the next frame. + * @param coordinateList list of pixels of which the color should be black + */ + public void draw(List> coordinateList) { + LOGGER.info("Start drawing next frame"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + frameBuffers[next].clearAll(); + for (Pair coordinate : coordinateList) { + var x = coordinate.getKey(); + var y = coordinate.getValue(); + frameBuffers[next].draw(x, y); + } + LOGGER.info("Swap current and next buffer"); + swap(); + LOGGER.info("Finish swapping"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + } + + public Buffer getBuffer() { + LOGGER.info("Get current buffer: " + current); + return frameBuffers[current]; + } + + private void swap() { + current = current ^ next; + next = current ^ next; + current = current ^ next; + } + +} diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java new file mode 100644 index 000000000000..6139e6bca786 --- /dev/null +++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java @@ -0,0 +1,39 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.doublebuffer; + +import org.junit.Test; + +/** + * App unit test. + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } + +} diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java new file mode 100644 index 000000000000..3f171d1d65db --- /dev/null +++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java @@ -0,0 +1,97 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.doublebuffer; + +import org.junit.Assert; +import org.junit.Test; + +/** + * FrameBuffer unit test. + */ +public class FrameBufferTest { + + @Test + public void testClearAll() { + try { + var field = FrameBuffer.class.getDeclaredField("pixels"); + Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH]; + for (int i = 0; i < pixels.length; ++i) { + pixels[i] = Pixel.WHITE; + } + pixels[0] = Pixel.BLACK; + var frameBuffer = new FrameBuffer(); + field.setAccessible(true); + field.set(frameBuffer, pixels); + frameBuffer.clearAll(); + Assert.assertEquals(Pixel.WHITE, frameBuffer.getPixels()[0]); + } catch (NoSuchFieldException | IllegalAccessException e) { + Assert.fail("Fail to modify field access."); + } + } + + @Test + public void testClear() { + try { + var field = FrameBuffer.class.getDeclaredField("pixels"); + Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH]; + for (int i = 0; i < pixels.length; ++i) { + pixels[i] = Pixel.WHITE; + } + pixels[0] = Pixel.BLACK; + var frameBuffer = new FrameBuffer(); + field.setAccessible(true); + field.set(frameBuffer, pixels); + frameBuffer.clear(0, 0); + Assert.assertEquals(Pixel.WHITE, frameBuffer.getPixels()[0]); + } catch (NoSuchFieldException | IllegalAccessException e) { + Assert.fail("Fail to modify field access."); + } + } + + @Test + public void testDraw() { + var frameBuffer = new FrameBuffer(); + frameBuffer.draw(0, 0); + Assert.assertEquals(Pixel.BLACK, frameBuffer.getPixels()[0]); + } + + @Test + public void testGetPixels() { + try { + var field = FrameBuffer.class.getDeclaredField("pixels"); + Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH]; + for (int i = 0; i < pixels.length; ++i) { + pixels[i] = Pixel.WHITE; + } + pixels[0] = Pixel.BLACK; + var frameBuffer = new FrameBuffer(); + field.setAccessible(true); + field.set(frameBuffer, pixels); + Assert.assertEquals(pixels, frameBuffer.getPixels()); + } catch (NoSuchFieldException | IllegalAccessException e) { + Assert.fail("Fail to modify field access."); + } + } + +} diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java new file mode 100644 index 000000000000..bd1dd44d06dd --- /dev/null +++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java @@ -0,0 +1,74 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.doublebuffer; + +import org.junit.Assert; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; + +/** + * Scene unit tests. + */ +public class SceneTest { + + @Test + public void testGetBuffer() { + try { + var scene = new Scene(); + var field1 = Scene.class.getDeclaredField("current"); + field1.setAccessible(true); + field1.set(scene, 0); + FrameBuffer[] frameBuffers = new FrameBuffer[2]; + FrameBuffer frameBuffer = new FrameBuffer(); + frameBuffer.draw(0, 0); + frameBuffers[0] = frameBuffer; + var field2 = Scene.class.getDeclaredField("frameBuffers"); + field2.setAccessible(true); + field2.set(scene, frameBuffers); + Assert.assertEquals(frameBuffer, scene.getBuffer()); + } catch (NoSuchFieldException | IllegalAccessException e) { + Assert.fail("Fail to access private field."); + } + } + + @Test + public void testDraw() { + try { + var scene = new Scene(); + var field1 = Scene.class.getDeclaredField("current"); + var field2 = Scene.class.getDeclaredField("next"); + field1.setAccessible(true); + field1.set(scene, 0); + field2.setAccessible(true); + field2.set(scene, 1); + scene.draw(new ArrayList<>()); + Assert.assertEquals(1, field1.get(scene)); + Assert.assertEquals(0, field2.get(scene)); + } catch (NoSuchFieldException | IllegalAccessException e) { + Assert.fail("Fail to access private field"); + } + } +} diff --git a/double-checked-locking/pom.xml b/double-checked-locking/pom.xml index 4db5d6fe63bd..02b03b7733f4 100644 --- a/double-checked-locking/pom.xml +++ b/double-checked-locking/pom.xml @@ -1,7 +1,7 @@ org.apache.camel camel-core - ${camel.version} @@ -47,6 +51,15 @@ ${camel.version} + + com.sun.xml.bind + jaxb-impl + + + javax.xml.bind + jaxb-api + + com.github.sbrannen @@ -70,4 +83,5 @@ + diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java index d55f24e3ddad..f8fec8121b37 100644 --- a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java +++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.aggregator; import org.apache.camel.CamelContext; diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java index 5f130ff69159..652ddbb199c1 100644 --- a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java +++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.aggregator.routes; import org.apache.camel.builder.RouteBuilder; diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java index 4b5e4cb2f501..f8f2822a9dd6 100644 --- a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java +++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.aggregator.routes; import org.apache.camel.Exchange; diff --git a/eip-aggregator/src/main/resources/application.properties b/eip-aggregator/src/main/resources/application.properties index 044833fc1be1..34febce1a9c8 100644 --- a/eip-aggregator/src/main/resources/application.properties +++ b/eip-aggregator/src/main/resources/application.properties @@ -1,6 +1,6 @@ # # The MIT License -# Copyright (c) 2014 Ilkka Seppälä +# Copyright © 2014-2019 Ilkka Seppälä # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java index 40a33678670f..1dc0311a0c71 100644 --- a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java +++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.aggregator; import org.junit.jupiter.api.Test; diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java index 2c7d207d6f53..ff83321964f9 100644 --- a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java +++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.aggregator.routes; import org.apache.camel.EndpointInject; @@ -28,7 +29,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @@ -44,7 +45,7 @@ *

*/ @ExtendWith(SpringExtension.class) -@SpringApplicationConfiguration(classes = AggregatorRouteTest.class) +@SpringBootTest(classes = AggregatorRouteTest.class) @ActiveProfiles("test") @EnableAutoConfiguration @ComponentScan diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java index 7a7a15154677..69862faf1fe9 100644 --- a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java +++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.aggregator.routes; import org.apache.camel.CamelContext; diff --git a/eip-aggregator/src/test/resources/application-test.properties b/eip-aggregator/src/test/resources/application-test.properties index 8d6ecbbd3bf2..0cab1156b7fd 100644 --- a/eip-aggregator/src/test/resources/application-test.properties +++ b/eip-aggregator/src/test/resources/application-test.properties @@ -1,6 +1,6 @@ # # The MIT License -# Copyright (c) 2014 Ilkka Seppälä +# Copyright © 2014-2019 Ilkka Seppälä # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal diff --git a/eip-message-channel/pom.xml b/eip-message-channel/pom.xml index 9d91b7ead49d..5e72da9ef32e 100644 --- a/eip-message-channel/pom.xml +++ b/eip-message-channel/pom.xml @@ -2,7 +2,7 @@ org.apache.camel camel-core - ${camel.version} @@ -47,6 +51,16 @@ ${camel.version} + + com.sun.xml.bind + jaxb-impl + + + javax.xml.bind + jaxb-api + + + com.github.sbrannen @@ -70,4 +84,5 @@ + diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java index ceadb5f8dc0e..e2df6f7e9254 100644 --- a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java +++ b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.splitter; import org.apache.camel.CamelContext; diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java index f7eb28deaf11..1efd8401c26b 100644 --- a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java +++ b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.splitter.routes; import org.apache.camel.builder.RouteBuilder; diff --git a/eip-splitter/src/main/resources/application.properties b/eip-splitter/src/main/resources/application.properties index 044833fc1be1..34febce1a9c8 100644 --- a/eip-splitter/src/main/resources/application.properties +++ b/eip-splitter/src/main/resources/application.properties @@ -1,6 +1,6 @@ # # The MIT License -# Copyright (c) 2014 Ilkka Seppälä +# Copyright © 2014-2019 Ilkka Seppälä # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java index fe3eca01e2db..4f8088c6d3a8 100644 --- a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java +++ b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.splitter; import org.junit.jupiter.api.Test; diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java index 9257a4410186..3c8bdac91f0d 100644 --- a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java +++ b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.splitter.routes; import org.apache.camel.EndpointInject; @@ -28,7 +29,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @@ -42,7 +43,7 @@ *

*/ @ExtendWith(SpringExtension.class) -@SpringApplicationConfiguration(classes = SplitterRouteTest.class) +@SpringBootTest(classes = SplitterRouteTest.class) @ActiveProfiles("test") @EnableAutoConfiguration @ComponentScan diff --git a/eip-splitter/src/test/resources/application-test.properties b/eip-splitter/src/test/resources/application-test.properties index 8d6ecbbd3bf2..0cab1156b7fd 100644 --- a/eip-splitter/src/test/resources/application-test.properties +++ b/eip-splitter/src/test/resources/application-test.properties @@ -1,6 +1,6 @@ # # The MIT License -# Copyright (c) 2014 Ilkka Seppälä +# Copyright © 2014-2019 Ilkka Seppälä # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index efca8d3c4cfb..ae896f0d0399 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -1,15 +1,19 @@ org.apache.camel camel-core - ${camel.version} @@ -47,6 +51,16 @@ ${camel.version} + + com.sun.xml.bind + jaxb-impl + + + javax.xml.bind + jaxb-api + + + com.github.sbrannen @@ -70,4 +84,5 @@ + diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java index ca605cb78171..5db2e88281b3 100644 --- a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java +++ b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.wiretap; import org.apache.camel.CamelContext; diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java index 994ceacdb6bc..4cb91e162c8e 100644 --- a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java +++ b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.wiretap.routes; import org.apache.camel.builder.RouteBuilder; diff --git a/eip-wire-tap/src/main/resources/application.properties b/eip-wire-tap/src/main/resources/application.properties index 90a152425a4e..13e13b959fd2 100644 --- a/eip-wire-tap/src/main/resources/application.properties +++ b/eip-wire-tap/src/main/resources/application.properties @@ -1,6 +1,6 @@ # # The MIT License -# Copyright (c) 2014 Ilkka Seppälä +# Copyright © 2014-2019 Ilkka Seppälä # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java index 673803df706b..fe2a01acbd5f 100644 --- a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java +++ b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.wiretap; import org.junit.jupiter.api.Test; diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java index 449f86208258..d134c53e5e16 100644 --- a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java +++ b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.eip.wiretap.routes; import org.apache.camel.EndpointInject; @@ -29,7 +30,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @@ -45,7 +46,7 @@ *

*/ @ExtendWith(SpringExtension.class) -@SpringApplicationConfiguration(classes = WireTapRouteTest.class) +@SpringBootTest(classes = WireTapRouteTest.class) @ActiveProfiles("test") @EnableAutoConfiguration @ComponentScan diff --git a/eip-wire-tap/src/test/resources/application-test.properties b/eip-wire-tap/src/test/resources/application-test.properties index e76faa1fc864..a64f4b316700 100644 --- a/eip-wire-tap/src/test/resources/application-test.properties +++ b/eip-wire-tap/src/test/resources/application-test.properties @@ -1,6 +1,6 @@ # # The MIT License -# Copyright (c) 2014 Ilkka Seppälä +# Copyright © 2014-2019 Ilkka Seppälä # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal diff --git a/event-aggregator/pom.xml b/event-aggregator/pom.xml index 2e9f4d9a97fb..191eaed043e0 100644 --- a/event-aggregator/pom.xml +++ b/event-aggregator/pom.xml @@ -1,7 +1,7 @@ - - - - Design Patterns - Factory Method Presentation - - - - - - - - - \ No newline at end of file diff --git a/factory-method/pom.xml b/factory-method/pom.xml index cc4d21d1a4c8..f4ca2cd5048b 100644 --- a/factory-method/pom.xml +++ b/factory-method/pom.xml @@ -2,7 +2,7 @@ - diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java index 351936b2cd64..07d13423a96e 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

+ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

+ * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java index 284ccf2ab2cb..ee2360b9850b 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

+ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

+ * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.featuretoggle.pattern; import com.iluwatar.featuretoggle.user.User; diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java index 1ded334ec7d7..0696cf487ed6 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

+ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

+ * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.featuretoggle.pattern.propertiesversion; import com.iluwatar.featuretoggle.pattern.Service; diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java index 887c9f663bfe..9f50d280a162 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

+ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

+ * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.featuretoggle.pattern.tieredversion; import com.iluwatar.featuretoggle.pattern.Service; diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java index baf25aa8b7d6..263d5ce92fd2 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

+ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

+ * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.featuretoggle.user; /** diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java index cb84ec533274..40325041b7ef 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

+ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

+ * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.featuretoggle.user; import java.util.ArrayList; diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java index 8b85e93496ae..0bab8bca4ba2 100644 --- a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java +++ b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

+ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

+ * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java index 4755d569e09e..1d161c741a74 100644 --- a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java +++ b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

+ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

+ * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.featuretoggle.pattern.tieredversion; import com.iluwatar.featuretoggle.pattern.Service; diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java index 2771655ddefa..9490b59a5967 100644 --- a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java +++ b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

+ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

+ * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.featuretoggle.user; import org.junit.jupiter.api.Test; diff --git a/fluentinterface/pom.xml b/fluentinterface/pom.xml index 23fc5d806866..1e76ea628f9d 100644 --- a/fluentinterface/pom.xml +++ b/fluentinterface/pom.xml @@ -2,7 +2,7 @@ -7Zpdk6I4FIZ/jbdbJAHEyx7nY/diqrqqd2tnLiOJSDUSK6ZHe3/9BkmUfFiDDqBM2TcNBwLxOe85nBOYoPl6/4XjzeorI7SYwIDsJ+jjBEKA4kj+qyzvtWUag9qQ8Zyok06Gl/w/qoyBsr7lhG6NEwVjhcg3pjFlZUlTYdgw52xnnrZkhXnXDc6oY3hJceFa/82JWNXWJApO9j9pnq30nUGgjixw+ppx9laq+00gWh7+6sNrrK+lzt+uMGG7hgl9mqA5Z0zUW+v9nBYVW42tHvf5zNHjvDktRZsBqB7wAxdvVM/4MC/xrlnIKW6qzRXd44yVE/RhQ3m+poLyk/X5ZPqwW+WCvmxwWo3aSYFI20qsC7kH5Ka6I+WC7s/OGhxZSI1RJi/N3+UpagBMFD4lL6D3dydnIa2lVcNRMFZGrASSHa99giQ3FCc/MzhKZmgaGcyOKBrMAPQwO2r7V5iFDrM549ThJgfJEKc/B7LMi2LOCsYP46oYg2kq7VvB2SttHCHxIo7ibhCGATARJshBqDNfk2AXoot+Lrpr4RFMk6UXXpwmdLHsCF5s6W/qwkMe+aEO4MW/GzwEPQmvJ3jT0cMDMxNeGA0GLxk7PDQ1H7VDKm82fnh2zoODwdPlz3jphdCUHoyGkx5oUeRdTS+iCQl99BK4QHFHxUoUWfQ89V5v9Fq0FXdOz9ZeMCC9Nk/ckjxVfa7cK1lJTWJ0n4tvje3vcjuotks5k2/Nne/6rJJ8zqsJHQ7Vd6PE6ZEtenJG7I2n1KhQBeYZFU0duJAbECMPRG3jtMAi/2HOwkdW3eGZ5XJ+Z7vECFjOqWevRjWbZOtCCJkXCu2Cvv7NzoUOjj7+7Ha+b1MwXOz7P6IefQwfPr7Qx33WNYNkR5s60nXuANkR9lnXDEIPWc8WNBvu2aJn+8v5JfDkF/V0Ac2nS3e5J/Hkntkj91yWe7S7O/U/OO/9/nzfWC5/+L6d70dfldsrOSEcbiXHs4R9ZeTUGdEXO41E2mX0TD3Rc1+Vue2gq6Mn6S963BX4Z8bF1hGBlLcwPW/GhFJGM4CUCRd5VsrdVDrz8FaoCpY8xcWTOrDOCSnOBWcH8YVmoYHzGDgNWYS+12pdxJe7SP/PVlKQZ1Q0ltVvtVEfXrRSojD3/w4NALvudd9hAN97x7ALQO6ywN90WwUDzqiS903h2CvFiZucZ32xcdvmv6RqMi6zFCtvjuZY4et851lN6g2N221+xAIv8Pb28RQHJhcwG04yOrU1uHxl6au0kLvBYz3dYOTi6S3doPF2irpKNAqe2I96mIIHWJ6Mr20XgF059dcuoD5axWEEoOsRQwDThwAuFECbfvE+Ox5dlxkCSB4CuFAAXbW8vpcRvldRHT4CfAK46WrhKAXQ5quzOxUAdAWAbrpkOEoBuE35E8Eb2Y//XuseVh+CPP1ZR+secvf0dXftkdMn9OjT/w== \ No newline at end of file diff --git a/hexagonal/etc/presentation.html b/hexagonal/etc/presentation.html deleted file mode 100644 index 5c6d1d0a5c6a..000000000000 --- a/hexagonal/etc/presentation.html +++ /dev/null @@ -1,127 +0,0 @@ - - - - - Title - - - - - - - - - - diff --git a/hexagonal/pom.xml b/hexagonal/pom.xml index 4f56a1020116..060d0135b428 100644 --- a/hexagonal/pom.xml +++ b/hexagonal/pom.xml @@ -2,7 +2,7 @@ - - - - - - - - - - - - - - - \ No newline at end of file + + 4.0.0 + + java-design-patterns + com.iluwatar + 1.22.0-SNAPSHOT + + leader-election + + + org.junit.jupiter + junit-jupiter-engine + test + + + \ No newline at end of file diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java new file mode 100644 index 000000000000..d69a1f134bc1 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java @@ -0,0 +1,149 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + +/** + * Abstract class of all the instance implementation classes. + */ +public abstract class AbstractInstance implements Instance, Runnable { + + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractInstance.class); + + protected static final int HEARTBEAT_INTERVAL = 5000; + + protected MessageManager messageManager; + protected Queue messageQueue; + protected final int localId; + protected int leaderId; + protected boolean alive; + + /** + * Constructor of BullyInstance. + */ + public AbstractInstance(MessageManager messageManager, int localId, int leaderId) { + this.messageManager = messageManager; + this.messageQueue = new ConcurrentLinkedQueue<>(); + this.localId = localId; + this.leaderId = leaderId; + this.alive = true; + } + + /** + * The instance will execute the message in its message queue periodically once it is alive. + */ + @Override + @SuppressWarnings("squid:S2189") + public void run() { + while (true) { + if (!this.messageQueue.isEmpty()) { + this.processMessage(this.messageQueue.remove()); + } + } + } + + /** + * Once messages are sent to the certain instance, it will firstly be added to the queue and wait to be executed. + * @param message Message sent by other instances + */ + @Override + public void onMessage(Message message) { + messageQueue.offer(message); + } + + /** + * Check if the instance is alive or not. + * @return {@code true} if the instance is alive. + */ + @Override + public boolean isAlive() { + return alive; + } + + /** + * Set the health status of the certain instance. + * @param alive {@code true} for alive. + */ + @Override + public void setAlive(boolean alive) { + this.alive = alive; + } + + /** + * Process the message according to its type. + * @param message Message polled from queue. + */ + private void processMessage(Message message) { + switch (message.getType()) { + case ELECTION: + LOGGER.info("Instance " + localId + " - Election Message handling..."); + handleElectionMessage(message); + break; + case LEADER: + LOGGER.info("Instance " + localId + " - Leader Message handling..."); + handleLeaderMessage(message); + break; + case HEARTBEAT: + LOGGER.info("Instance " + localId + " - Heartbeat Message handling..."); + handleHeartbeatMessage(message); + break; + case ELECTION_INVOKE: + LOGGER.info("Instance " + localId + " - Election Invoke Message handling..."); + handleElectionInvokeMessage(); + break; + case LEADER_INVOKE: + LOGGER.info("Instance " + localId + " - Leader Invoke Message handling..."); + handleLeaderInvokeMessage(); + break; + case HEARTBEAT_INVOKE: + LOGGER.info("Instance " + localId + " - Heartbeat Invoke Message handling..."); + handleHeartbeatInvokeMessage(); + break; + default: + break; + } + } + + /** + * Abstract methods to handle different types of message. These methods need to be implemented in concrete instance + * class to implement corresponding leader-selection pattern. + */ + protected abstract void handleElectionMessage(Message message); + + protected abstract void handleElectionInvokeMessage(); + + protected abstract void handleLeaderMessage(Message message); + + protected abstract void handleLeaderInvokeMessage(); + + protected abstract void handleHeartbeatMessage(Message message); + + protected abstract void handleHeartbeatInvokeMessage(); + +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java new file mode 100644 index 000000000000..c7e4fa598cb6 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java @@ -0,0 +1,73 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Abstract class of all the message manager classes. + */ +public abstract class AbstractMessageManager implements MessageManager { + + /** + * Contain all the instances in the system. Key is its ID, and value is the instance itself. + */ + protected Map instanceMap; + + /** + * Construtor of AbstractMessageManager + */ + public AbstractMessageManager(Map instanceMap) { + this.instanceMap = instanceMap; + } + + /** + * Find the next instance with smallest ID. + * @return The next instance. + */ + protected Instance findNextInstance(int currentId) { + Instance result = null; + List candidateList = instanceMap.keySet() + .stream() + .filter((i) -> i > currentId && instanceMap.get(i).isAlive()) + .sorted() + .collect(Collectors.toList()); + if (candidateList.isEmpty()) { + int index = instanceMap.keySet() + .stream() + .filter((i) -> instanceMap.get(i).isAlive()) + .sorted() + .collect(Collectors.toList()) + .get(0); + result = instanceMap.get(index); + } else { + int index = candidateList.get(0); + result = instanceMap.get(index); + } + return result; + } + +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java new file mode 100644 index 000000000000..1b39dff834f5 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java @@ -0,0 +1,49 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection; + +/** + * Instance interface + */ +public interface Instance { + + /** + * Check if the instance is alive or not. + * @return {@code true} if the instance is alive. + */ + boolean isAlive(); + + /** + * Set the health status of the certain instance. + * @param alive {@code true} for alive. + */ + void setAlive(boolean alive); + + /** + * Consume messages from other instances. + * @param message Message sent by other instances + */ + void onMessage(Message message); + +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java b/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java new file mode 100644 index 000000000000..1302d558857d --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java @@ -0,0 +1,76 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection; + +import java.util.Objects; + +/** + * Message used to transport data between instances. + */ +public class Message { + + private MessageType type; + + private String content; + + public Message() {} + + public Message(MessageType type, String content) { + this.type = type; + this.content = content; + } + + public MessageType getType() { + return type; + } + + public void setType(MessageType type) { + this.type = type; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Message message = (Message) o; + return type == message.type && Objects.equals(content, message.content); + } + + @Override + public int hashCode() { + return Objects.hash(type, content); + } +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java new file mode 100644 index 000000000000..fbd41cac970c --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java @@ -0,0 +1,60 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection; + +/** + * MessageManager interface + */ +public interface MessageManager { + + /** + * Send heartbeat message to leader instance to check whether the leader instance is alive. + * @param leaderId Instance ID of leader instance. + * @return {@code true} if leader instance is alive, or {@code false} if not. + */ + boolean sendHeartbeatMessage(int leaderId); + + /** + * Send election message to other instances. + * @param currentId Instance ID of which sends this message. + * @param content Election message content. + * @return {@code true} if the message is accepted by the target instances. + */ + boolean sendElectionMessage(int currentId, String content); + + /** + * Send new leader notification message to other instances. + * @param currentId Instance ID of which sends this message. + * @param leaderId Leader message content. + * @return {@code true} if the message is accepted by the target instances. + */ + boolean sendLeaderMessage(int currentId, int leaderId); + + /** + * Send heartbeat invoke message. This will invoke heartbeat task in the target instance. + * @param currentId Instance ID of which sends this message. + */ + void sendHeartbeatInvokeMessage(int currentId); + +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java new file mode 100644 index 000000000000..1749ca15c66f --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java @@ -0,0 +1,62 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection; + +/** + * Message Type enum + */ +public enum MessageType { + + /** + * Start the election. The content of the message stores ID(s) of the candidate instance(s). + */ + ELECTION, + + /** + * Nodify the new leader. The content of the message should be the leader ID. + */ + LEADER, + + /** + * Check health of current leader instance. + */ + HEARTBEAT, + + /** + * Inform target instance to start election. + */ + ELECTION_INVOKE, + + /** + * Inform target instance to notify all the other instance that it is the new leader. + */ + LEADER_INVOKE, + + /** + * Inform target instance to start heartbeat. + */ + HEARTBEAT_INVOKE + +} + diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java new file mode 100644 index 000000000000..c111f442e7ad --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java @@ -0,0 +1,77 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.bully; + +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageManager; +import com.iluwatar.leaderelection.MessageType; + +import java.util.HashMap; +import java.util.Map; + +/** + * Example of how to use bully leader election. Initially 5 instances is created in the clould + * system, and the instance with ID 1 is set as leader. After the system is started stop the + * leader instance, and the new leader will be elected. + */ +public class BullyApp { + + /** + * Program entry point + */ + public static void main(String[] args) { + + Map instanceMap = new HashMap<>(); + MessageManager messageManager = new BullyMessageManager(instanceMap); + + BullyInstance instance1 = new BullyInstance(messageManager, 1, 1); + BullyInstance instance2 = new BullyInstance(messageManager, 2, 1); + BullyInstance instance3 = new BullyInstance(messageManager, 3, 1); + BullyInstance instance4 = new BullyInstance(messageManager, 4, 1); + BullyInstance instance5 = new BullyInstance(messageManager, 5, 1); + + instanceMap.put(1, instance1); + instanceMap.put(2, instance2); + instanceMap.put(3, instance3); + instanceMap.put(4, instance4); + instanceMap.put(5, instance5); + + instance4.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); + + Thread thread1 = new Thread(instance1); + Thread thread2 = new Thread(instance2); + Thread thread3 = new Thread(instance3); + Thread thread4 = new Thread(instance4); + Thread thread5 = new Thread(instance5); + + thread1.start(); + thread2.start(); + thread3.start(); + thread4.start(); + thread5.start(); + + instance1.setAlive(false); + } +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java new file mode 100644 index 000000000000..c2c497339536 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java @@ -0,0 +1,121 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.bully; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Impelemetation with bully algorithm. Each instance should have a sequential id and is able to + * communicate with other instances in the system. Initially the instance with smallest (or largest) + * ID is selected to be the leader. All the other instances send heartbeat message to leader periodically + * to check its health. If one certain instance finds the server done, it will send an election message + * to all the instances of which the ID is larger. If the target instance is alive, it will return an + * alive message (in this sample return true) and then send election message with its ID. If not, + * the original instance will send leader message to all the other instances. + */ +public class BullyInstance extends AbstractInstance { + + private static final Logger LOGGER = LoggerFactory.getLogger(BullyInstance.class); + + /** + * Constructor of BullyInstance. + */ + public BullyInstance(MessageManager messageManager, int localId, int leaderId) { + super(messageManager, localId, leaderId); + } + + /** + * Process the heartbeat invoke message. After receiving the message, the instance will send a heartbeat + * to leader to check its health. If alive, it will inform the next instance to do the heartbeat. If not, + * it will start the election process. + */ + @Override + protected void handleHeartbeatInvokeMessage() { + try { + boolean isLeaderAlive = messageManager.sendHeartbeatMessage(leaderId); + if (isLeaderAlive) { + LOGGER.info("Instance " + localId + "- Leader is alive."); + Thread.sleep(HEARTBEAT_INTERVAL); + messageManager.sendHeartbeatInvokeMessage(localId); + } else { + LOGGER.info("Instance " + localId + "- Leader is not alive. Start election."); + boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); + if (electionResult) { + LOGGER.info("Instance " + localId + "- Succeed in election. Start leader notification."); + messageManager.sendLeaderMessage(localId, localId); + } + } + } catch (InterruptedException e) { + LOGGER.info("Instance " + localId + "- Interrupted."); + } + } + + /** + * Process election invoke message. Send election message to all the instances with smaller ID. If any + * one of them is alive, do nothing. If no instance alive, send leader message to all the alive instance + * and restart heartbeat. + */ + @Override + protected void handleElectionInvokeMessage() { + if (!isLeader()) { + LOGGER.info("Instance " + localId + "- Start election."); + boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); + if (electionResult) { + LOGGER.info("Instance " + localId + "- Succeed in election. Start leader notification."); + leaderId = localId; + messageManager.sendLeaderMessage(localId, localId); + messageManager.sendHeartbeatInvokeMessage(localId); + } + } + } + + /** + * Process leader message. Update local leader information. + */ + @Override + protected void handleLeaderMessage(Message message) { + leaderId = Integer.valueOf(message.getContent()); + LOGGER.info("Instance " + localId + " - Leader update done."); + } + + private boolean isLeader() { + return localId == leaderId; + } + + /** + * Not used in Bully instance. + */ + @Override + protected void handleLeaderInvokeMessage() {} + + @Override + protected void handleHeartbeatMessage(Message message) {} + + @Override + protected void handleElectionMessage(Message message) {} +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java new file mode 100644 index 000000000000..907098f6b379 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java @@ -0,0 +1,117 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.bully; + +import com.iluwatar.leaderelection.AbstractMessageManager; +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Implementation of BullyMessageManager + */ +public class BullyMessageManager extends AbstractMessageManager { + + /** + * Constructor of BullyMessageManager. + */ + public BullyMessageManager(Map instanceMap) { + super(instanceMap); + } + + /** + * Send heartbeat message to current leader instance to check the health. + * @param leaderId leaderID + * @return {@code true} if the leader is alive. + */ + @Override + public boolean sendHeartbeatMessage(int leaderId) { + Instance leaderInstance = instanceMap.get(leaderId); + boolean alive = leaderInstance.isAlive(); + return alive; + } + + /** + * Send election message to all the instances with smaller ID. + * @param currentId Instance ID of which sends this message. + * @param content Election message content. + * @return {@code true} if no alive instance has smaller ID, so that the election is accepted. + */ + @Override + public boolean sendElectionMessage(int currentId, String content) { + List candidateList = findElectionCandidateInstanceList(currentId); + if (candidateList.isEmpty()) { + return true; + } else { + Message electionMessage = new Message(MessageType.ELECTION_INVOKE, ""); + candidateList.stream() + .forEach((i) -> instanceMap.get(i).onMessage(electionMessage)); + return false; + } + } + + /** + * Send leader message to all the instances to notify the new leader. + * @param currentId Instance ID of which sends this message. + * @param leaderId Leader message content. + * @return {@code true} if the message is accepted. + */ + @Override + public boolean sendLeaderMessage(int currentId, int leaderId) { + Message leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); + instanceMap.keySet() + .stream() + .filter((i) -> i != currentId) + .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage)); + return false; + } + + /** + * Send heartbeat invoke message to the next instance. + * @param currentId Instance ID of which sends this message. + */ + @Override + public void sendHeartbeatInvokeMessage(int currentId) { + Instance nextInstance = this.findNextInstance(currentId); + Message heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); + nextInstance.onMessage(heartbeatInvokeMessage); + } + + /** + * Find all the alive instances with smaller ID than current instance. + * @param currentId ID of current instance. + * @return ID list of all the candidate instance. + */ + private List findElectionCandidateInstanceList(int currentId) { + return instanceMap.keySet() + .stream() + .filter((i) -> i < currentId && instanceMap.get(i).isAlive()) + .collect(Collectors.toList()); + } + +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java new file mode 100644 index 000000000000..a8a6271eae15 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java @@ -0,0 +1,77 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.ring; + +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageManager; +import com.iluwatar.leaderelection.MessageType; + +import java.util.HashMap; +import java.util.Map; + +/** + * Example of how to use ring leader election. Initially 5 instances is created in the clould + * system, and the instance with ID 1 is set as leader. After the system is started stop the + * leader instance, and the new leader will be elected. + */ +public class RingApp { + + /** + * Program entry point + */ + public static void main(String[] args) { + + Map instanceMap = new HashMap<>(); + MessageManager messageManager = new RingMessageManager(instanceMap); + + RingInstance instance1 = new RingInstance(messageManager, 1, 1); + RingInstance instance2 = new RingInstance(messageManager, 2, 1); + RingInstance instance3 = new RingInstance(messageManager, 3, 1); + RingInstance instance4 = new RingInstance(messageManager, 4, 1); + RingInstance instance5 = new RingInstance(messageManager, 5, 1); + + instanceMap.put(1, instance1); + instanceMap.put(2, instance2); + instanceMap.put(3, instance3); + instanceMap.put(4, instance4); + instanceMap.put(5, instance5); + + instance2.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); + + Thread thread1 = new Thread(instance1); + Thread thread2 = new Thread(instance2); + Thread thread3 = new Thread(instance3); + Thread thread4 = new Thread(instance4); + Thread thread5 = new Thread(instance5); + + thread1.start(); + thread2.start(); + thread3.start(); + thread4.start(); + thread5.start(); + + instance1.setAlive(false); + } +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java new file mode 100644 index 000000000000..4cdbb57090d8 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java @@ -0,0 +1,133 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.ring; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Implementation with token ring algorithm. The instances in the system are organized as a ring. + * Each instance should have a sequential id and the instance with smallest (or largest) id should + * be the initial leader. All the other instances send heartbeat message to leader periodically + * to check its health. If one certain instance finds the server done, it will send an election + * message to the next alive instance in the ring, which contains its own ID. Then the next instance + * add its ID into the message and pass it to the next. After all the alive instances' ID are add + * to the message, the message is send back to the first instance and it will choose the instance + * with smallest ID to be the new leader, and then send a leader message to other instances to + * inform the result. + */ +public class RingInstance extends AbstractInstance { + + private static final Logger LOGGER = LoggerFactory.getLogger(RingInstance.class); + + /** + * Constructor of RingInstance. + */ + public RingInstance(MessageManager messageManager, int localId, int leaderId) { + super(messageManager, localId, leaderId); + } + + /** + * Process the heartbeat invoke message. After receiving the message, the instance will send a heartbeat + * to leader to check its health. If alive, it will inform the next instance to do the heartbeat. If not, + * it will start the election process. + */ + @Override + protected void handleHeartbeatInvokeMessage() { + try { + boolean isLeaderAlive = messageManager.sendHeartbeatMessage(this.leaderId); + if (isLeaderAlive) { + LOGGER.info("Instance " + localId + "- Leader is alive. Start next heartbeat in 5 second."); + Thread.sleep(HEARTBEAT_INTERVAL); + messageManager.sendHeartbeatInvokeMessage(this.localId); + } else { + LOGGER.info("Instance " + localId + "- Leader is not alive. Start election."); + messageManager.sendElectionMessage(this.localId, String.valueOf(this.localId)); + } + } catch (InterruptedException e) { + LOGGER.info("Instance " + localId + "- Interrupted."); + } + } + + /** + * Process election message. If the local ID is contained in the ID list, the instance will select the + * alive instance with smallest ID to be the new leader, and send the leader inform message. If not, + * it will add its local ID to the list and send the message to the next instance in the ring. + */ + @Override + protected void handleElectionMessage(Message message) { + String content = message.getContent(); + LOGGER.info("Instance " + localId + " - Election Message: " + content); + List candidateList = + Arrays.stream(content.trim().split(",")) + .map(Integer::valueOf) + .sorted() + .collect(Collectors.toList()); + if (candidateList.contains(localId)) { + int newLeaderId = candidateList.get(0); + LOGGER.info("Instance " + localId + " - New leader should be " + newLeaderId + "."); + messageManager.sendLeaderMessage(localId, newLeaderId); + } else { + content += "," + localId; + messageManager.sendElectionMessage(localId, content); + } + } + + /** + * Process leader Message. The instance will set the leader ID to be the new one and send the message to + * the next instance until all the alive instance in the ring is informed. + */ + @Override + protected void handleLeaderMessage(Message message) { + int newLeaderId = Integer.valueOf(message.getContent()); + if (this.leaderId != newLeaderId) { + LOGGER.info("Instance " + localId + " - Update leaderID"); + this.leaderId = newLeaderId; + messageManager.sendLeaderMessage(localId, newLeaderId); + } else { + LOGGER.info("Instance " + localId + " - Leader update done. Start heartbeat."); + messageManager.sendHeartbeatInvokeMessage(localId); + } + } + + /** + * Not used in Ring instance. + */ + @Override + protected void handleLeaderInvokeMessage() {} + + @Override + protected void handleHeartbeatMessage(Message message) {} + + @Override + protected void handleElectionInvokeMessage() {} + +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java new file mode 100644 index 000000000000..34496363372f --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java @@ -0,0 +1,96 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.ring; + +import com.iluwatar.leaderelection.AbstractMessageManager; +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; + +import java.util.Map; + +/** + * Implementation of RingMessageManager + */ +public class RingMessageManager extends AbstractMessageManager { + + /** + * Constructor of RingMessageManager. + */ + public RingMessageManager(Map instanceMap) { + super(instanceMap); + } + + /** + * Send heartbeat message to current leader instance to check the health. + * @param leaderId leaderID + * @return {@code true} if the leader is alive. + */ + @Override + public boolean sendHeartbeatMessage(int leaderId) { + Instance leaderInstance = instanceMap.get(leaderId); + boolean alive = leaderInstance.isAlive(); + return alive; + } + + /** + * Send election message to the next instance. + * @param currentId currentID + * @param content list contains all the IDs of instances which have received this election message. + * @return {@code true} if the election message is accepted by the target instance. + */ + @Override + public boolean sendElectionMessage(int currentId, String content) { + Instance nextInstance = this.findNextInstance(currentId); + Message electionMessage = new Message(MessageType.ELECTION, content); + nextInstance.onMessage(electionMessage); + return true; + } + + /** + * Send leader message to the next instance. + * @param currentId Instance ID of which sends this message. + * @param leaderId Leader message content. + * @return {@code true} if the leader message is accepted by the target instance. + */ + @Override + public boolean sendLeaderMessage(int currentId, int leaderId) { + Instance nextInstance = this.findNextInstance(currentId); + Message leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); + nextInstance.onMessage(leaderMessage); + return true; + } + + /** + * Send heartbeat invoke message to the next instance. + * @param currentId Instance ID of which sends this message. + */ + @Override + public void sendHeartbeatInvokeMessage(int currentId) { + Instance nextInstance = this.findNextInstance(currentId); + Message heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); + nextInstance.onMessage(heartbeatInvokeMessage); + } + +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java new file mode 100644 index 000000000000..272fef29ea3d --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java @@ -0,0 +1,48 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Message test case. + */ +public class MessageTest { + + @Test + public void testGetType() { + Message message = new Message(MessageType.HEARTBEAT, ""); + assertEquals(MessageType.HEARTBEAT, message.getType()); + } + + @Test + public void testGetContent() { + String content = "test"; + Message message = new Message(MessageType.HEARTBEAT, content); + assertEquals(content, message.getContent()); + } + +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java new file mode 100644 index 000000000000..3ef36f758d97 --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java @@ -0,0 +1,39 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.bully; + +import org.junit.jupiter.api.Test; + +/** + * BullyApp unit test. + */ +public class BullyAppTest { + + @Test + public void test() { + String[] args = {}; + BullyApp.main(args); + } + +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java new file mode 100644 index 000000000000..524cf32170dc --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java @@ -0,0 +1,132 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.bully; + +import com.iluwatar.leaderelection.*; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Queue; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * BullyMessageManager unit test. + */ +public class BullyMessageManagerTest { + + @Test + public void testSendHeartbeatMessage() { + Instance instance1 = new BullyInstance(null, 1, 1); + Map instanceMap = Map.of(1, instance1); + MessageManager messageManager = new BullyMessageManager(instanceMap); + assertTrue(messageManager.sendHeartbeatMessage(1)); + } + + @Test + public void testSendElectionMessageNotAccepted() { + try { + Instance instance1 = new BullyInstance(null, 1, 1); + Instance instance2 = new BullyInstance(null, 1, 2); + Instance instance3 = new BullyInstance(null, 1, 3); + Instance instance4 = new BullyInstance(null, 1, 4); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); + instance1.setAlive(false); + MessageManager messageManager = new BullyMessageManager(instanceMap); + boolean result = messageManager.sendElectionMessage(3, "3"); + Class instanceClass = AbstractInstance.class; + Field messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + Message message2 = ((Queue) messageQueueField.get(instance2)).poll(); + int instance4QueueSize = ((Queue) messageQueueField.get(instance4)).size(); + Message expectedMessage = new Message(MessageType.ELECTION_INVOKE, ""); + assertEquals(message2, expectedMessage); + assertEquals(instance4QueueSize, 0); + assertEquals(result, false); + } catch (IllegalAccessException | NoSuchFieldException e) { + fail("Error to access private field."); + } + } + + @Test + public void testElectionMessageAccepted() { + Instance instance1 = new BullyInstance(null, 1, 1); + Instance instance2 = new BullyInstance(null, 1, 2); + Instance instance3 = new BullyInstance(null, 1, 3); + Instance instance4 = new BullyInstance(null, 1, 4); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); + instance1.setAlive(false); + MessageManager messageManager = new BullyMessageManager(instanceMap); + boolean result = messageManager.sendElectionMessage(2, "2"); + assertEquals(result, true); + } + + @Test + public void testSendLeaderMessage() { + try { + Instance instance1 = new BullyInstance(null, 1, 1); + Instance instance2 = new BullyInstance(null, 1, 2); + Instance instance3 = new BullyInstance(null, 1, 3); + Instance instance4 = new BullyInstance(null, 1, 4); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); + instance1.setAlive(false); + MessageManager messageManager = new BullyMessageManager(instanceMap); + messageManager.sendLeaderMessage(2, 2); + Class instanceClass = AbstractInstance.class; + Field messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + Message message3 = ((Queue) messageQueueField.get(instance3)).poll(); + Message message4 = ((Queue) messageQueueField.get(instance4)).poll(); + Message expectedMessage = new Message(MessageType.LEADER, "2"); + assertEquals(message3, expectedMessage); + assertEquals(message4, expectedMessage); + } catch (IllegalAccessException | NoSuchFieldException e) { + fail("Error to access private field."); + } + } + + @Test + public void testSendHeartbeatInvokeMessage() { + try { + Instance instance1 = new BullyInstance(null, 1, 1); + Instance instance2 = new BullyInstance(null, 1, 2); + Instance instance3 = new BullyInstance(null, 1, 3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); + MessageManager messageManager = new BullyMessageManager(instanceMap); + messageManager.sendHeartbeatInvokeMessage(2); + Message message = new Message(MessageType.HEARTBEAT_INVOKE, ""); + Class instanceClass = AbstractInstance.class; + Field messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + Message messageSent = ((Queue) messageQueueField.get(instance3)).poll(); + assertEquals(messageSent.getType(), message.getType()); + assertEquals(messageSent.getContent(), message.getContent()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Error to access private field."); + } + } + + +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java new file mode 100644 index 000000000000..a2bbf9c59d5d --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java @@ -0,0 +1,78 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.bully; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.Queue; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * BullyInstance unit test. + */ +public class BullyinstanceTest { + + @Test + public void testOnMessage() { + try { + final BullyInstance bullyInstance = new BullyInstance(null, 1, 1); + Message bullyMessage = new Message(MessageType.HEARTBEAT, ""); + bullyInstance.onMessage(bullyMessage); + Class instanceClass = AbstractInstance.class; + Field messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + assertEquals(bullyMessage, ((Queue) messageQueueField.get(bullyInstance)).poll()); + } catch (IllegalAccessException | NoSuchFieldException e) { + fail("fail to access messasge queue."); + } + + } + + @Test + public void testIsAlive() { + try { + final BullyInstance bullyInstance = new BullyInstance(null, 1, 1); + Class instanceClass = AbstractInstance.class; + Field aliveField = instanceClass.getDeclaredField("alive"); + aliveField.setAccessible(true); + aliveField.set(bullyInstance, false); + assertFalse(bullyInstance.isAlive()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Fail to access field alive."); + } + } + + @Test + public void testSetAlive() { + final BullyInstance bullyInstance = new BullyInstance(null, 1, 1); + bullyInstance.setAlive(false); + assertFalse(bullyInstance.isAlive()); + } + +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java new file mode 100644 index 000000000000..ec3851d9be63 --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java @@ -0,0 +1,39 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.ring; + +import org.junit.jupiter.api.Test; + +/** + * RingApp unit test. + */ +public class RingAppTest { + + @Test + public void test() { + String[] args = {}; + RingApp.main(args); + } + +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java new file mode 100644 index 000000000000..6807b1480d8e --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java @@ -0,0 +1,76 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.ring; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.Queue; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * RingInstance unit test. + */ +public class RingInstanceTest { + + @Test + public void testOnMessage() { + try { + final RingInstance ringInstance = new RingInstance(null, 1, 1); + Message ringMessage = new Message(MessageType.HEARTBEAT, ""); + ringInstance.onMessage(ringMessage); + Class ringInstanceClass = AbstractInstance.class; + Field messageQueueField = ringInstanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + assertEquals(ringMessage, ((Queue) messageQueueField.get(ringInstance)).poll()); + } catch (IllegalAccessException | NoSuchFieldException e) { + fail("fail to access messasge queue."); + } + } + + @Test + public void testIsAlive() { + try { + final RingInstance ringInstance = new RingInstance(null, 1, 1); + Class ringInstanceClass = AbstractInstance.class; + Field aliveField = ringInstanceClass.getDeclaredField("alive"); + aliveField.setAccessible(true); + aliveField.set(ringInstance, false); + assertFalse(ringInstance.isAlive()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Fail to access field alive."); + } + } + + @Test + public void testSetAlive() { + final RingInstance ringInstance = new RingInstance(null, 1, 1); + ringInstance.setAlive(false); + assertFalse(ringInstance.isAlive()); + } +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java new file mode 100644 index 000000000000..d8429f02b05f --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java @@ -0,0 +1,112 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.leaderelection.ring; + +import com.iluwatar.leaderelection.*; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Queue; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * RingMessageManager unit test. + */ +public class RingMessageManagerTest { + + @Test + public void testSendHeartbeatMessage() { + Instance instance1 = new RingInstance(null, 1, 1); + Map instanceMap = Map.of(1, instance1); + MessageManager messageManager = new RingMessageManager(instanceMap); + assertTrue(messageManager.sendHeartbeatMessage(1)); + } + + @Test + public void testSendElectionMessage() { + try { + Instance instance1 = new RingInstance(null, 1, 1); + Instance instance2 = new RingInstance(null, 1, 2); + Instance instance3 = new RingInstance(null, 1, 3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); + MessageManager messageManager = new RingMessageManager(instanceMap); + String messageContent = "2"; + messageManager.sendElectionMessage(2, messageContent); + Message ringMessage = new Message(MessageType.ELECTION, messageContent); + Class instanceClass = AbstractInstance.class; + Field messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + Message ringMessageSent = ((Queue) messageQueueField.get(instance3)).poll(); + assertEquals(ringMessageSent.getType(), ringMessage.getType()); + assertEquals(ringMessageSent.getContent(), ringMessage.getContent()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Error to access private field."); + } + } + + @Test + public void testSendLeaderMessage() { + try { + Instance instance1 = new RingInstance(null, 1, 1); + Instance instance2 = new RingInstance(null, 1, 2); + Instance instance3 = new RingInstance(null, 1, 3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); + MessageManager messageManager = new RingMessageManager(instanceMap); + String messageContent = "3"; + messageManager.sendLeaderMessage(2, 3); + Message ringMessage = new Message(MessageType.LEADER, messageContent); + Class instanceClass = AbstractInstance.class; + Field messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + Message ringMessageSent = ((Queue) messageQueueField.get(instance3)).poll(); + assertEquals(ringMessageSent, ringMessage); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Error to access private field."); + } + } + + @Test + public void testSendHeartbeatInvokeMessage() { + try { + Instance instance1 = new RingInstance(null, 1, 1); + Instance instance2 = new RingInstance(null, 1, 2); + Instance instance3 = new RingInstance(null, 1, 3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); + MessageManager messageManager = new RingMessageManager(instanceMap); + messageManager.sendHeartbeatInvokeMessage(2); + Message ringMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); + Class instanceClass = AbstractInstance.class; + Field messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + Message ringMessageSent = ((Queue) messageQueueField.get(instance3)).poll(); + assertEquals(ringMessageSent.getType(), ringMessage.getType()); + assertEquals(ringMessageSent.getContent(), ringMessage.getContent()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Error to access private field."); + } + } + +} diff --git a/license-plugin-header-style.xml b/license-plugin-header-style.xml new file mode 100644 index 000000000000..db5e35461711 --- /dev/null +++ b/license-plugin-header-style.xml @@ -0,0 +1,41 @@ + + + + + + /* + * + */EOL + (\\s|\\t)*/\\*.*$ + .*\\*/(\\s|\\t)*$ + false + true + false + + diff --git a/marker/pom.xml b/marker/pom.xml index afa82f4db4bf..d8166ab86c32 100644 --- a/marker/pom.xml +++ b/marker/pom.xml @@ -1,15 +1,19 @@ The Master-Worker pattern is used when the problem at hand can be solved by dividing into @@ -46,7 +48,8 @@ */ public class App { - + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Program entry point. * @param args command line args @@ -61,10 +64,9 @@ public static void main(String[] args) { ArrayResult result = (ArrayResult) mw.getResult(input); if (result != null) { ArrayUtilityMethods.printMatrix(inputMatrix); - System.out.println(""); ArrayUtilityMethods.printMatrix(result.data); } else { - System.out.println("Please enter non-zero input"); + LOGGER.info("Please enter non-zero input"); } } diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java index fe435b064dca..df2d691b26eb 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java index 30a446477d18..dbe4f7477c12 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java index 3e399a11e453..04db66492a13 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,6 +23,9 @@ package com.iluwatar.masterworker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Random; /** @@ -30,7 +33,10 @@ */ public class ArrayUtilityMethods { - + + private static final Logger LOGGER = LoggerFactory.getLogger(ArrayUtilityMethods.class); + + private static final Random RANDOM = new Random(); /** * Method arraysSame compares 2 arrays @param a1 and @param a2 * and @return whether their values are equal (boolean). @@ -83,11 +89,10 @@ public static boolean matricesSame(int[][] m1, int[][] m2) { public static int[][] createRandomIntMatrix(int rows, int columns) { int[][] matrix = new int[rows][columns]; - Random rand = new Random(); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { //filling cells in matrix - matrix[i][j] = rand.nextInt(10); + matrix[i][j] = RANDOM.nextInt(10); } } return matrix; @@ -101,9 +106,9 @@ public static void printMatrix(int[][] matrix) { //prints out int[][] for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { - System.out.print(matrix[i][j] + " "); + LOGGER.info(matrix[i][j] + " "); } - System.out.println(""); + LOGGER.info(""); } } diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java index 994c6b56d0b1..d0d0c2ddeac4 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java index a63e083d4ada..1bc729aa9228 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java index d7b931b2e8aa..76e9ff35ab08 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java index 4342e7fbb54e..009faf106536 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java index 9f446b96a6b7..0a3ab79b7cc1 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java index 8df46e12ee08..7e7d796eb718 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java index 7781bd365c57..1d06fcc875da 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java index 3ff27e5477e3..fff38e953216 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java index 666d469a5e1e..b5820e2af931 100644 --- a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java +++ b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java index 5ee89a94ad96..aae784b527b5 100644 --- a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java +++ b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.masterworker; import static org.junit.jupiter.api.Assertions.*; diff --git a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java index 0ac9f67e161e..b80d7881f991 100644 --- a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java +++ b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java index 307696e0c97e..3e5f581b93cf 100644 --- a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java +++ b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/mediator/pom.xml b/mediator/pom.xml index 14aadac8dd9b..7fba84dd11ab 100644 --- a/mediator/pom.xml +++ b/mediator/pom.xml @@ -2,7 +2,7 @@ + diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/App.java b/mute-idiom/src/main/java/com/iluwatar/mute/App.java index c35559dcd97f..28649e24990a 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/App.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/App.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java index 7a37ef03dfe0..d5fdaaec2b34 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java index d5d9b802849f..87a1f651e77f 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.mute; import java.io.ByteArrayOutputStream; diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java index 11bb3a6ec875..a10fe4617605 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java index 31624c99449b..5ca525a9d9f5 100644 --- a/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java +++ b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java index 07498645e83c..f2743113bea1 100644 --- a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java +++ b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/mutex/pom.xml b/mutex/pom.xml index 2075fb4a2462..05f9295eead8 100644 --- a/mutex/pom.xml +++ b/mutex/pom.xml @@ -2,7 +2,7 @@ + 4.0.0 @@ -36,6 +50,17 @@ + + + org.apache.maven.plugins + maven-compiler-plugin + ${compiler.version} + + 8 + 8 + + + @@ -78,7 +103,7 @@ true - 4.0.1 + 5.2.1 @@ -118,7 +143,6 @@ ${datanucleus-maven-plugin.version} false - ${basedir}/log4j.properties true ${basedir}/datanucleus.properties diff --git a/naked-objects/dom/src/main/java/META-INF/persistence.xml b/naked-objects/dom/src/main/java/META-INF/persistence.xml index 8824aa1ace92..fd916b0456bd 100644 --- a/naked-objects/dom/src/main/java/META-INF/persistence.xml +++ b/naked-objects/dom/src/main/java/META-INF/persistence.xml @@ -1,21 +1,27 @@ - + 4.0.0 diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/DomainAppFixturesProvider.java b/naked-objects/fixture/src/main/java/domainapp/fixture/DomainAppFixturesProvider.java index ccc11f2b8ece..7a7e8c4b7bac 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/DomainAppFixturesProvider.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/DomainAppFixturesProvider.java @@ -1,17 +1,26 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.fixture; import org.apache.isis.applib.annotation.DomainService; diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java index 58b656a9816f..4de9bfc9cf88 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java @@ -1,16 +1,24 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * - * http://www.apache.org/licenses/LICENSE-2.0 + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package domainapp.fixture.modules.simple; diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java index c0319d95383e..8fc54d0ada80 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectsTearDown.java @@ -1,16 +1,24 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * - * http://www.apache.org/licenses/LICENSE-2.0 + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package domainapp.fixture.modules.simple; diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java index be891158a0d7..303dfda4fa13 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java @@ -1,31 +1,36 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * - * http://www.apache.org/licenses/LICENSE-2.0 + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package domainapp.fixture.scenarios; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import com.google.common.collect.Lists; - -import org.apache.isis.applib.fixturescripts.FixtureScript; - import domainapp.dom.modules.simple.SimpleObject; import domainapp.fixture.modules.simple.SimpleObjectCreate; import domainapp.fixture.modules.simple.SimpleObjectsTearDown; +import org.apache.isis.applib.fixturescripts.FixtureScript; + +import java.util.Collections; +import java.util.List; /** @@ -33,8 +38,8 @@ */ public class RecreateSimpleObjects extends FixtureScript { - public final List names = Collections.unmodifiableList(Arrays.asList("Foo", "Bar", "Baz", - "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo")); + public final List names = Collections.unmodifiableList(List.of("Foo", "Bar", "Baz", + "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo")); // region > number (optional input) private Integer number; diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index c4dd52dcf652..62d25df032c9 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -1,14 +1,28 @@ - + 4.0.0 @@ -90,6 +104,11 @@ hsqldb + + javax.annotation + javax.annotation-api + + - diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java index 3ac5a1d75f2e..f67c268766c4 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java @@ -1,17 +1,26 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * - * http://www.apache.org/licenses/LICENSE-2.0 + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.integtests.bootstrap; import org.apache.isis.core.commons.config.IsisConfiguration; @@ -41,7 +50,6 @@ public static void initIsft() { private static class SimpleAppSystemBuilder extends IsisSystemForTest.Builder { public SimpleAppSystemBuilder() { - withLoggingAt(org.apache.log4j.Level.INFO); with(testConfiguration()); with(new DataNucleusPersistenceMechanismInstaller()); diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java index e41399fdd7d8..b3bd973bd0e2 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/BootstrappingGlue.java @@ -1,17 +1,26 @@ -/** - * O * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * http://www.apache.org/licenses/LICENSE-2.0 + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.integtests.specglue; import org.apache.isis.core.specsupport.scenarios.ScenarioExecutionScope; @@ -28,7 +37,6 @@ public class BootstrappingGlue extends CukeGlueAbstract { @Before(value = {"@integration"}, order = 100) public void beforeScenarioIntegrationScope() { - org.apache.log4j.PropertyConfigurator.configure("logging.properties"); SimpleAppSystemInitializer.initIsft(); before(ScenarioExecutionScope.INTEGRATION); diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java index 7a75a038139f..025c6724aa32 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java @@ -1,17 +1,26 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * http://www.apache.org/licenses/LICENSE-2.0 + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.integtests.specglue; import org.apache.isis.core.specsupport.specs.CukeGlueAbstract; diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java index b7af9f05232d..7b508faf38cf 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java @@ -1,17 +1,26 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * http://www.apache.org/licenses/LICENSE-2.0 + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.integtests.specglue.modules.simple; import static org.hamcrest.CoreMatchers.is; diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specs/RunSpecs.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specs/RunSpecs.java index 8a842a0f3140..d92cfa88185c 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/specs/RunSpecs.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specs/RunSpecs.java @@ -1,17 +1,26 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * http://www.apache.org/licenses/LICENSE-2.0 + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.integtests.specs; import org.junit.runner.RunWith; diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java index 66deaeb84034..24d8d207ce02 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java @@ -1,21 +1,26 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * - * http://www.apache.org/licenses/LICENSE-2.0 + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.integtests.tests; import org.junit.BeforeClass; @@ -32,7 +37,6 @@ public abstract class SimpleAppIntegTest extends IntegrationTestAbstract { @BeforeClass public static void initClass() { - org.apache.log4j.PropertyConfigurator.configure("logging.properties"); SimpleAppSystemInitializer.initIsft(); // instantiating will install onto ThreadLocal diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java index 3d9009bf88af..11ff6a47d400 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java @@ -1,21 +1,26 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * - * http://www.apache.org/licenses/LICENSE-2.0 + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.integtests.tests.modules.simple; import static org.junit.Assert.assertEquals; diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java index 168d4865a574..c762dd88f9b5 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java @@ -1,21 +1,26 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * - * http://www.apache.org/licenses/LICENSE-2.0 + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.integtests.tests.modules.simple; import static org.junit.Assert.assertEquals; diff --git a/naked-objects/pom.xml b/naked-objects/pom.xml index 271a07705589..b035c3894058 100644 --- a/naked-objects/pom.xml +++ b/naked-objects/pom.xml @@ -1,14 +1,28 @@ - + 4.0.0 diff --git a/naked-objects/webapp/ide/intellij/launch/README.txt b/naked-objects/webapp/ide/intellij/launch/README.txt index 6659454efdbe..2977f3068716 100644 --- a/naked-objects/webapp/ide/intellij/launch/README.txt +++ b/naked-objects/webapp/ide/intellij/launch/README.txt @@ -1,6 +1,6 @@ ==== The MIT License - Copyright (c) 2014-2016 Ilkka Seppälä + Copyright © 2014-2019 Ilkka Seppälä Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/naked-objects/webapp/ide/intellij/launch/SimpleApp_PROTOTYPE.xml b/naked-objects/webapp/ide/intellij/launch/SimpleApp_PROTOTYPE.xml index 9831f9a1f7bf..c27b5fbdd00a 100644 --- a/naked-objects/webapp/ide/intellij/launch/SimpleApp_PROTOTYPE.xml +++ b/naked-objects/webapp/ide/intellij/launch/SimpleApp_PROTOTYPE.xml @@ -1,7 +1,7 @@ + 4.0.0 @@ -202,26 +216,6 @@ hsqldb - - - - - - - org.lazyluke - log4jdbc-remix - - - org.slf4j - slf4j-api - - - - - junit junit diff --git a/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java b/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java index 459e4b7de9e0..649aea7fd743 100644 --- a/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java +++ b/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java @@ -1,17 +1,26 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + package domainapp.webapp; import java.io.IOException; @@ -42,6 +51,8 @@ import de.agilecoders.wicket.core.settings.IBootstrapSettings; import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchTheme; import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -64,6 +75,7 @@ */ public class SimpleApplication extends IsisWicketApplication { + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleApplication.class); private static final long serialVersionUID = 1L; /** @@ -116,7 +128,7 @@ public WebRequest newWebRequest(HttpServletRequest servletRequest, String filter servletRequest.getSession().invalidate(); } } catch (Exception e) { - System.out.println(e); + LOGGER.error(e.getMessage()); } return super.newWebRequest(servletRequest, filterPath); } diff --git a/naked-objects/webapp/src/main/resources/domainapp/webapp/welcome.html b/naked-objects/webapp/src/main/resources/domainapp/webapp/welcome.html index a87d67384a9f..e81389640efc 100644 --- a/naked-objects/webapp/src/main/resources/domainapp/webapp/welcome.html +++ b/naked-objects/webapp/src/main/resources/domainapp/webapp/welcome.html @@ -1,21 +1,27 @@

Apache Isis™ is a platform to let you rapidly develop diff --git a/naked-objects/webapp/src/main/webapp/WEB-INF/isis.properties b/naked-objects/webapp/src/main/webapp/WEB-INF/isis.properties index 929d1775a8b9..2ebd42968626 100644 --- a/naked-objects/webapp/src/main/webapp/WEB-INF/isis.properties +++ b/naked-objects/webapp/src/main/webapp/WEB-INF/isis.properties @@ -1,19 +1,25 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. +# +# The MIT License +# Copyright © 2014-2019 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# ################################################################################# diff --git a/naked-objects/webapp/src/main/webapp/WEB-INF/persistor.properties b/naked-objects/webapp/src/main/webapp/WEB-INF/persistor.properties index c73af73c78d4..594b97edec95 100644 --- a/naked-objects/webapp/src/main/webapp/WEB-INF/persistor.properties +++ b/naked-objects/webapp/src/main/webapp/WEB-INF/persistor.properties @@ -1,19 +1,25 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. +# +# The MIT License +# Copyright © 2014-2019 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# diff --git a/naked-objects/webapp/src/main/webapp/WEB-INF/persistor_datanucleus.properties b/naked-objects/webapp/src/main/webapp/WEB-INF/persistor_datanucleus.properties index 675ced3bf8c0..572b2e194c95 100644 --- a/naked-objects/webapp/src/main/webapp/WEB-INF/persistor_datanucleus.properties +++ b/naked-objects/webapp/src/main/webapp/WEB-INF/persistor_datanucleus.properties @@ -1,19 +1,25 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. +# +# The MIT License +# Copyright © 2014-2019 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# # # configuration file for the JDO/DataNucleus objectstore diff --git a/naked-objects/webapp/src/main/webapp/WEB-INF/viewer_restfulobjects.properties b/naked-objects/webapp/src/main/webapp/WEB-INF/viewer_restfulobjects.properties index 0a85fb681bc9..34f639a549fd 100644 --- a/naked-objects/webapp/src/main/webapp/WEB-INF/viewer_restfulobjects.properties +++ b/naked-objects/webapp/src/main/webapp/WEB-INF/viewer_restfulobjects.properties @@ -1,19 +1,25 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. +# +# The MIT License +# Copyright © 2014-2019 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# # # configuration file for the Restful Objects viewer diff --git a/naked-objects/webapp/src/main/webapp/WEB-INF/viewer_wicket.properties b/naked-objects/webapp/src/main/webapp/WEB-INF/viewer_wicket.properties index ba9eaaffb873..b52c7fa6e42e 100644 --- a/naked-objects/webapp/src/main/webapp/WEB-INF/viewer_wicket.properties +++ b/naked-objects/webapp/src/main/webapp/WEB-INF/viewer_wicket.properties @@ -1,19 +1,25 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. +# +# The MIT License +# Copyright © 2014-2019 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# # # configuration file for the Wicket viewer diff --git a/naked-objects/webapp/src/main/webapp/WEB-INF/web.xml b/naked-objects/webapp/src/main/webapp/WEB-INF/web.xml index bb6098f0bcfa..6a3ecd65dfdc 100644 --- a/naked-objects/webapp/src/main/webapp/WEB-INF/web.xml +++ b/naked-objects/webapp/src/main/webapp/WEB-INF/web.xml @@ -1,21 +1,27 @@ This app has been generated using Apache Isis' - SimpleApp archetype, + SimpleApp archetype, to create a purposefully minimal application that nevertheless includes fixture data, integration tests and BDD specs.

- The app itself consists of a single domain class, SimpleObject, - along with an equally simple (factory/repository) domain service, SimpleObjects. + The app itself consists of a single domain class, SimpleObject, + along with an equally simple (factory/repository) domain service, SimpleObjects.

To access the app:

@@ -98,8 +98,8 @@

provides accesses to a generic UI for end-users, - Isis' Wicket Viewer. - As its name suggests, this viewer is built on top of Apache Wicket™. + Isis' Wicket Viewer. + As its name suggests, this viewer is built on top of Apache Wicket™.

  • @@ -118,7 +118,7 @@

    The default user/password is sven/pass (as configured in the - shiro.ini file). + shiro.ini file).

    diff --git a/naked-objects/webapp/src/main/webapp/css/application.css b/naked-objects/webapp/src/main/webapp/css/application.css index 9f1612af1a24..b41165a5c680 100644 --- a/naked-objects/webapp/src/main/webapp/css/application.css +++ b/naked-objects/webapp/src/main/webapp/css/application.css @@ -1,19 +1,22 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at +/** + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * - * http://www.apache.org/licenses/LICENSE-2.0 + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ - diff --git a/naked-objects/webapp/src/main/webapp/scripts/application.js b/naked-objects/webapp/src/main/webapp/scripts/application.js index 3611ec357912..5ea0e2de6fa6 100644 --- a/naked-objects/webapp/src/main/webapp/scripts/application.js +++ b/naked-objects/webapp/src/main/webapp/scripts/application.js @@ -1,6 +1,6 @@ /* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/null-object/pom.xml b/null-object/pom.xml index f477b861c6d7..7111c8ff9822 100644 --- a/null-object/pom.xml +++ b/null-object/pom.xml @@ -2,7 +2,7 @@ + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.22.0-SNAPSHOT + + pipeline + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/App.java b/pipeline/src/main/java/com/iluwatar/pipeline/App.java new file mode 100644 index 000000000000..3298a6eb69b2 --- /dev/null +++ b/pipeline/src/main/java/com/iluwatar/pipeline/App.java @@ -0,0 +1,67 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.pipeline; + +/** + * The Pipeline pattern uses ordered stages to process a sequence of input values. + * Each implemented task is represented by a stage of the pipeline. You can think of + * pipelines as similar to assembly lines in a factory, where each item in the assembly + * line is constructed in stages. The partially assembled item is passed from one assembly + * stage to another. The outputs of the assembly line occur in the same order as that of the + * inputs. + * + * Classes used in this example are suffixed with "Handlers", and synonymously refers to the + * "stage". + */ +public class App { + /** + * Specify the initial input type for the first stage handler and the expected output type + * of the last stage handler as type parameters for Pipeline. Use the fluent builder by + * calling addHandler to add more stage handlers on the pipeline. + */ + public static void main(String[] args) { + /* + Suppose we wanted to pass through a String to a series of filtering stages and convert it + as a char array on the last stage. + + - Stage handler 1 (pipe): Removing the alphabets, accepts a String input and returns the + processed String output. This will be used by the next handler as its input. + + - Stage handler 2 (pipe): Removing the digits, accepts a String input and returns the + processed String output. This shall also be used by the last handler we have. + + - Stage handler 3 (pipe): Converting the String input to a char array handler. We would + be returning a different type in here since that is what's specified by the requirement. + This means that at any stages along the pipeline, the handler can return any type of data + as long as it fulfills the requirements for the next handler's input. + + Suppose we wanted to add another handler after ConvertToCharArrayHandler. That handler + then is expected to receive an input of char[] array since that is the type being returned + by the previous handler, ConvertToCharArrayHandler. + */ + new Pipeline<>(new RemoveAlphabetsHandler()) + .addHandler(new RemoveDigitsHandler()) + .addHandler(new ConvertToCharArrayHandler()); + } +} diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java new file mode 100644 index 000000000000..104d81f40b88 --- /dev/null +++ b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java @@ -0,0 +1,46 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.pipeline; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; + +/** + * Stage handler that converts an input String to its char[] array counterpart. + */ +class ConvertToCharArrayHandler implements Handler { + + private static final Logger LOGGER = LoggerFactory.getLogger(ConvertToCharArrayHandler.class); + + @Override + public char[] process(String input) { + char[] characters = input.toCharArray(); + LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", + ConvertToCharArrayHandler.class, input, String.class, Arrays.toString(characters), Character[].class)); + + return characters; + } +} diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java b/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java new file mode 100644 index 000000000000..253bc22f5607 --- /dev/null +++ b/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java @@ -0,0 +1,33 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.pipeline; + +/** + * Forms a contract to all stage handlers to accept a certain type of input and return a processed output. + * @param the input type of the handler + * @param the processed output type of the handler + */ +interface Handler { + O process(I input); +} \ No newline at end of file diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java b/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java new file mode 100644 index 000000000000..af5c69b1d77c --- /dev/null +++ b/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java @@ -0,0 +1,47 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.pipeline; + +/** + * Main Pipeline class that initially sets the current handler. Processed output + * of the initial handler is then passed as the input to the next stage handlers. + * @param the type of the input for the first stage handler + * @param the final stage handler's output type + */ +class Pipeline { + + private final Handler currentHandler; + + Pipeline(Handler currentHandler) { + this.currentHandler = currentHandler; + } + + Pipeline addHandler(Handler newHandler) { + return new Pipeline<>(input -> newHandler.process(currentHandler.process(input))); + } + + O execute(I input) { + return currentHandler.process(input); + } +} \ No newline at end of file diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java new file mode 100644 index 000000000000..930332671c3d --- /dev/null +++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java @@ -0,0 +1,55 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.pipeline; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Stage handler that returns a new instance of String without the alphabet characters of the input string. + */ +class RemoveAlphabetsHandler implements Handler { + + private static final Logger LOGGER = LoggerFactory.getLogger(RemoveAlphabetsHandler.class); + + @Override + public String process(String input) { + StringBuilder inputWithoutAlphabets = new StringBuilder(); + + for (int index = 0; index < input.length(); index++) { + char currentCharacter = input.charAt(index); + if (Character.isAlphabetic(currentCharacter)) { + continue; + } + + inputWithoutAlphabets.append(currentCharacter); + } + + String inputWithoutAlphabetsStr = inputWithoutAlphabets.toString(); + LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", + RemoveAlphabetsHandler.class, input, String.class, inputWithoutAlphabetsStr, String.class)); + + return inputWithoutAlphabetsStr; + } +} \ No newline at end of file diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java new file mode 100644 index 000000000000..6fd591006c55 --- /dev/null +++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java @@ -0,0 +1,55 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.pipeline; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Stage handler that returns a new instance of String without the digit characters of the input string. + */ +class RemoveDigitsHandler implements Handler { + + private static final Logger LOGGER = LoggerFactory.getLogger(RemoveDigitsHandler.class); + + @Override + public String process(String input) { + StringBuilder inputWithoutDigits = new StringBuilder(); + + for (int index = 0; index < input.length(); index++) { + char currentCharacter = input.charAt(index); + if (Character.isDigit(currentCharacter)) { + continue; + } + + inputWithoutDigits.append(currentCharacter); + } + + String inputWithoutDigitsStr = inputWithoutDigits.toString(); + LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", + RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class)); + + return inputWithoutDigitsStr; + } +} \ No newline at end of file diff --git a/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java b/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java new file mode 100644 index 000000000000..d5a892d91809 --- /dev/null +++ b/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java @@ -0,0 +1,38 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.pipeline; + +import org.junit.jupiter.api.Test; + +/** + * Application Test + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java b/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java new file mode 100644 index 000000000000..1de692222dbe --- /dev/null +++ b/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java @@ -0,0 +1,46 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.pipeline; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +/** + * Test for {@link Pipeline} + */ +public class PipelineTest { + + @Test + public void testAddHandlersToPipeline() { + Pipeline filters = new Pipeline<>(new RemoveAlphabetsHandler()) + .addHandler(new RemoveDigitsHandler()) + .addHandler(new ConvertToCharArrayHandler()); + + assertArrayEquals( + new char[] {'#', '!', '(', '&', '%', '#', '!'}, + filters.execute("#H!E(L&L0O%THE3R#34E!") + ); + } +} diff --git a/poison-pill/pom.xml b/poison-pill/pom.xml index 16ee086c7088..b10b54c008ff 100644 --- a/poison-pill/pom.xml +++ b/poison-pill/pom.xml @@ -2,7 +2,7 @@ @@ -25,25 +30,24 @@ java-design-patterns 1.22.0-SNAPSHOT pom - 2014 + 2014-2019 UTF-8 - 5.0.1.Final - 4.2.4.RELEASE - 1.3.3.RELEASE - 1.9.2.RELEASE + 5.2.18.Final + 5.0.13.RELEASE + 2.0.9.RELEASE + 2.0.14.RELEASE 1.4.190 4.12 - 5.0.2 + 5.5.2 ${junit.version}.2 1.0.2 3.8.1 0.8.4 1.4 - 2.16.1 + 2.24.0 19.0 1.10.19 - 4.5.10 2.22 4.0 3.3.0 @@ -51,12 +55,12 @@ 1.2.3 1.1.0 1.11.289 - 1.0.0 2.0.1 2.8.5 - 3.12.0 - 2.3.0 - 1.3.1 + 2.3.1 + 2.3.2 + 1.3.2 + 1.19.0 abstract-factory @@ -96,6 +100,7 @@ property intercepting-filter producer-consumer + pipeline poison-pill reader-writer-lock lazy-loading @@ -174,7 +179,11 @@ commander typeobjectpattern bytecode + leader-election data-locality + subclass-sandbox + circuit-breaker + double-buffer @@ -191,11 +200,6 @@ hibernate-core ${hibernate.version} - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - org.springframework.boot spring-boot-dependencies @@ -213,11 +217,6 @@ spring-webmvc ${spring.version} - - org.apache.httpcomponents - httpclient - ${apache-httpcomponents.version} - com.h2database h2 @@ -244,6 +243,12 @@ ${junit.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + org.junit.jupiter junit-jupiter-engine @@ -310,6 +315,22 @@ javax.annotation-api ${annotation-api.version} + + com.sun.xml.bind + jaxb-impl + ${jaxb-impl.version} + + + org.javassist + javassist + 3.25.0-GA + + + com.github.stefanbirkner + system-rules + ${system-rules.version} + test + @@ -334,44 +355,13 @@ - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.jacoco - - jacoco-maven-plugin - - - [0.6.2,) - - - prepare-agent - - - - - - - - - - org.apache.maven.plugins maven-compiler-plugin ${compiler.version} - 1.8 - 1.8 + 11 + 11 @@ -391,20 +381,6 @@ - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - prepare-agent - - prepare-agent - - - - - @@ -420,32 +396,36 @@ validate - checkstyle.xml + google_checks.xml checkstyle-suppressions.xml UTF-8 - true - true + true true + + - org.apache.maven.plugins - maven-pmd-plugin - ${pmd.version} - - true - 5 - true - + org.commonjava.maven.plugins + directory-maven-plugin + 0.3.1 + directories - check + directory-of + initialize - exclude-pmd.properties + projectRoot + + com.iluwatar + java-design-patterns + @@ -461,6 +441,15 @@ Ilkka Seppälä true + + ${projectRoot}${file.separator}license-plugin-header-style.xml + + + SLASHSTAR_CUSTOM_STYLE + + + .github/FUNDING.yml + @@ -472,16 +461,32 @@ + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + prepare-agent + + prepare-agent + + + + report + + report + + + + + - - org.apache.maven.plugins - maven-pmd-plugin - ${pmd.version} - org.apache.maven.plugins maven-jxr-plugin diff --git a/priority-queue/pom.xml b/priority-queue/pom.xml index aaf172ef3953..3e5ac50e81ab 100644 --- a/priority-queue/pom.xml +++ b/priority-queue/pom.xml @@ -2,7 +2,7 @@ - - - - Title - - - - - - - - - diff --git a/proxy/etc/proxy-concept.png b/proxy/etc/proxy-concept.png deleted file mode 100644 index dac5d954bc58..000000000000 Binary files a/proxy/etc/proxy-concept.png and /dev/null differ diff --git a/proxy/etc/proxy-concept.xml b/proxy/etc/proxy-concept.xml deleted file mode 100644 index 83373a92959b..000000000000 --- a/proxy/etc/proxy-concept.xml +++ /dev/null @@ -1,25 +0,0 @@ - -7Vhtb5swEP41kbYPnQJuaPexeVv3YVK1aur60YEL8WowM05K+utnYxswkC6p2rSbmkoNfnx3vpfnLsAATZLiC8fZ6huLgA78YVQM0HTg+x4KPPmlkK1GziwQcxIZoRq4Jg9gwKFB1ySC3BEUjFFBMhcMWZpCKBwMc87uXbElo+6pGY6hA1yHmHbRGxKJlUbPR8MavwQSr+zJ3tDsLHB4F3O2Ts15Ax8ty4/eTrC1ZeTzFY7YfQNCswGacMaEvkqKCVCVW5s2rTffsVv5zSEV+yica4UNpmuwHgdUqo4z5Z3YmowEv9fKpXGCeUzSAbqQu8OskP8lWAam8BPBMr132tgTUIgTTEls9ELpG/DapryKzXd5MmkAOJEGx7S7+qpsLHEIFeyqOBZl/KR9yoJ3EAtcrxe/FKtq7UVbVmJZG1txlTLLZRudtzvQJ6WYwlI0crzLdje8PpdfxgMlW9b4ww15wDz6qKU3TLJuT/d8xzF/A1wQ2Z4XmkXTkmdjw6mpdmjMpNSSlt20JJLlaLxkqTDDxfPNeo4TQtVYugS6AWVVlU4kVAkpGak6YZTx8mTbvWicC87uoLEzLD+KahxHRMbb2Juezrz5qIpEuQ/Fzhb1qsaXAxVYAoJvpYhR8M/NrDCz1A6h+3owVeNk5Q4lMxDNMIwr0/VAkBdmJvTPB+vumxoQVTd+B0yP1awR2fQGbFOuHPcf68g8w+lBPSLddnUquPTl9VvlhYmPfJf4fcz3TnuYHzwH8f23TPwrzortO+X/O8oHnkv5s9ERGY/eIuN336VNqCrE/k3wj99SzAL19zw0G70iy7pPHLNCQBrlnQpJ8EI9y8nVgrLwTsYuIZv8QC/nZVmmQzfjMg98+1Phn0Z2eWv3CiIaW3J1awxoDyDqPBu28iq9ZGsegnuLJCTtQTQeq7rpbybYJpMDxYJs3CP7MmzMXTGiWL+jlAi1aqQ9NUrNB8GWHd/7iyEdXsdQWe8qxP0o8PmoFPCaBKiL/tOoVAQodw5v1SeSxn8nzUGkQd37sR85PEYYlkHq8kXN6wjnK4gMLZp0MZTwOpSoZ0mXSE8sPnov/mHF77s12V35lKVQ9izmomd8NOZFKWLWbULs8RPSJcvz/YToEI/CiKD1hqF643AsSsgi4W1DLFMC+eEO1wzTFvfkm1zWb1y1eP1aG83+AA== \ No newline at end of file diff --git a/proxy/pom.xml b/proxy/pom.xml index e6b3ec76f7c4..e1df3657a6fa 100644 --- a/proxy/pom.xml +++ b/proxy/pom.xml @@ -2,7 +2,7 @@ - 4.0.0 diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java index 42335f313f1c..1232a73f73bc 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java index b0ccecabadaf..a4c7d07448fc 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.reader.writer.lock; import java.util.concurrent.locks.Lock; diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java index f0f5a009040a..282503ea63bc 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.reader.writer.lock; import java.util.HashSet; diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java index dc379eef97ba..afe93efd7ef2 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.reader.writer.lock; import java.util.concurrent.locks.Lock; diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java index fbdf3f846a97..0c323724e471 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.reader.writer.lock; import org.junit.jupiter.api.Test; diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java index c8de8c511b55..1f6edfa3cf3f 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java index 8fe5912ea3a5..849cf32ba802 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.reader.writer.lock; import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java index bb01e11b09eb..60c78e57313a 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.reader.writer.lock; import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java index b8ad531ce856..98f14a82bcc0 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.reader.writer.lock.utils; import ch.qos.logback.classic.Logger; diff --git a/repository/pom.xml b/repository/pom.xml index 2ccdc9da7ba5..906389282945 100644 --- a/repository/pom.xml +++ b/repository/pom.xml @@ -2,7 +2,7 @@ 4.0.0 diff --git a/retry/src/main/java/com/iluwatar/retry/App.java b/retry/src/main/java/com/iluwatar/retry/App.java index 20205bdf3973..5eb78125cc8b 100644 --- a/retry/src/main/java/com/iluwatar/retry/App.java +++ b/retry/src/main/java/com/iluwatar/retry/App.java @@ -1,25 +1,24 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä - * + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; diff --git a/retry/src/main/java/com/iluwatar/retry/BusinessException.java b/retry/src/main/java/com/iluwatar/retry/BusinessException.java index eefbf2813cbf..2da1cca8ab7b 100644 --- a/retry/src/main/java/com/iluwatar/retry/BusinessException.java +++ b/retry/src/main/java/com/iluwatar/retry/BusinessException.java @@ -1,25 +1,24 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä - * + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; diff --git a/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java b/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java index aefb589c79c3..a829ff541f35 100644 --- a/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java +++ b/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java @@ -1,25 +1,24 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä - * + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; diff --git a/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java b/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java index 596d8584d67b..c0a9ca434c93 100644 --- a/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java +++ b/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java @@ -1,25 +1,24 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä - * + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; diff --git a/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java b/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java index 2a93e992d333..02cbc6521ab9 100644 --- a/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java +++ b/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java @@ -1,25 +1,24 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä - * + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; diff --git a/retry/src/main/java/com/iluwatar/retry/FindCustomer.java b/retry/src/main/java/com/iluwatar/retry/FindCustomer.java index 421f450e59f1..e5013f50e925 100644 --- a/retry/src/main/java/com/iluwatar/retry/FindCustomer.java +++ b/retry/src/main/java/com/iluwatar/retry/FindCustomer.java @@ -1,32 +1,31 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä - * + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; import java.util.ArrayDeque; -import java.util.Arrays; import java.util.Deque; +import java.util.List; /** * Finds a customer, returning its ID from our records. @@ -49,7 +48,7 @@ public final class FindCustomer implements BusinessOperation { */ public FindCustomer(String customerId, BusinessException... errors) { this.customerId = customerId; - this.errors = new ArrayDeque<>(Arrays.asList(errors)); + this.errors = new ArrayDeque<>(List.of(errors)); } @Override diff --git a/retry/src/main/java/com/iluwatar/retry/Retry.java b/retry/src/main/java/com/iluwatar/retry/Retry.java index da5c76d5d3ac..7f188cb8f181 100644 --- a/retry/src/main/java/com/iluwatar/retry/Retry.java +++ b/retry/src/main/java/com/iluwatar/retry/Retry.java @@ -1,25 +1,24 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä - * + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; diff --git a/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java index b24bebbce192..91dc0d6b2369 100644 --- a/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java +++ b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java @@ -1,7 +1,6 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -10,16 +9,16 @@ * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; @@ -39,6 +38,7 @@ * @param the remote op's return type */ public final class RetryExponentialBackoff implements BusinessOperation { + private static final Random RANDOM = new Random(); private final BusinessOperation op; private final int maxAttempts; private final long maxDelay; @@ -100,8 +100,7 @@ public T perform() throws BusinessException { } try { - Random rand = new Random(); - long testDelay = (long) Math.pow(2, this.attempts()) * 1000 + rand.nextInt(1000); + long testDelay = (long) Math.pow(2, this.attempts()) * 1000 + RANDOM.nextInt(1000); long delay = testDelay < this.maxDelay ? testDelay : maxDelay; Thread.sleep(delay); } catch (InterruptedException f) { diff --git a/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java index 5c0cc66ed36b..b52763099bd4 100644 --- a/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java +++ b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java @@ -1,25 +1,24 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä - * + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; diff --git a/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java index d14b1eef68a6..f07d665af6a3 100644 --- a/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java +++ b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java @@ -1,7 +1,6 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -10,16 +9,16 @@ * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; diff --git a/retry/src/test/java/com/iluwatar/retry/RetryTest.java b/retry/src/test/java/com/iluwatar/retry/RetryTest.java index d435c7e84331..64df9d14d8f9 100644 --- a/retry/src/test/java/com/iluwatar/retry/RetryTest.java +++ b/retry/src/test/java/com/iluwatar/retry/RetryTest.java @@ -1,25 +1,24 @@ /* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Ilkka Seppälä - * + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ package com.iluwatar.retry; diff --git a/role-object/README.md b/role-object/README.md new file mode 100644 index 000000000000..0e960140c987 --- /dev/null +++ b/role-object/README.md @@ -0,0 +1,31 @@ +--- +layout: pattern +title: Role Object +folder: role-object +permalink: /patterns/role-object/ +categories: Structural +tags: + - Java + - Difficulty-Medium + - Handle Body Pattern +--- + +## Also known as +Post pattern, Extension Object pattern + +## Intent +Adapt an object to different client’s needs through transparently attached role objects, each one representing a role +the object has to play in that client’s context. The object manages its role set dynamically. By representing roles as +individual objects, different contexts are kept separate and system configuration is simplified. + +## Applicability +Use the Role Object pattern, if: +- you want to handle a key abstraction in different contexts and you do not want to put the resulting context specific interfaces into the same class interface. +- you want to handle the available roles dynamically so that they can be attached and removed on demand, that is at runtime, rather than fixing them statically at compile-time. +- you want to treat the extensions transparently and need to preserve the logical object identity of the resultingobject conglomerate. +- you want to keep role/client pairs independent from each other so that changes to a role do not affect clients that are not interested in that role. + +## Credits +- [Hillside - Role object pattern](https://hillside.net/plop/plop97/Proceedings/riehle.pdf) +- [Role object](http://wiki.c2.com/?RoleObject) +- [Fowler - Dealing with roles](https://martinfowler.com/apsupp/roles.pdf) \ No newline at end of file diff --git a/module/src/main/resources/log4j.xml b/role-object/pom.xml similarity index 62% rename from module/src/main/resources/log4j.xml rename to role-object/pom.xml index b591c17e1665..c9feb1419afd 100644 --- a/module/src/main/resources/log4j.xml +++ b/role-object/pom.xml @@ -1,8 +1,8 @@ - + - - - - - - - - - - - - - - - \ No newline at end of file + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.22.0-SNAPSHOT + + + role-object + + + junit + junit + test + + + + diff --git a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java new file mode 100644 index 000000000000..b8296dabacc6 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java @@ -0,0 +1,93 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.roleobject; + +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 + * dynamically attached to and removed from the core object. + * We call the resulting composite object structure, + * consisting of the core and its role objects, a subject. + * A subject often plays several roles and the same role is likely to + * be played by different subjects. + * As an example consider two different customers playing the role of borrower and + * 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. + *

    + * 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. + * It defines additional operations to manage the customer’s + * credits and securities. Similarly, the {@link InvestorRole} class adds operations specific + * to the investment department’s 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, let’s 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); + + public static void main(String[] args) { + Customer customer = Customer.newCustomer(Borrower, Investor); + + 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); + + 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); + } + + +} diff --git a/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java b/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java new file mode 100644 index 000000000000..425d9511d083 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java @@ -0,0 +1,40 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * 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 String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String borrow(){ + return String.format("Borrower %s wants to get some money.",name); + } + +} diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java new file mode 100644 index 000000000000..ebcddff4b154 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java @@ -0,0 +1,79 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * 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; + +/** + * The main abstraction to work with Customer. + */ +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); + + /** + * Check specific role @see {@link Role} + * + * @param role to check + * @return true if the role exists otherwise false + */ + + 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); + + /** + * 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 Optional getRole(Role role, Class 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; + } + +} diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java new file mode 100644 index 000000000000..5de27aa9295d --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java @@ -0,0 +1,75 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.roleobject; + +import java.util.*; + +/** + * Core class to store different customer roles + * + * @see CustomerRole + * Note: not thread safe + */ +public class CustomerCore extends Customer { + + private Map roles; + + 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 hasRole(Role role) { + return roles.containsKey(role); + } + + @Override + public boolean remRole(Role role) { + return Objects.nonNull(roles.remove(role)); + } + + @Override + public Optional getRole(Role role, Class 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 + "}"; + } +} diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java new file mode 100644 index 000000000000..40fe2341b3a9 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java @@ -0,0 +1,28 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * 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 + */ +public abstract class CustomerRole extends CustomerCore{} diff --git a/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java b/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java new file mode 100644 index 000000000000..6d5c17c904f7 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java @@ -0,0 +1,48 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * 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; + } + + public void setName(String name) { + this.name = name; + } + + 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); + } +} diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Role.java b/role-object/src/main/java/com/iluwatar/roleobject/Role.java new file mode 100644 index 000000000000..f6c739891566 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/Role.java @@ -0,0 +1,55 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.roleobject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; + +/** + * Possible roles + */ +public enum Role { + Borrower(BorrowerRole.class), Investor(InvestorRole.class); + + private Class typeCst; + + Role(Class typeCst) { + this.typeCst = typeCst; + } + + private static final Logger logger = LoggerFactory.getLogger(Role.class); + + @SuppressWarnings("unchecked") + public Optional instance() { + Class typeCst = this.typeCst; + try { + return (Optional) Optional.of(typeCst.newInstance()); + } catch (InstantiationException | IllegalAccessException e) { + logger.error("error creating an object", e); + } + return Optional.empty(); + } + +} diff --git a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java new file mode 100644 index 000000000000..831781d7103b --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java @@ -0,0 +1,33 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.roleobject; + +import org.junit.Test; + +public class ApplicationRoleObjectTest { + + @Test + public void mainTest() { + ApplicationRoleObject.main(new String[]{}); + } +} \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java new file mode 100644 index 000000000000..0c0f92fc2322 --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java @@ -0,0 +1,40 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.roleobject; + +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class BorrowerRoleTest { + + @Test + public void borrowTest() { + BorrowerRole borrowerRole = new BorrowerRole(); + borrowerRole.setName("test"); + String res = "Borrower test wants to get some money."; + + Assert.assertEquals(borrowerRole.borrow(),res); + } +} \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java new file mode 100644 index 000000000000..1b2987400d05 --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java @@ -0,0 +1,103 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.roleobject; + +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.*; + +public class CustomerCoreTest { + + @Test + public void addRole() { + CustomerCore core = new CustomerCore(); + boolean add = core.addRole(Role.Borrower); + assertTrue(add); + + } + + @Test + public void hasRole() { + CustomerCore core = new CustomerCore(); + core.addRole(Role.Borrower); + + boolean has = core.hasRole(Role.Borrower); + assertTrue(has); + + boolean notHas = core.hasRole(Role.Investor); + assertFalse(notHas); + } + + @Test + public void remRole() { + CustomerCore core = new CustomerCore(); + core.addRole(Role.Borrower); + + Optional bRole = core.getRole(Role.Borrower, BorrowerRole.class); + assertTrue(bRole.isPresent()); + + boolean res = core.remRole(Role.Borrower); + assertTrue(res); + + Optional empt = core.getRole(Role.Borrower, BorrowerRole.class); + assertFalse(empt.isPresent()); + + } + + @Test + public void getRole() { + CustomerCore core = new CustomerCore(); + core.addRole(Role.Borrower); + + Optional bRole = core.getRole(Role.Borrower, BorrowerRole.class); + assertTrue(bRole.isPresent()); + + Optional nonRole = core.getRole(Role.Borrower, InvestorRole.class); + assertFalse(nonRole.isPresent()); + + Optional invRole = core.getRole(Role.Investor, InvestorRole.class); + assertFalse(invRole.isPresent()); + + + } + + + @Test + public void toStringTest() { + CustomerCore core = new CustomerCore(); + core.addRole(Role.Borrower); + assertEquals(core.toString(), "Customer{roles=[Borrower]}"); + + core = new CustomerCore(); + core.addRole(Role.Investor); + assertEquals(core.toString(), "Customer{roles=[Investor]}"); + + core = new CustomerCore(); + assertEquals(core.toString(), "Customer{roles=[]}"); + + + } + +} \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java new file mode 100644 index 000000000000..06afa1016275 --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java @@ -0,0 +1,38 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.roleobject; + +import org.junit.Assert; +import org.junit.Test; + +public class InvestorRoleTest { + + @Test + public void investTest() { + InvestorRole investorRole = new InvestorRole(); + investorRole.setName("test"); + investorRole.setAmountToInvest(10); + String res = "Investor test has invested 10 dollars"; + Assert.assertEquals(investorRole.invest(), res); + } +} \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java new file mode 100644 index 000000000000..6ae5b0cd8857 --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java @@ -0,0 +1,40 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.roleobject; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.*; + +public class RoleTest { + + @Test + public void instanceTest() { + Optional instance = Role.Borrower.instance(); + Assert.assertTrue(instance.isPresent()); + Assert.assertEquals(instance.get().getClass(),BorrowerRole.class); + } +} \ No newline at end of file diff --git a/semaphore/pom.xml b/semaphore/pom.xml index 3761e5e49a8f..1ae865f02442 100644 --- a/semaphore/pom.xml +++ b/semaphore/pom.xml @@ -2,7 +2,7 @@ aws-lambda-java-events ${aws-lambda-java-events.version} - - com.amazonaws - aws-lambda-java-log4j - ${aws-lambda-log4j.version} - com.fasterxml.jackson.core jackson-core diff --git a/serverless/serverless.yml b/serverless/serverless.yml index c463395df226..bbf9a71c47c2 100644 --- a/serverless/serverless.yml +++ b/serverless/serverless.yml @@ -1,6 +1,6 @@ # # The MIT License -# Copyright (c) 2014 Ilkka Seppälä +# Copyright © 2014-2019 Ilkka Seppälä # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal diff --git a/serverless/src/main/java/com/iluwatar/serverless/baas/api/AbstractDynamoDbHandler.java b/serverless/src/main/java/com/iluwatar/serverless/baas/api/AbstractDynamoDbHandler.java index ac27a9a4a4b7..eff21f879cdc 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/baas/api/AbstractDynamoDbHandler.java +++ b/serverless/src/main/java/com/iluwatar/serverless/baas/api/AbstractDynamoDbHandler.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.baas.api; import com.amazonaws.regions.Regions; diff --git a/serverless/src/main/java/com/iluwatar/serverless/baas/api/FindPersonApiHandler.java b/serverless/src/main/java/com/iluwatar/serverless/baas/api/FindPersonApiHandler.java index fab448d5c2dd..3e0bde023761 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/baas/api/FindPersonApiHandler.java +++ b/serverless/src/main/java/com/iluwatar/serverless/baas/api/FindPersonApiHandler.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.baas.api; import com.amazonaws.services.lambda.runtime.Context; @@ -27,7 +28,10 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.iluwatar.serverless.baas.model.Person; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Map; /** * find person from persons collection @@ -36,13 +40,15 @@ public class FindPersonApiHandler extends AbstractDynamoDbHandler implements RequestHandler { - private static final Logger LOG = Logger.getLogger(FindPersonApiHandler.class); + private static final Logger LOG = LoggerFactory.getLogger(FindPersonApiHandler.class); private static final Integer SUCCESS_STATUS_CODE = 200; @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent, Context context) { - LOG.info(apiGatewayProxyRequestEvent.getPathParameters()); + Map pathParameters = apiGatewayProxyRequestEvent.getPathParameters(); + pathParameters.keySet().stream().map(key -> key + "=" + pathParameters.get(key)).forEach(LOG::info); + Person person = this.getDynamoDbMapper().load(Person.class, apiGatewayProxyRequestEvent .getPathParameters().get("id")); diff --git a/serverless/src/main/java/com/iluwatar/serverless/baas/api/SavePersonApiHandler.java b/serverless/src/main/java/com/iluwatar/serverless/baas/api/SavePersonApiHandler.java index b66b997d2ec7..502f12258d94 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/baas/api/SavePersonApiHandler.java +++ b/serverless/src/main/java/com/iluwatar/serverless/baas/api/SavePersonApiHandler.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.baas.api; import com.amazonaws.services.lambda.runtime.Context; @@ -27,7 +28,8 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.iluwatar.serverless.baas.model.Person; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; @@ -38,7 +40,7 @@ public class SavePersonApiHandler extends AbstractDynamoDbHandler implements RequestHandler { - private static final Logger LOG = Logger.getLogger(SavePersonApiHandler.class); + private static final Logger LOG = LoggerFactory.getLogger(SavePersonApiHandler.class); private static final Integer CREATED_STATUS_CODE = 201; private static final Integer BAD_REQUEST_STATUS_CODE = 400; diff --git a/serverless/src/main/java/com/iluwatar/serverless/baas/model/Address.java b/serverless/src/main/java/com/iluwatar/serverless/baas/model/Address.java index 7331cea2b5c9..c2e8fdac609e 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/baas/model/Address.java +++ b/serverless/src/main/java/com/iluwatar/serverless/baas/model/Address.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.baas.model; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; diff --git a/serverless/src/main/java/com/iluwatar/serverless/baas/model/Person.java b/serverless/src/main/java/com/iluwatar/serverless/baas/model/Person.java index 75604999ea34..cf8a30d3f931 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/baas/model/Person.java +++ b/serverless/src/main/java/com/iluwatar/serverless/baas/model/Person.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.baas.model; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; @@ -106,7 +107,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - int result = firstName != null ? firstName.hashCode() : 0; + var result = firstName != null ? firstName.hashCode() : 0; result = 31 * result + (lastName != null ? lastName.hashCode() : 0); result = 31 * result + (address != null ? address.hashCode() : 0); return result; diff --git a/serverless/src/main/java/com/iluwatar/serverless/faas/ApiGatewayResponse.java b/serverless/src/main/java/com/iluwatar/serverless/faas/ApiGatewayResponse.java index 98e2de64fe3c..8de0421612c8 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/faas/ApiGatewayResponse.java +++ b/serverless/src/main/java/com/iluwatar/serverless/faas/ApiGatewayResponse.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.faas; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/serverless/src/main/java/com/iluwatar/serverless/faas/LambdaInfo.java b/serverless/src/main/java/com/iluwatar/serverless/faas/LambdaInfo.java index 03932a9f0143..8fec384577a1 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/faas/LambdaInfo.java +++ b/serverless/src/main/java/com/iluwatar/serverless/faas/LambdaInfo.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.faas; import java.io.Serializable; @@ -129,7 +130,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - int result = awsRequestId != null ? awsRequestId.hashCode() : 0; + var result = awsRequestId != null ? awsRequestId.hashCode() : 0; result = 31 * result + (logGroupName != null ? logGroupName.hashCode() : 0); result = 31 * result + (logStreamName != null ? logStreamName.hashCode() : 0); result = 31 * result + (functionName != null ? functionName.hashCode() : 0); diff --git a/serverless/src/main/java/com/iluwatar/serverless/faas/api/LambdaInfoApiHandler.java b/serverless/src/main/java/com/iluwatar/serverless/faas/api/LambdaInfoApiHandler.java index 67e1835f9e13..62b73ee576fb 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/faas/api/LambdaInfoApiHandler.java +++ b/serverless/src/main/java/com/iluwatar/serverless/faas/api/LambdaInfoApiHandler.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.faas.api; import com.iluwatar.serverless.faas.ApiGatewayResponse; @@ -27,8 +28,8 @@ import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.iluwatar.serverless.faas.LambdaInfo; -import org.apache.log4j.BasicConfigurator; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; @@ -39,13 +40,12 @@ */ public class LambdaInfoApiHandler implements RequestHandler, ApiGatewayResponse> { - private static final Logger LOG = Logger.getLogger(LambdaInfoApiHandler.class); + private static final Logger LOG = LoggerFactory.getLogger(LambdaInfoApiHandler.class); private static final Integer SUCCESS_STATUS_CODE = 200; @Override public ApiGatewayResponse handleRequest(Map input, Context context) { - BasicConfigurator.configure(); LOG.info("received: " + input); return new ApiGatewayResponse @@ -63,7 +63,7 @@ public ApiGatewayResponse handleRequest(Map input, Context conte * @return LambdaInfo */ private LambdaInfo lambdaInfo(Context context) { - LambdaInfo lambdaInfo = new LambdaInfo(); + var lambdaInfo = new LambdaInfo(); lambdaInfo.setAwsRequestId(context.getAwsRequestId()); lambdaInfo.setFunctionName(context.getFunctionName()); lambdaInfo.setFunctionVersion(context.getFunctionVersion()); @@ -75,7 +75,7 @@ private LambdaInfo lambdaInfo(Context context) { } private Map headers() { - Map headers = new HashMap<>(); + var headers = new HashMap(); headers.put("Content-Type", "application/json"); return headers; diff --git a/serverless/src/main/resources/log4j.properties b/serverless/src/main/resources/log4j.properties deleted file mode 100644 index 15a25e61b87a..000000000000 --- a/serverless/src/main/resources/log4j.properties +++ /dev/null @@ -1,29 +0,0 @@ -# -# The MIT License -# Copyright (c) 2014 Ilkka Seppälä -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# - -log = . -log4j.rootLogger = DEBUG, LAMBDA - -log4j.appender.LAMBDA=com.amazonaws.services.lambda.runtime.log4j.LambdaAppender -log4j.appender.LAMBDA.layout=org.apache.log4j.PatternLayout -log4j.appender.LAMBDA.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} <%X{AWSRequestId}> %-5p %c:%L - %m%n diff --git a/serverless/src/test/java/com/iluwatar/serverless/baas/api/FindPersonApiHandlerTest.java b/serverless/src/test/java/com/iluwatar/serverless/baas/api/FindPersonApiHandlerTest.java index 561281ab3b58..a688bdf9d0ac 100644 --- a/serverless/src/test/java/com/iluwatar/serverless/baas/api/FindPersonApiHandlerTest.java +++ b/serverless/src/test/java/com/iluwatar/serverless/baas/api/FindPersonApiHandlerTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.baas.api; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; diff --git a/serverless/src/test/java/com/iluwatar/serverless/baas/api/SavePersonApiHandlerTest.java b/serverless/src/test/java/com/iluwatar/serverless/baas/api/SavePersonApiHandlerTest.java index 83008bdff309..66636c011458 100644 --- a/serverless/src/test/java/com/iluwatar/serverless/baas/api/SavePersonApiHandlerTest.java +++ b/serverless/src/test/java/com/iluwatar/serverless/baas/api/SavePersonApiHandlerTest.java @@ -1,6 +1,6 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.baas.api; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; diff --git a/serverless/src/test/java/com/iluwatar/serverless/faas/api/LambdaInfoApiHandlerTest.java b/serverless/src/test/java/com/iluwatar/serverless/faas/api/LambdaInfoApiHandlerTest.java index 876489ed2262..ec6872973449 100644 --- a/serverless/src/test/java/com/iluwatar/serverless/faas/api/LambdaInfoApiHandlerTest.java +++ b/serverless/src/test/java/com/iluwatar/serverless/faas/api/LambdaInfoApiHandlerTest.java @@ -1,17 +1,17 @@ -/** +/* * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - *

    + * Copyright © 2014-2019 Ilkka Seppälä + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - *

    + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - *

    + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.serverless.faas.api; import com.amazonaws.services.lambda.runtime.Context; diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 403a896a4613..31fc6f625b68 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -2,7 +2,7 @@ + + + java-design-patterns + com.iluwatar + 1.22.0-SNAPSHOT + + 4.0.0 + + subclass-sandbox + + + + junit + junit + + + com.github.stefanbirkner + system-rules + + + + \ No newline at end of file diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java new file mode 100644 index 000000000000..9d3881b52010 --- /dev/null +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java @@ -0,0 +1,53 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The subclass sandbox pattern describes a basic idea, while not having a lot + * of detailed mechanics. You will need the pattern when you have several similar + * subclasses. If you have to make a tiny change, then change the base class, + * while all subclasses shouldn't have to be touched. So the base class has to be + * able to provide all of the operations a derived class needs to perform. + */ +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** + * Entry point of the main program. + * @param args Program runtime arguments. + */ + public static void main(String[] args) { + LOGGER.info("Use superpower: sky launch"); + var skyLaunch = new SkyLaunch(); + skyLaunch.activate(); + LOGGER.info("Use superpower: ground dive"); + var groundDive = new GroundDive(); + groundDive.activate(); + } + +} diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java new file mode 100644 index 000000000000..57779e823c57 --- /dev/null +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java @@ -0,0 +1,44 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.slf4j.LoggerFactory; + +/** + * GroundDive superpower. + */ +public class GroundDive extends Superpower { + + public GroundDive() { + super(); + logger = LoggerFactory.getLogger(GroundDive.class); + } + + @Override + protected void activate() { + move(0, 0, -20); + playSound("GROUNDDIVE_SOUND", 5); + spawnParticles("GROUNDDIVE_PARTICLE", 20); + } +} diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java new file mode 100644 index 000000000000..803fd419ae56 --- /dev/null +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java @@ -0,0 +1,44 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.slf4j.LoggerFactory; + +/** + * SkyLaunch superpower. + */ +public class SkyLaunch extends Superpower { + + public SkyLaunch() { + super(); + logger = LoggerFactory.getLogger(SkyLaunch.class); + } + + @Override + protected void activate() { + move(0, 0, 20); + playSound("SKYLAUNCH_SOUND", 1); + spawnParticles("SKYLAUNCH_PARTICLE", 100); + } +} diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java new file mode 100644 index 000000000000..aa10f9bee0bb --- /dev/null +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java @@ -0,0 +1,69 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.slf4j.Logger; + +/** + * Superpower abstract class. In this class the basic operations of all types of + * superpowers are provided as protected methods. + */ +public abstract class Superpower { + + protected Logger logger; + + /** + * Subclass of superpower should implement this sandbox method by calling the + * methods provided in this super class. + */ + protected abstract void activate(); + + /** + * Move to (x, y, z). + * @param x X coordinate. + * @param y Y coordinate. + * @param z Z coordinate. + */ + protected void move(double x, double y, double z) { + logger.info("Move to ( " + x + ", " + y + ", " + z + " )"); + } + + /** + * Play sound effect for the superpower. + * @param soundName Sound name. + * @param volumn Value of volumn. + */ + protected void playSound(String soundName, int volumn) { + logger.info("Play " + soundName + " with volumn " + volumn); + } + + /** + * Spawn particles for the superpower. + * @param particleType Particle type. + * @param count Count of particles to be spawned. + */ + protected void spawnParticles(String particleType, int count) { + logger.info("Spawn " + count + " particle with type " + particleType); + } +} diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java new file mode 100644 index 000000000000..51ed0d455052 --- /dev/null +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java @@ -0,0 +1,38 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.junit.Test; + +/** + * App unit tests. + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } +} diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java new file mode 100644 index 000000000000..ff052a81eb30 --- /dev/null +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java @@ -0,0 +1,92 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.contrib.java.lang.system.SystemOutRule; + +/** + * GroundDive unit tests. + */ +public class GroundDiveTest { + + @Rule + public SystemOutRule log = new SystemOutRule().enableLog(); + + @Test + public void testMove() { + log.clearLog(); + var groundDive = new GroundDive(); + groundDive.move(1.0, 1.0, 1.0); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Move to ( 1.0, 1.0, 1.0 )"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testPlaySound() { + log.clearLog(); + var groundDive = new GroundDive(); + groundDive.playSound("SOUND_NAME", 1); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Play SOUND_NAME with volumn 1"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testSpawnParticles() { + log.clearLog(); + var groundDive = new GroundDive(); + groundDive.spawnParticles("PARTICLE_TYPE", 100); + final var outputLog = getLogContent(log.getLog()); + final var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testActivate() { + log.clearLog(); + var groundDive = new GroundDive(); + groundDive.activate();; + String[] logs = log.getLog().split("\n"); + final var expectedSize = 3; + final var log1 = logs[0].split("-")[1].trim() + " -" + logs[0].split("-")[2].trim(); + final var expectedLog1 = "Move to ( 0.0, 0.0, -20.0 )"; + final var log2 = getLogContent(logs[1]); + final var expectedLog2 = "Play GROUNDDIVE_SOUND with volumn 5"; + final var log3 = getLogContent(logs[2]); + final var expectedLog3 = "Spawn 20 particle with type GROUNDDIVE_PARTICLE"; + Assert.assertEquals(logs.length, expectedSize); + Assert.assertEquals(log1, expectedLog1); + Assert.assertEquals(log2, expectedLog2); + Assert.assertEquals(log3, expectedLog3); + } + + private String getLogContent(String log) { + return log.split("-")[1].trim(); + } + +} diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java new file mode 100644 index 000000000000..58a349bb5dfd --- /dev/null +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java @@ -0,0 +1,91 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.contrib.java.lang.system.SystemOutRule; + +/** + * SkyLaunch unit tests. + */ +public class SkyLaunchTest { + + @Rule + public SystemOutRule log = new SystemOutRule().enableLog(); + + @Test + public void testMove() { + log.clearLog(); + var skyLaunch = new SkyLaunch(); + skyLaunch.move(1.0, 1.0, 1.0); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Move to ( 1.0, 1.0, 1.0 )"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testPlaySound() { + log.clearLog(); + var skyLaunch = new SkyLaunch(); + skyLaunch.playSound("SOUND_NAME", 1); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Play SOUND_NAME with volumn 1"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testSpawnParticles() { + log.clearLog(); + var skyLaunch = new SkyLaunch(); + skyLaunch.spawnParticles("PARTICLE_TYPE", 100); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testActivate() { + log.clearLog(); + var skyLaunch = new SkyLaunch(); + skyLaunch.activate();; + String[] logs = log.getLog().split("\n"); + final var expectedSize = 3; + final var log1 = getLogContent(logs[0]); + final var expectedLog1 = "Move to ( 0.0, 0.0, 20.0 )"; + final var log2 = getLogContent(logs[1]); + final var expectedLog2 = "Play SKYLAUNCH_SOUND with volumn 1"; + final var log3 = getLogContent(logs[2]); + final var expectedLog3 = "Spawn 100 particle with type SKYLAUNCH_PARTICLE"; + Assert.assertEquals(logs.length, expectedSize); + Assert.assertEquals(log1, expectedLog1); + Assert.assertEquals(log2, expectedLog2); + Assert.assertEquals(log3, expectedLog3); + } + + private String getLogContent(String log) { + return log.split("-")[1].trim(); + } +} diff --git a/template-method/pom.xml b/template-method/pom.xml index e1f24ae251db..0f4a03a5fec2 100644 --- a/template-method/pom.xml +++ b/template-method/pom.xml @@ -2,7 +2,7 @@