diff --git a/LICENSE.md b/LICENSE.md index e73cf6618a69..909c618ceba9 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014-2016 Ilkka Seppälä +Copyright (c) 2014-2020 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/abstract-document/src/main/java/com/iluwatar/abstractdocument/module-info.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/module-info.java new file mode 100644 index 000000000000..9121f004990b --- /dev/null +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/module-info.java @@ -0,0 +1,26 @@ +/* + * 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. + */ + +module com.iluwatar.abstractdocument { + requires org.slf4j; +} \ No newline at end of file diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/module-info.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/module-info.java new file mode 100644 index 000000000000..f075aadc0b82 --- /dev/null +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/module-info.java @@ -0,0 +1,26 @@ +/* + * 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. + */ + +module com.iluwatar.abstractfactory { + requires org.slf4j; +} \ No newline at end of file diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/module-info.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/module-info.java new file mode 100644 index 000000000000..78de5a786d71 --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/module-info.java @@ -0,0 +1,26 @@ +/* + * 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. + */ + +module com.iluwatar.acyclicvisitor { + requires org.slf4j; +} \ No newline at end of file diff --git a/balking/pom.xml b/balking/pom.xml index aca041684f50..96453169265b 100644 --- a/balking/pom.xml +++ b/balking/pom.xml @@ -1,46 +1,54 @@ - + - - java-design-patterns - com.iluwatar - 1.23.0-SNAPSHOT - - 4.0.0 - - balking - - - org.junit.jupiter - junit-jupiter-engine - test - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + java-design-patterns + com.iluwatar + 1.23.0-SNAPSHOT + + 4.0.0 + + balking + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.balking.App + + + + + + + + diff --git a/bridge/pom.xml b/bridge/pom.xml index b37cb8c9da27..0664bc9b5977 100644 --- a/bridge/pom.xml +++ b/bridge/pom.xml @@ -1,47 +1,59 @@ - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.23.0-SNAPSHOT - - bridge - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.mockito - mockito-core - test - - + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.23.0-SNAPSHOT + + bridge + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.bridge.App + + + + + + + + diff --git a/builder/pom.xml b/builder/pom.xml index e31ef2798bcf..dab9c66a7f5b 100644 --- a/builder/pom.xml +++ b/builder/pom.xml @@ -1,42 +1,54 @@ - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.23.0-SNAPSHOT - - builder - - - org.junit.jupiter - junit-jupiter-engine - test - - + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.23.0-SNAPSHOT + + builder + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.builder.App + + + + + + + + diff --git a/business-delegate/pom.xml b/business-delegate/pom.xml index 4bf05843c00c..26987c73aef1 100644 --- a/business-delegate/pom.xml +++ b/business-delegate/pom.xml @@ -1,31 +1,23 @@ - + + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 com.iluwatar @@ -45,4 +37,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.business.delegate.App + + + + + + + + diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/module-info.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/module-info.java new file mode 100644 index 000000000000..8f331c848d30 --- /dev/null +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/module-info.java @@ -0,0 +1,26 @@ +/* + * 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. + */ + +module com.iluwatar.business.delegate { + requires org.slf4j; +} \ No newline at end of file diff --git a/bytecode/pom.xml b/bytecode/pom.xml index 6b2f0bf548ee..f6be69ceede7 100644 --- a/bytecode/pom.xml +++ b/bytecode/pom.xml @@ -1,45 +1,56 @@ - + - - java-design-patterns - com.iluwatar - 1.23.0-SNAPSHOT - - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + java-design-patterns + com.iluwatar + 1.23.0-SNAPSHOT + + 4.0.0 + + bytecode + + + org.junit.jupiter + junit-jupiter-engine + test + + - bytecode - - - org.junit.jupiter - junit-jupiter-engine - test - - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.bytecode.App + + + + + + + + \ No newline at end of file diff --git a/caching/pom.xml b/caching/pom.xml index e479bc143b52..704dd78d0049 100644 --- a/caching/pom.xml +++ b/caching/pom.xml @@ -41,7 +41,7 @@ org.mongodb mongodb-driver - 3.0.4 + 3.12.1 org.mongodb @@ -69,6 +69,21 @@ false + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.caching.App + + + + + + diff --git a/callback/pom.xml b/callback/pom.xml index 634e4f7e90c9..c156527f5dab 100644 --- a/callback/pom.xml +++ b/callback/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.callback.App + + + + + + + + diff --git a/callback/src/main/java/com/iluwatar/callback/module-info.java b/callback/src/main/java/com/iluwatar/callback/module-info.java new file mode 100644 index 000000000000..21a7a732b74b --- /dev/null +++ b/callback/src/main/java/com/iluwatar/callback/module-info.java @@ -0,0 +1,26 @@ +/* + * 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. + */ + +module com.iluwatar.callback { + requires org.slf4j; +} \ No newline at end of file diff --git a/chain/pom.xml b/chain/pom.xml index f92637935560..cf70ad1e89f0 100644 --- a/chain/pom.xml +++ b/chain/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.chain.App + + + + + + + + diff --git a/chain/src/main/java/com/iluwatar/chain/module-info.java b/chain/src/main/java/com/iluwatar/chain/module-info.java new file mode 100644 index 000000000000..4f11ab327766 --- /dev/null +++ b/chain/src/main/java/com/iluwatar/chain/module-info.java @@ -0,0 +1,26 @@ +/* + * 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. + */ + +module com.iluwatar.chain { + requires org.slf4j; +} \ No newline at end of file diff --git a/circuit-breaker/pom.xml b/circuit-breaker/pom.xml index b04cd5c25ecc..fd9f85675650 100644 --- a/circuit-breaker/pom.xml +++ b/circuit-breaker/pom.xml @@ -37,4 +37,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.circuitbreaker.App + + + + + + + + diff --git a/collection-pipeline/pom.xml b/collection-pipeline/pom.xml index 3c2a925c4836..6d8d467ad151 100644 --- a/collection-pipeline/pom.xml +++ b/collection-pipeline/pom.xml @@ -37,4 +37,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.collectionpipeline.App + + + + + + + + diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/module-info.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/module-info.java new file mode 100644 index 000000000000..f8bd30a68177 --- /dev/null +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/module-info.java @@ -0,0 +1,26 @@ +/* + * 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. + */ + +module com.iluwatar.collectionpipeline { + requires org.slf4j; +} \ No newline at end of file diff --git a/command/pom.xml b/command/pom.xml index d43e09822734..50a14c45f00d 100644 --- a/command/pom.xml +++ b/command/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.command.App + + + + + + + + diff --git a/commander/pom.xml b/commander/pom.xml index 7c675a304d3a..7ab29e421c60 100644 --- a/commander/pom.xml +++ b/commander/pom.xml @@ -37,4 +37,69 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + Employee + + + + com.iluwatar.commander.AppEmployeeDbFailCases + + + ${project.artifactId}-EmployeeDBFailCase + + + + Message + + + + com.iluwatar.commander.AppMessagingFailCases + + + ${project.artifactId}-MessagingFailCase + + + + Payment + + + + com.iluwatar.commander.AppPaymentFailCases + + + ${project.artifactId}-PaymentFailCase + + + + Queue + + + + com.iluwatar.commander.AppQueueFailCases + + + ${project.artifactId}-QueueFailCase + + + + Shipping + + + + com.iluwatar.commander.AppShippingFailCases + + + ${project.artifactId}-ShippingFailCase + + + + + + diff --git a/composite/pom.xml b/composite/pom.xml index e833646807da..c16b95c13a8a 100644 --- a/composite/pom.xml +++ b/composite/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.composite.App + + + + + + + + diff --git a/converter/pom.xml b/converter/pom.xml index 9495e811ec9a..56eb2ccdbc8d 100644 --- a/converter/pom.xml +++ b/converter/pom.xml @@ -1,49 +1,58 @@ - + - - java-design-patterns - com.iluwatar - 1.23.0-SNAPSHOT - - 4.0.0 - - - org.junit.jupiter - junit-jupiter-engine - test - - - com.google.guava - guava - - - converter - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + java-design-patterns + com.iluwatar + 1.23.0-SNAPSHOT + + converter + 4.0.0 + + + org.junit.jupiter + junit-jupiter-engine + test + + + com.google.guava + guava + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.converter.App + + + + + + + + diff --git a/cqrs/pom.xml b/cqrs/pom.xml index 0f1b4a7c31d9..b3a0303e634e 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -58,7 +58,25 @@ jaxb-api test - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.cqrs.app.App + + + + + + + + diff --git a/dao/pom.xml b/dao/pom.xml index c3bc3300c030..7e8bd56256a6 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -24,8 +24,8 @@ --> + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 com.iluwatar @@ -41,12 +41,31 @@ test - com.h2database - h2 - + com.h2database + h2 + - org.mockito - mockito-core + org.mockito + mockito-core + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.dao.App + + + + + + + + diff --git a/data-bus/pom.xml b/data-bus/pom.xml index 9a13745fe159..e67135ae0a28 100644 --- a/data-bus/pom.xml +++ b/data-bus/pom.xml @@ -48,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.databus.App + + + + + + + + diff --git a/data-locality/pom.xml b/data-locality/pom.xml index d64b0f9416ff..660daa9b7fcc 100644 --- a/data-locality/pom.xml +++ b/data-locality/pom.xml @@ -26,20 +26,38 @@ - 4.0.0 - - com.iluwatar - java-design-patterns - 1.23.0-SNAPSHOT - - data-locality - - - - org.junit.jupiter - junit-jupiter-engine - test - - + 4.0.0 + + com.iluwatar + java-design-patterns + 1.23.0-SNAPSHOT + + data-locality + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.data.locality.Application + + + + + + + + \ No newline at end of file diff --git a/data-mapper/pom.xml b/data-mapper/pom.xml index b587960ef788..64f03a186a7c 100644 --- a/data-mapper/pom.xml +++ b/data-mapper/pom.xml @@ -38,4 +38,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.datamapper.App + + + + + + + + diff --git a/data-transfer-object/pom.xml b/data-transfer-object/pom.xml index d01ff4f72ec0..5889daba887f 100644 --- a/data-transfer-object/pom.xml +++ b/data-transfer-object/pom.xml @@ -38,4 +38,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.datatransfer.CustomerClientApp + + + + + + + + diff --git a/decorator/pom.xml b/decorator/pom.xml index 3d005fa64a0a..c7e1a4d8deb3 100644 --- a/decorator/pom.xml +++ b/decorator/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.decorator.App + + + + + + + + diff --git a/delegation/pom.xml b/delegation/pom.xml index 5179a86852cd..63cd91842caa 100644 --- a/delegation/pom.xml +++ b/delegation/pom.xml @@ -26,20 +26,39 @@ - - java-design-patterns - com.iluwatar - 1.23.0-SNAPSHOT - - 4.0.0 + + java-design-patterns + com.iluwatar + 1.23.0-SNAPSHOT + + 4.0.0 - delegation + delegation - - - org.junit.jupiter - junit-jupiter-engine - test - - + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.delegation.simple.App + + + + + + + + diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index 5caf8fbbce4f..9baffe3824ab 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -43,4 +43,23 @@ guice + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.dependency.injection.App + + + + + + + + diff --git a/dirty-flag/pom.xml b/dirty-flag/pom.xml index 0362780cb1e2..c014cd41e193 100644 --- a/dirty-flag/pom.xml +++ b/dirty-flag/pom.xml @@ -46,4 +46,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.dirtyflag.App + + + + + + + + diff --git a/double-buffer/pom.xml b/double-buffer/pom.xml index f4ea7db792a3..084cbc8c9f98 100644 --- a/double-buffer/pom.xml +++ b/double-buffer/pom.xml @@ -45,5 +45,24 @@ commons-lang3 + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.doublebuffer.App + + + + + + + + \ No newline at end of file diff --git a/double-checked-locking/pom.xml b/double-checked-locking/pom.xml index 27d7d24205d2..a77546386723 100644 --- a/double-checked-locking/pom.xml +++ b/double-checked-locking/pom.xml @@ -42,4 +42,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.doublechecked.locking.App + + + + + + + + diff --git a/double-dispatch/pom.xml b/double-dispatch/pom.xml index 059a7515b3b5..9582797a2729 100644 --- a/double-dispatch/pom.xml +++ b/double-dispatch/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.doubledispatch.App + + + + + + + + diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml index e32969eaec76..578d1bbf2e46 100644 --- a/eip-aggregator/pom.xml +++ b/eip-aggregator/pom.xml @@ -84,4 +84,23 @@ + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.epi.aggregator.App + + + + + + + + diff --git a/eip-message-channel/pom.xml b/eip-message-channel/pom.xml index 800a62883c18..bea72b1f9110 100644 --- a/eip-message-channel/pom.xml +++ b/eip-message-channel/pom.xml @@ -48,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.eip.message.channel.App + + + + + + + + diff --git a/eip-publish-subscribe/pom.xml b/eip-publish-subscribe/pom.xml index 65384438ef44..e7b5462b6e13 100644 --- a/eip-publish-subscribe/pom.xml +++ b/eip-publish-subscribe/pom.xml @@ -46,4 +46,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.eip.publish.subscribe.App + + + + + + + + diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml index e73139b959fb..9c06f3f8d0f4 100644 --- a/eip-splitter/pom.xml +++ b/eip-splitter/pom.xml @@ -84,5 +84,24 @@ + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.eip.splitter.App + + + + + + + + diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index 6d29aac1afd7..06cbc33db7b8 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -84,5 +84,24 @@ + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.eip.wiretap.App + + + + + + + + diff --git a/event-aggregator/pom.xml b/event-aggregator/pom.xml index a9e8b4cd16ff..5553de2e342a 100644 --- a/event-aggregator/pom.xml +++ b/event-aggregator/pom.xml @@ -43,4 +43,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.event.aggregator.App + + + + + + + + diff --git a/event-asynchronous/pom.xml b/event-asynchronous/pom.xml index c05f54afde3f..001b3b9a894c 100644 --- a/event-asynchronous/pom.xml +++ b/event-asynchronous/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.event.asynchronous.App + + + + + + + + diff --git a/event-driven-architecture/pom.xml b/event-driven-architecture/pom.xml index 62a00fb70a5d..17d2795c4398 100644 --- a/event-driven-architecture/pom.xml +++ b/event-driven-architecture/pom.xml @@ -49,4 +49,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.eda.App + + + + + + + + diff --git a/event-queue/pom.xml b/event-queue/pom.xml index 58f31e3a05cb..fd8ce99026e3 100644 --- a/event-queue/pom.xml +++ b/event-queue/pom.xml @@ -40,4 +40,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.event.queue.App + + + + + + + + diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml index 1232bb4b43fe..0d1592abbbb9 100644 --- a/event-sourcing/pom.xml +++ b/event-sourcing/pom.xml @@ -43,8 +43,27 @@ com.google.code.gson gson - 2.8.1 + 2.8.6 + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.event.sourcing.App + + + + + + + + diff --git a/execute-around/pom.xml b/execute-around/pom.xml index e4f1d3fd299f..1752f04f5f8b 100644 --- a/execute-around/pom.xml +++ b/execute-around/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.execute.around.App + + + + + + + + diff --git a/extension-objects/pom.xml b/extension-objects/pom.xml index 34630508f480..0194357eda15 100644 --- a/extension-objects/pom.xml +++ b/extension-objects/pom.xml @@ -41,5 +41,24 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + App + + + + + + + + diff --git a/facade/README.md b/facade/README.md index 42000149898a..48650dfbb31c 100644 --- a/facade/README.md +++ b/facade/README.md @@ -76,9 +76,7 @@ public abstract class DwarvenMineWorker { } public void action(Action... actions) { - for (Action action : actions) { - action(action); - } + Arrays.stream(actions).forEach(this::action); } public abstract void work(); @@ -165,9 +163,7 @@ public class DwarvenGoldmineFacade { private static void makeActions(Collection workers, DwarvenMineWorker.Action... actions) { - for (DwarvenMineWorker worker : workers) { - worker.action(actions); - } + workers.forEach(worker -> worker.action(actions)); } } ``` diff --git a/facade/pom.xml b/facade/pom.xml index 560f7ae1018c..a7fdb88f0809 100644 --- a/facade/pom.xml +++ b/facade/pom.xml @@ -39,4 +39,24 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.facade.App + + + + + + + + + diff --git a/facade/src/main/java/com/iluwatar/facade/App.java b/facade/src/main/java/com/iluwatar/facade/App.java index 8d1c34c39576..d77695b28ffd 100644 --- a/facade/src/main/java/com/iluwatar/facade/App.java +++ b/facade/src/main/java/com/iluwatar/facade/App.java @@ -42,7 +42,7 @@ public class App { * @param args command line args */ public static void main(String[] args) { - DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade(); + var facade = new DwarvenGoldmineFacade(); facade.startNewDay(); facade.digOutGold(); facade.endDay(); diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java index 9982e556b2b4..0cc91f29d6a6 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java @@ -63,8 +63,6 @@ private static void makeActions( Collection workers, DwarvenMineWorker.Action... actions ) { - for (DwarvenMineWorker worker : workers) { - worker.action(actions); - } + workers.forEach(worker -> worker.action(actions)); } } diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java index 8263d71f241b..d52291ad434a 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java @@ -23,6 +23,7 @@ package com.iluwatar.facade; +import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -76,9 +77,7 @@ private void action(Action action) { * Perform actions. */ public void action(Action... actions) { - for (Action action : actions) { - action(action); - } + Arrays.stream(actions).forEach(this::action); } public abstract void work(); diff --git a/facade/src/test/java/com/iluwatar/facade/AppTest.java b/facade/src/test/java/com/iluwatar/facade/AppTest.java index 828c01ebf61c..b6287b02b174 100644 --- a/facade/src/test/java/com/iluwatar/facade/AppTest.java +++ b/facade/src/test/java/com/iluwatar/facade/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java index 33e157b771d2..3b67f37547c6 100644 --- a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java +++ b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java @@ -23,20 +23,19 @@ package com.iluwatar.facade; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Date: 12/9/15 - 9:40 PM * @@ -56,16 +55,16 @@ public void tearDown() { appender.stop(); } - /** + /** * Test a complete day cycle in the gold mine by executing all three different steps: {@link * DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link * DwarvenGoldmineFacade#endDay()}. - * + *

* See if the workers are doing what's expected from them on each step. */ @Test public void testFullWorkDay() { - final DwarvenGoldmineFacade goldMine = new DwarvenGoldmineFacade(); + final var goldMine = new DwarvenGoldmineFacade(); goldMine.startNewDay(); // On the start of a day, all workers should wake up ... @@ -128,7 +127,9 @@ public int getLogSize() { } public boolean logContains(String message) { - return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + return log.stream() + .map(ILoggingEvent::getFormattedMessage) + .anyMatch(message::equals); } } diff --git a/factory-kit/pom.xml b/factory-kit/pom.xml index 194f94d5d926..87f27b341bc4 100644 --- a/factory-kit/pom.xml +++ b/factory-kit/pom.xml @@ -40,4 +40,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.factorykit.App + + + + + + + + diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/App.java b/factory-kit/src/main/java/com/iluwatar/factorykit/App.java index f767fb689359..a47ee38226cc 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/App.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/App.java @@ -48,13 +48,13 @@ public class App { * @param args command line args */ public static void main(String[] args) { - WeaponFactory factory = WeaponFactory.factory(builder -> { + var factory = WeaponFactory.factory(builder -> { builder.add(WeaponType.SWORD, Sword::new); builder.add(WeaponType.AXE, Axe::new); builder.add(WeaponType.SPEAR, Spear::new); builder.add(WeaponType.BOW, Bow::new); }); - Weapon axe = factory.create(WeaponType.AXE); + var axe = factory.create(WeaponType.AXE); LOGGER.info(axe.toString()); } } diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java index 2bdde87f7545..cf520dc0563b 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java @@ -24,7 +24,6 @@ package com.iluwatar.factorykit; import java.util.HashMap; -import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; @@ -52,7 +51,7 @@ public interface WeaponFactory { * @return factory with specified {@link Builder}s */ static WeaponFactory factory(Consumer consumer) { - Map> map = new HashMap<>(); + var map = new HashMap>(); consumer.accept(map::put); return name -> map.get(name).get(); } diff --git a/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java b/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java index 2d3481c4884d..f1d3c65a2f52 100644 --- a/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java +++ b/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java @@ -33,8 +33,7 @@ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java b/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java index 9892e8497409..fd8241efe262 100644 --- a/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java +++ b/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java @@ -23,6 +23,8 @@ package com.iluwatar.factorykit.factorykit; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.factorykit.Axe; import com.iluwatar.factorykit.Spear; import com.iluwatar.factorykit.Sword; @@ -32,10 +34,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; - - /** - * Test Factory Kit Pattern +/** + * Test Factory Kit Pattern */ public class FactoryKitTest { @@ -51,30 +51,33 @@ public void init() { } /** - * Testing {@link WeaponFactory} to produce a SPEAR asserting that the Weapon is an instance of {@link Spear} + * Testing {@link WeaponFactory} to produce a SPEAR asserting that the Weapon is an instance of + * {@link Spear} */ @Test public void testSpearWeapon() { - Weapon weapon = factory.create(WeaponType.SPEAR); + var weapon = factory.create(WeaponType.SPEAR); verifyWeapon(weapon, Spear.class); } /** - * Testing {@link WeaponFactory} to produce a AXE asserting that the Weapon is an instance of {@link Axe} + * Testing {@link WeaponFactory} to produce a AXE asserting that the Weapon is an instance of + * {@link Axe} */ @Test public void testAxeWeapon() { - Weapon weapon = factory.create(WeaponType.AXE); + var weapon = factory.create(WeaponType.AXE); verifyWeapon(weapon, Axe.class); } /** - * Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of {@link Sword} + * Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of + * {@link Sword} */ @Test public void testWeapon() { - Weapon weapon = factory.create(WeaponType.SWORD); + var weapon = factory.create(WeaponType.SWORD); verifyWeapon(weapon, Sword.class); } diff --git a/factory-method/README.md b/factory-method/README.md index 18cbba2e4a35..48ba6649cbcd 100644 --- a/factory-method/README.md +++ b/factory-method/README.md @@ -55,7 +55,7 @@ public class OrcBlacksmith implements Blacksmith { Now as the customers come the correct type of blacksmith is summoned and requested weapons are manufactured ```java -Blacksmith blacksmith = new ElfBlacksmith(); +var blacksmith = new ElfBlacksmith(); blacksmith.manufactureWeapon(WeaponType.SPEAR); blacksmith.manufactureWeapon(WeaponType.AXE); // Elvish weapons are created diff --git a/factory-method/pom.xml b/factory-method/pom.xml index 5b3b6c9cc5b1..5f0358d4dcc1 100644 --- a/factory-method/pom.xml +++ b/factory-method/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.factory.method.App + + + + + + + + diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/App.java b/factory-method/src/main/java/com/iluwatar/factory/method/App.java index 8ebf54b03965..1bfd824578eb 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/App.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/App.java @@ -64,7 +64,7 @@ public App(Blacksmith blacksmith) { */ public static void main(String[] args) { // Lets go to war with Orc weapons - App app = new App(new OrcBlacksmith()); + var app = new App(new OrcBlacksmith()); app.manufactureWeapons(); // Lets go to war with Elf weapons @@ -73,8 +73,7 @@ public static void main(String[] args) { } private void manufactureWeapons() { - Weapon weapon; - weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); LOGGER.info(weapon.toString()); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); LOGGER.info(weapon.toString()); diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java index 0da783a34352..b6f29e43a937 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java @@ -23,6 +23,7 @@ package com.iluwatar.factory.method; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -35,14 +36,12 @@ public class ElfBlacksmith implements Blacksmith { static { ELFARSENAL = new HashMap<>(WeaponType.values().length); - for (WeaponType type : WeaponType.values()) { - ELFARSENAL.put(type, new ElfWeapon(type)); - } + Arrays.stream(WeaponType.values()).forEach(type -> ELFARSENAL.put(type, new ElfWeapon(type))); } - + @Override public Weapon manufactureWeapon(WeaponType weaponType) { return ELFARSENAL.get(weaponType); } - + } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java index 376b2ec34283..b048300855df 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java @@ -23,6 +23,7 @@ package com.iluwatar.factory.method; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -35,9 +36,7 @@ public class OrcBlacksmith implements Blacksmith { static { ORCARSENAL = new HashMap<>(WeaponType.values().length); - for (WeaponType type : WeaponType.values()) { - ORCARSENAL.put(type, new OrcWeapon(type)); - } + Arrays.stream(WeaponType.values()).forEach(type -> ORCARSENAL.put(type, new OrcWeapon(type))); } @Override diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java index eb71fb167249..c23295d9a0ff 100644 --- a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java +++ b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java @@ -25,15 +25,12 @@ import org.junit.jupiter.api.Test; -import java.io.IOException; - /** * Tests that Factory Method example runs without errors. */ public class AppTest { @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + public void test() { + App.main(new String[]{}); } } diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java index eab890002f24..68960204a2b3 100644 --- a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java +++ b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java @@ -23,79 +23,80 @@ package com.iluwatar.factory.method; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * The Factory Method is a creational design pattern which uses factory methods to deal with the * problem of creating objects without specifying the exact class of object that will be created. * This is done by creating objects via calling a factory method either specified in an interface * and implemented by child classes, or implemented in a base class and optionally overridden by * derived classes—rather than by calling a constructor. - * - *

Factory produces the object of its liking. - * The weapon {@link Weapon} manufactured by the - * blacksmith depends on the kind of factory implementation it is referring to. + * + *

Factory produces the object of its liking. + * The weapon {@link Weapon} manufactured by the blacksmith depends on the kind of factory + * implementation it is referring to. *

*/ public class FactoryMethodTest { /** - * Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance - * of {@link OrcWeapon}. + * Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of + * {@link OrcWeapon}. */ @Test public void testOrcBlacksmithWithSpear() { - Blacksmith blacksmith = new OrcBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + var blacksmith = new OrcBlacksmith(); + var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); verifyWeapon(weapon, WeaponType.SPEAR, OrcWeapon.class); } /** - * Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance - * of {@link OrcWeapon}. + * Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance of + * {@link OrcWeapon}. */ @Test public void testOrcBlacksmithWithAxe() { - Blacksmith blacksmith = new OrcBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.AXE); + var blacksmith = new OrcBlacksmith(); + var weapon = blacksmith.manufactureWeapon(WeaponType.AXE); verifyWeapon(weapon, WeaponType.AXE, OrcWeapon.class); } /** - * Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an - * instance of {@link ElfWeapon}. + * Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an instance + * of {@link ElfWeapon}. */ @Test public void testElfBlacksmithWithShortSword() { - Blacksmith blacksmith = new ElfBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); + var blacksmith = new ElfBlacksmith(); + var weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); verifyWeapon(weapon, WeaponType.SHORT_SWORD, ElfWeapon.class); } /** - * Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance - * of {@link ElfWeapon}. + * Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of + * {@link ElfWeapon}. */ @Test public void testElfBlacksmithWithSpear() { - Blacksmith blacksmith = new ElfBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + var blacksmith = new ElfBlacksmith(); + var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); verifyWeapon(weapon, WeaponType.SPEAR, ElfWeapon.class); } /** * This method asserts that the weapon object that is passed is an instance of the clazz and the * weapon is of type expectedWeaponType. - * - * @param weapon weapon object which is to be verified + * + * @param weapon weapon object which is to be verified * @param expectedWeaponType expected WeaponType of the weapon - * @param clazz expected class of the weapon + * @param clazz expected class of the weapon */ private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class clazz) { assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); - assertEquals(expectedWeaponType, weapon.getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType); + assertEquals(expectedWeaponType, weapon + .getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType); } } diff --git a/feature-toggle/pom.xml b/feature-toggle/pom.xml index 4ecd5f59df29..13f646b801a5 100644 --- a/feature-toggle/pom.xml +++ b/feature-toggle/pom.xml @@ -43,4 +43,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.featuretoggle.App + + + + + + + + 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 af8e731c8a98..ceb926b63f68 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java @@ -72,33 +72,33 @@ public class App { */ public static void main(String[] args) { - final Properties properties = new Properties(); + final var properties = new Properties(); properties.put("enhancedWelcome", true); - Service service = new PropertiesFeatureToggleVersion(properties); - final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + var service = new PropertiesFeatureToggleVersion(properties); + final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); LOGGER.info(welcomeMessage); // --------------------------------------------- - final Properties turnedOff = new Properties(); + final var turnedOff = new Properties(); turnedOff.put("enhancedWelcome", false); - Service turnedOffService = new PropertiesFeatureToggleVersion(turnedOff); - final String welcomeMessageturnedOff = + var turnedOffService = new PropertiesFeatureToggleVersion(turnedOff); + final var welcomeMessageturnedOff = turnedOffService.getWelcomeMessage(new User("Jamie No Code")); LOGGER.info(welcomeMessageturnedOff); // -------------------------------------------- - Service service2 = new TieredFeatureToggleVersion(); + var service2 = new TieredFeatureToggleVersion(); - final User paidUser = new User("Jamie Coder"); - final User freeUser = new User("Alan Defect"); + final var paidUser = new User("Jamie Coder"); + final var freeUser = new User("Alan Defect"); UserGroup.addUserToPaidGroup(paidUser); UserGroup.addUserToFreeGroup(freeUser); - final String welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser); - final String welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser); + final var welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser); + final var welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser); LOGGER.info(welcomeMessageFreeUser); LOGGER.info(welcomeMessagePaidUser); } 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 0bab8bca4ba2..69641a7ada37 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 @@ -23,17 +23,15 @@ package com.iluwatar.featuretoggle.pattern.propertiesversion; -import com.iluwatar.featuretoggle.pattern.Service; -import com.iluwatar.featuretoggle.user.User; -import org.junit.jupiter.api.Test; - -import java.util.Properties; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.iluwatar.featuretoggle.user.User; +import java.util.Properties; +import org.junit.jupiter.api.Test; + /** * Test Properties Toggle */ @@ -49,7 +47,7 @@ public void testNullPropertiesPassed() { @Test public void testNonBooleanProperty() { assertThrows(IllegalArgumentException.class, () -> { - final Properties properties = new Properties(); + final var properties = new Properties(); properties.setProperty("enhancedWelcome", "Something"); new PropertiesFeatureToggleVersion(properties); }); @@ -57,21 +55,21 @@ public void testNonBooleanProperty() { @Test public void testFeatureTurnedOn() { - final Properties properties = new Properties(); + final var properties = new Properties(); properties.put("enhancedWelcome", true); - Service service = new PropertiesFeatureToggleVersion(properties); + var service = new PropertiesFeatureToggleVersion(properties); assertTrue(service.isEnhanced()); - final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); assertEquals("Welcome Jamie No Code. You're using the enhanced welcome message.", welcomeMessage); } @Test public void testFeatureTurnedOff() { - final Properties properties = new Properties(); + final var properties = new Properties(); properties.put("enhancedWelcome", false); - Service service = new PropertiesFeatureToggleVersion(properties); + var service = new PropertiesFeatureToggleVersion(properties); assertFalse(service.isEnhanced()); - final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); assertEquals("Welcome to the application.", welcomeMessage); } } 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 1d161c741a74..bb7195b7d2e6 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 @@ -23,15 +23,15 @@ package com.iluwatar.featuretoggle.pattern.tieredversion; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.featuretoggle.pattern.Service; import com.iluwatar.featuretoggle.user.User; import com.iluwatar.featuretoggle.user.UserGroup; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Test Tiered Feature Toggle */ @@ -49,15 +49,15 @@ public void setUp() { @Test public void testGetWelcomeMessageForPaidUser() { - final String welcomeMessage = service.getWelcomeMessage(paidUser); - final String expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software."; + final var welcomeMessage = service.getWelcomeMessage(paidUser); + final var expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software."; assertEquals(expected, welcomeMessage); } @Test public void testGetWelcomeMessageForFreeUser() { - final String welcomeMessage = service.getWelcomeMessage(freeUser); - final String expected = "I suppose you can use this software."; + final var welcomeMessage = service.getWelcomeMessage(freeUser); + final var expected = "I suppose you can use this software."; assertEquals(expected, welcomeMessage); } 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 9490b59a5967..9bc29fabfcf7 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 @@ -23,34 +23,34 @@ package com.iluwatar.featuretoggle.user; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * Test User Group specific feature */ public class UserGroupTest { @Test - public void testAddUserToFreeGroup() throws Exception { - User user = new User("Free User"); + public void testAddUserToFreeGroup() { + var user = new User("Free User"); UserGroup.addUserToFreeGroup(user); assertFalse(UserGroup.isPaid(user)); } @Test - public void testAddUserToPaidGroup() throws Exception { - User user = new User("Paid User"); + public void testAddUserToPaidGroup() { + var user = new User("Paid User"); UserGroup.addUserToPaidGroup(user); assertTrue(UserGroup.isPaid(user)); } @Test - public void testAddUserToPaidWhenOnFree() throws Exception { - User user = new User("Paid User"); + public void testAddUserToPaidWhenOnFree() { + var user = new User("Paid User"); UserGroup.addUserToFreeGroup(user); assertThrows(IllegalArgumentException.class, () -> { UserGroup.addUserToPaidGroup(user); @@ -58,8 +58,8 @@ public void testAddUserToPaidWhenOnFree() throws Exception { } @Test - public void testAddUserToFreeWhenOnPaid() throws Exception { - User user = new User("Free User"); + public void testAddUserToFreeWhenOnPaid() { + var user = new User("Free User"); UserGroup.addUserToPaidGroup(user); assertThrows(IllegalArgumentException.class, () -> { UserGroup.addUserToFreeGroup(user); diff --git a/fluentinterface/pom.xml b/fluentinterface/pom.xml index a40541fc4e2b..9eb063c132c5 100644 --- a/fluentinterface/pom.xml +++ b/fluentinterface/pom.xml @@ -46,4 +46,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.fluentinterface.app.App + + + + + + + + diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java index b3f8fc0b6a32..547c657e4c53 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java @@ -28,8 +28,6 @@ import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable; import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable; -import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.StringJoiner; import java.util.function.Function; @@ -57,19 +55,23 @@ public class App { */ public static void main(String[] args) { - List integerList = new ArrayList<>(); - integerList.addAll(List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, - -68, 45)); + var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68); prettyPrint("The initial list contains: ", integerList); - List firstFiveNegatives = - SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).first(3).asList(); + var firstFiveNegatives = SimpleFluentIterable + .fromCopyOf(integerList) + .filter(negatives()) + .first(3) + .asList(); prettyPrint("The first three negative values are: ", firstFiveNegatives); - List lastTwoPositives = - SimpleFluentIterable.fromCopyOf(integerList).filter(positives()).last(2).asList(); + var lastTwoPositives = SimpleFluentIterable + .fromCopyOf(integerList) + .filter(positives()) + .last(2) + .asList(); prettyPrint("The last two positive values are: ", lastTwoPositives); SimpleFluentIterable @@ -79,15 +81,21 @@ public static void main(String[] args) { .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); - List transformedList = - SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).map(transformToString()) - .asList(); + var transformedList = SimpleFluentIterable + .fromCopyOf(integerList) + .filter(negatives()) + .map(transformToString()) + .asList(); prettyPrint("A string-mapped list of negative numbers contains: ", transformedList); - List lastTwoOfFirstFourStringMapped = - LazyFluentIterable.from(integerList).filter(positives()).first(4).last(2) - .map(number -> "String[" + valueOf(number) + "]").asList(); + var lastTwoOfFirstFourStringMapped = LazyFluentIterable + .from(integerList) + .filter(positives()) + .first(4) + .last(2) + .map(number -> "String[" + valueOf(number) + "]") + .asList(); prettyPrint("The lazy list contains the last two of the first four positive numbers " + "mapped to Strings: ", lastTwoOfFirstFourStringMapped); @@ -96,12 +104,11 @@ public static void main(String[] args) { .filter(negatives()) .first(2) .last() - .ifPresent(lastOfFirstTwo -> LOGGER - .info("The last of the first two negatives is: {}", lastOfFirstTwo)); + .ifPresent(number -> LOGGER.info("Last amongst first two negatives: {}", number)); } private static Function transformToString() { - return integer -> "String[" + valueOf(integer) + "]"; + return integer -> "String[" + integer + "]"; } private static Predicate negatives() { @@ -116,14 +123,12 @@ private static void prettyPrint(String prefix, Iterable iterable) { prettyPrint(", ", prefix, iterable); } - private static void prettyPrint(String delimiter, String prefix, - Iterable iterable) { - StringJoiner joiner = new StringJoiner(delimiter, prefix, "."); - Iterator iterator = iterable.iterator(); - while (iterator.hasNext()) { - joiner.add(iterator.next().toString()); - } - + private static void prettyPrint( + String delimiter, String prefix, + Iterable iterable + ) { + var joiner = new StringJoiner(delimiter, prefix, "."); + iterable.forEach(e -> joiner.add(e.toString())); LOGGER.info(joiner.toString()); } } diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java index ea8d7c9bf1fb..2ffa4d3dd355 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java @@ -24,7 +24,6 @@ package com.iluwatar.fluentinterface.fluentiterable; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -102,11 +101,8 @@ public interface FluentIterable extends Iterable { * @return a list with all objects of the given iterator */ static List copyToList(Iterable iterable) { - List copy = new ArrayList<>(); - Iterator iterator = iterable.iterator(); - while (iterator.hasNext()) { - copy.add(iterator.next()); - } + var copy = new ArrayList(); + iterable.forEach(copy::add); return copy; } } diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java index 711b54fc9c1a..c0b52cec7e03 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java @@ -65,7 +65,7 @@ public final E next() { if (next == null) { return fromIterator.next(); } else { - final E result = next; + final var result = next; next = null; return result; } diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java index 82173c513189..f001c532f2c0 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java @@ -67,14 +67,14 @@ protected LazyFluentIterable() { */ @Override public FluentIterable filter(Predicate predicate) { - return new LazyFluentIterable() { + return new LazyFluentIterable<>() { @Override public Iterator iterator() { return new DecoratingIterator(iterable.iterator()) { @Override public E computeNext() { while (fromIterator.hasNext()) { - E candidate = fromIterator.next(); + var candidate = fromIterator.next(); if (predicate.test(candidate)) { return candidate; } @@ -94,7 +94,7 @@ public E computeNext() { */ @Override public Optional first() { - Iterator resultIterator = first(1).iterator(); + var resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } @@ -116,7 +116,7 @@ public Iterator iterator() { @Override public E computeNext() { if (currentIndex < count && fromIterator.hasNext()) { - E candidate = fromIterator.next(); + var candidate = fromIterator.next(); currentIndex++; return candidate; } @@ -134,7 +134,7 @@ public E computeNext() { */ @Override public Optional last() { - Iterator resultIterator = last(1).iterator(); + var resultIterator = last(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } @@ -162,25 +162,20 @@ public Iterator iterator() { public E computeNext() { initialize(); - E candidate = null; while (currentIndex < stopIndex && fromIterator.hasNext()) { currentIndex++; fromIterator.next(); } if (currentIndex >= stopIndex && fromIterator.hasNext()) { - candidate = fromIterator.next(); + return fromIterator.next(); } - return candidate; + return null; } private void initialize() { if (list == null) { list = new ArrayList<>(); - Iterator newIterator = iterable.iterator(); - while (newIterator.hasNext()) { - list.add(newIterator.next()); - } - + iterable.forEach(list::add); totalElementsCount = list.size(); stopIndex = totalElementsCount - count; } diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java index 5165ca765e37..b6a0686532ec 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java @@ -62,9 +62,9 @@ protected SimpleFluentIterable(Iterable iterable) { */ @Override public final FluentIterable filter(Predicate predicate) { - Iterator iterator = iterator(); + var iterator = iterator(); while (iterator.hasNext()) { - E nextElement = iterator.next(); + var nextElement = iterator.next(); if (!predicate.test(nextElement)) { iterator.remove(); } @@ -79,7 +79,7 @@ public final FluentIterable filter(Predicate predicate) { */ @Override public final Optional first() { - Iterator resultIterator = first(1).iterator(); + var resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } @@ -92,8 +92,8 @@ public final Optional first() { */ @Override public final FluentIterable first(int count) { - Iterator iterator = iterator(); - int currentCount = 0; + var iterator = iterator(); + var currentCount = 0; while (iterator.hasNext()) { iterator.next(); if (currentCount >= count) { @@ -111,7 +111,7 @@ public final FluentIterable first(int count) { */ @Override public final Optional last() { - List list = last(1).asList(); + var list = last(1).asList(); if (list.isEmpty()) { return Optional.empty(); } @@ -127,9 +127,9 @@ public final Optional last() { */ @Override public final FluentIterable last(int count) { - int remainingElementsCount = getRemainingElementsCount(); - Iterator iterator = iterator(); - int currentIndex = 0; + var remainingElementsCount = getRemainingElementsCount(); + var iterator = iterator(); + var currentIndex = 0; while (iterator.hasNext()) { iterator.next(); if (currentIndex < remainingElementsCount - count) { @@ -150,11 +150,8 @@ public final FluentIterable last(int count) { */ @Override public final FluentIterable map(Function function) { - List temporaryList = new ArrayList<>(); - Iterator iterator = iterator(); - while (iterator.hasNext()) { - temporaryList.add(function.apply(iterator.next())); - } + var temporaryList = new ArrayList(); + this.forEach(e -> temporaryList.add(function.apply(e))); return from(temporaryList); } @@ -178,7 +175,7 @@ public static FluentIterable from(Iterable iterable) { } public static FluentIterable fromCopyOf(Iterable iterable) { - List copy = FluentIterable.copyToList(iterable); + var copy = FluentIterable.copyToList(iterable); return new SimpleFluentIterable<>(copy); } @@ -204,10 +201,8 @@ public Spliterator spliterator() { * @return the count of remaining objects of the current Iterable */ public final int getRemainingElementsCount() { - int counter = 0; - Iterator iterator = iterator(); - while (iterator.hasNext()) { - iterator.next(); + var counter = 0; + for (var ignored : this) { counter++; } return counter; @@ -219,10 +214,8 @@ public final int getRemainingElementsCount() { * @return a new List with the remaining objects. */ public static List toList(Iterator iterator) { - List copy = new ArrayList<>(); - while (iterator.hasNext()) { - copy.add(iterator.next()); - } + var copy = new ArrayList(); + iterator.forEachRemaining(copy::add); return copy; } } diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java index f6543f46b3e5..6f25d841691d 100644 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java +++ b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java @@ -32,7 +32,6 @@ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java index 4ee30d3e5734..2ae69eaf84d3 100644 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java +++ b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java @@ -23,16 +23,19 @@ package com.iluwatar.fluentinterface.fluentiterable; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.Collections; import java.util.List; -import java.util.Optional; -import java.util.Spliterator; import java.util.function.Consumer; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; +import org.junit.jupiter.api.Test; /** * Date: 12/12/15 - 7:00 PM @@ -50,28 +53,28 @@ public abstract class FluentIterableTest { protected abstract FluentIterable createFluentIterable(final Iterable integers); @Test - public void testFirst() throws Exception { - final List integers = List.of(1, 2, 3, 10, 9, 8); - final Optional first = createFluentIterable(integers).first(); + public void testFirst() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var first = createFluentIterable(integers).first(); assertNotNull(first); assertTrue(first.isPresent()); assertEquals(integers.get(0), first.get()); } @Test - public void testFirstEmptyCollection() throws Exception { - final List integers = Collections.emptyList(); - final Optional first = createFluentIterable(integers).first(); + public void testFirstEmptyCollection() { + final var integers = Collections.emptyList(); + final var first = createFluentIterable(integers).first(); assertNotNull(first); assertFalse(first.isPresent()); } @Test - public void testFirstCount() throws Exception { - final List integers = List.of(1, 2, 3, 10, 9, 8); - final List first4 = createFluentIterable(integers) - .first(4) - .asList(); + public void testFirstCount() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var first4 = createFluentIterable(integers) + .first(4) + .asList(); assertNotNull(first4); assertEquals(4, first4.size()); @@ -83,11 +86,11 @@ public void testFirstCount() throws Exception { } @Test - public void testFirstCountLessItems() throws Exception { - final List integers = List.of(1, 2, 3); - final List first4 = createFluentIterable(integers) - .first(4) - .asList(); + public void testFirstCountLessItems() { + final var integers = List.of(1, 2, 3); + final var first4 = createFluentIterable(integers) + .first(4) + .asList(); assertNotNull(first4); assertEquals(3, first4.size()); @@ -98,28 +101,28 @@ public void testFirstCountLessItems() throws Exception { } @Test - public void testLast() throws Exception { - final List integers = List.of(1, 2, 3, 10, 9, 8); - final Optional last = createFluentIterable(integers).last(); + public void testLast() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var last = createFluentIterable(integers).last(); assertNotNull(last); assertTrue(last.isPresent()); assertEquals(integers.get(integers.size() - 1), last.get()); } @Test - public void testLastEmptyCollection() throws Exception { - final List integers = Collections.emptyList(); - final Optional last = createFluentIterable(integers).last(); + public void testLastEmptyCollection() { + final var integers = Collections.emptyList(); + final var last = createFluentIterable(integers).last(); assertNotNull(last); assertFalse(last.isPresent()); } @Test - public void testLastCount() throws Exception { - final List integers = List.of(1, 2, 3, 10, 9, 8); - final List last4 = createFluentIterable(integers) - .last(4) - .asList(); + public void testLastCount() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var last4 = createFluentIterable(integers) + .last(4) + .asList(); assertNotNull(last4); assertEquals(4, last4.size()); @@ -130,11 +133,11 @@ public void testLastCount() throws Exception { } @Test - public void testLastCountLessItems() throws Exception { - final List integers = List.of(1, 2, 3); - final List last4 = createFluentIterable(integers) - .last(4) - .asList(); + public void testLastCountLessItems() { + final var integers = List.of(1, 2, 3); + final var last4 = createFluentIterable(integers) + .last(4) + .asList(); assertNotNull(last4); assertEquals(3, last4.size()); @@ -145,11 +148,11 @@ public void testLastCountLessItems() throws Exception { } @Test - public void testFilter() throws Exception { - final List integers = List.of(1, 2, 3, 10, 9, 8); - final List evenItems = createFluentIterable(integers) - .filter(i -> i % 2 == 0) - .asList(); + public void testFilter() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var evenItems = createFluentIterable(integers) + .filter(i -> i % 2 == 0) + .asList(); assertNotNull(evenItems); assertEquals(3, evenItems.size()); @@ -159,11 +162,11 @@ public void testFilter() throws Exception { } @Test - public void testMap() throws Exception { - final List integers = List.of(1, 2, 3); - final List longs = createFluentIterable(integers) - .map(Integer::longValue) - .asList(); + public void testMap() { + final var integers = List.of(1, 2, 3); + final var longs = createFluentIterable(integers) + .map(Integer::longValue) + .asList(); assertNotNull(longs); assertEquals(integers.size(), longs.size()); @@ -174,7 +177,7 @@ public void testMap() throws Exception { @Test public void testForEach() { - final List integers = List.of(1, 2, 3); + final var integers = List.of(1, 2, 3); final Consumer consumer = mock(Consumer.class); createFluentIterable(integers).forEach(consumer); @@ -188,8 +191,8 @@ public void testForEach() { @Test public void testSpliterator() throws Exception { - final List integers = List.of(1, 2, 3); - final Spliterator split = createFluentIterable(integers).spliterator(); + final var integers = List.of(1, 2, 3); + final var split = createFluentIterable(integers).spliterator(); assertNotNull(split); } diff --git a/flux/pom.xml b/flux/pom.xml index 1c44d80574ec..8effd0fc941b 100644 --- a/flux/pom.xml +++ b/flux/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.flux.app.App + + + + + + + + diff --git a/flux/src/main/java/com/iluwatar/flux/app/App.java b/flux/src/main/java/com/iluwatar/flux/app/App.java index 13a16c977437..1344d9eaa101 100644 --- a/flux/src/main/java/com/iluwatar/flux/app/App.java +++ b/flux/src/main/java/com/iluwatar/flux/app/App.java @@ -54,13 +54,13 @@ public class App { public static void main(String[] args) { // initialize and wire the system - MenuStore menuStore = new MenuStore(); + var menuStore = new MenuStore(); Dispatcher.getInstance().registerStore(menuStore); - ContentStore contentStore = new ContentStore(); + var contentStore = new ContentStore(); Dispatcher.getInstance().registerStore(contentStore); - MenuView menuView = new MenuView(); + var menuView = new MenuView(); menuStore.registerView(menuView); - ContentView contentView = new ContentView(); + var contentView = new ContentView(); contentStore.registerView(contentView); // render initial view diff --git a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java index 206ef8b3fdd0..cf09ecf6866e 100644 --- a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java +++ b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java @@ -70,6 +70,6 @@ public void menuItemSelected(MenuItem menuItem) { } private void dispatchAction(Action action) { - stores.stream().forEach(store -> store.onAction(action)); + stores.forEach(store -> store.onAction(action)); } } diff --git a/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java b/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java index be2a5e419bdb..60d3faea0e2e 100644 --- a/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java +++ b/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java @@ -38,7 +38,7 @@ public class ContentStore extends Store { @Override public void onAction(Action action) { if (action.getType().equals(ActionType.CONTENT_CHANGED)) { - ContentAction contentAction = (ContentAction) action; + var contentAction = (ContentAction) action; content = contentAction.getContent(); notifyChange(); } diff --git a/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java b/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java index 4757a563e63f..819500c8a360 100644 --- a/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java +++ b/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java @@ -38,7 +38,7 @@ public class MenuStore extends Store { @Override public void onAction(Action action) { if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) { - MenuAction menuAction = (MenuAction) action; + var menuAction = (MenuAction) action; selected = menuAction.getMenuItem(); notifyChange(); } diff --git a/flux/src/main/java/com/iluwatar/flux/store/Store.java b/flux/src/main/java/com/iluwatar/flux/store/Store.java index b0fc8bac0d23..cfbdf4af54ef 100644 --- a/flux/src/main/java/com/iluwatar/flux/store/Store.java +++ b/flux/src/main/java/com/iluwatar/flux/store/Store.java @@ -42,6 +42,6 @@ public void registerView(View view) { } protected void notifyChange() { - views.stream().forEach(view -> view.storeChanged(this)); + views.forEach(view -> view.storeChanged(this)); } } diff --git a/flux/src/main/java/com/iluwatar/flux/view/ContentView.java b/flux/src/main/java/com/iluwatar/flux/view/ContentView.java index fc794d8dc6bf..b71a2c53ba38 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/ContentView.java +++ b/flux/src/main/java/com/iluwatar/flux/view/ContentView.java @@ -40,7 +40,7 @@ public class ContentView implements View { @Override public void storeChanged(Store store) { - ContentStore contentStore = (ContentStore) store; + var contentStore = (ContentStore) store; content = contentStore.getContent(); render(); } diff --git a/flux/src/main/java/com/iluwatar/flux/view/MenuView.java b/flux/src/main/java/com/iluwatar/flux/view/MenuView.java index c09d146a9298..f4cdf7a4d7de 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/MenuView.java +++ b/flux/src/main/java/com/iluwatar/flux/view/MenuView.java @@ -41,14 +41,14 @@ public class MenuView implements View { @Override public void storeChanged(Store store) { - MenuStore menuStore = (MenuStore) store; + var menuStore = (MenuStore) store; selected = menuStore.getSelected(); render(); } @Override public void render() { - for (MenuItem item : MenuItem.values()) { + for (var item : MenuItem.values()) { if (selected.equals(item)) { LOGGER.info("* {}", item); } else { diff --git a/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java b/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java index 3e047db216ca..f0f41f8ce0f7 100644 --- a/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java +++ b/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java @@ -23,11 +23,11 @@ package com.iluwatar.flux.action; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.api.Test; + /** * Date: 12/12/15 - 10:11 PM * @@ -36,9 +36,9 @@ public class ContentTest { @Test - public void testToString() throws Exception { - for (final Content content : Content.values()) { - final String toString = content.toString(); + public void testToString() { + for (final var content : Content.values()) { + final var toString = content.toString(); assertNotNull(toString); assertFalse(toString.trim().isEmpty()); } diff --git a/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java b/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java index 272c3a31b7c0..374f27daaa4c 100644 --- a/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java +++ b/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java @@ -23,11 +23,11 @@ package com.iluwatar.flux.action; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.api.Test; + /** * Date: 12/12/15 - 10:15 PM * @@ -36,9 +36,9 @@ public class MenuItemTest { @Test - public void testToString() throws Exception { - for (final MenuItem menuItem : MenuItem.values()) { - final String toString = menuItem.toString(); + public void testToString() { + for (final var menuItem : MenuItem.values()) { + final var toString = menuItem.toString(); assertNotNull(toString); assertFalse(toString.trim().isEmpty()); } diff --git a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java index f4b58a9b11cb..8916ad4de856 100644 --- a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java +++ b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java b/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java index 33ee1b69d5c5..5212a57d8396 100644 --- a/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java +++ b/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java @@ -23,6 +23,14 @@ package com.iluwatar.flux.dispatcher; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + import com.iluwatar.flux.action.Action; import com.iluwatar.flux.action.ActionType; import com.iluwatar.flux.action.Content; @@ -30,23 +38,12 @@ import com.iluwatar.flux.action.MenuAction; import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.store.Store; +import java.util.List; +import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.util.List; -import java.util.stream.Collectors; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - /** * Date: 12/12/15 - 8:22 PM * @@ -61,53 +58,56 @@ public class DispatcherTest { */ @BeforeEach public void setUp() throws Exception { - final Constructor constructor; - constructor = Dispatcher.class.getDeclaredConstructor(); + final var constructor = Dispatcher.class.getDeclaredConstructor(); constructor.setAccessible(true); - final Field field = Dispatcher.class.getDeclaredField("instance"); + final var field = Dispatcher.class.getDeclaredField("instance"); field.setAccessible(true); field.set(Dispatcher.getInstance(), constructor.newInstance()); } @Test - public void testGetInstance() throws Exception { + public void testGetInstance() { assertNotNull(Dispatcher.getInstance()); assertSame(Dispatcher.getInstance(), Dispatcher.getInstance()); } @Test - public void testMenuItemSelected() throws Exception { - final Dispatcher dispatcher = Dispatcher.getInstance(); + public void testMenuItemSelected() { + final var dispatcher = Dispatcher.getInstance(); - final Store store = mock(Store.class); + final var store = mock(Store.class); dispatcher.registerStore(store); dispatcher.menuItemSelected(MenuItem.HOME); dispatcher.menuItemSelected(MenuItem.COMPANY); // We expect 4 events, 2 menu selections and 2 content change actions - final ArgumentCaptor actionCaptor = ArgumentCaptor.forClass(Action.class); + final var actionCaptor = ArgumentCaptor.forClass(Action.class); verify(store, times(4)).onAction(actionCaptor.capture()); verifyNoMoreInteractions(store); - final List actions = actionCaptor.getAllValues(); - final List menuActions = actions.stream() - .filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED)) - .map(a -> (MenuAction) a) - .collect(Collectors.toList()); + final var actions = actionCaptor.getAllValues(); + final var menuActions = actions.stream() + .filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED)) + .map(a -> (MenuAction) a) + .collect(Collectors.toList()); - final List contentActions = actions.stream() - .filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED)) - .map(a -> (ContentAction) a) - .collect(Collectors.toList()); + final var contentActions = actions.stream() + .filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED)) + .map(a -> (ContentAction) a) + .collect(Collectors.toList()); assertEquals(2, menuActions.size()); - assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals).count()); - assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.COMPANY::equals).count()); + assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals) + .count()); + assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem) + .filter(MenuItem.COMPANY::equals).count()); assertEquals(2, contentActions.size()); - assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.PRODUCTS::equals).count()); - assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.COMPANY::equals).count()); + assertEquals(1, contentActions.stream().map(ContentAction::getContent) + .filter(Content.PRODUCTS::equals).count()); + assertEquals(1, contentActions.stream().map(ContentAction::getContent) + .filter(Content.COMPANY::equals).count()); } diff --git a/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java b/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java index 5bb35a2f258c..cca59a5ab008 100644 --- a/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java +++ b/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java @@ -23,20 +23,20 @@ package com.iluwatar.flux.store; -import com.iluwatar.flux.action.Content; -import com.iluwatar.flux.action.ContentAction; -import com.iluwatar.flux.action.MenuAction; -import com.iluwatar.flux.action.MenuItem; -import com.iluwatar.flux.view.View; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.action.ContentAction; +import com.iluwatar.flux.action.MenuAction; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.view.View; +import org.junit.jupiter.api.Test; /** * Date: 12/12/15 - 10:18 PM @@ -46,10 +46,10 @@ public class ContentStoreTest { @Test - public void testOnAction() throws Exception { - final ContentStore contentStore = new ContentStore(); + public void testOnAction() { + final var contentStore = new ContentStore(); - final View view = mock(View.class); + final var view = mock(View.class); contentStore.registerView(view); verifyZeroInteractions(view); diff --git a/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java b/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java index 8085326c86a9..24a05f48659a 100644 --- a/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java +++ b/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java @@ -23,20 +23,20 @@ package com.iluwatar.flux.store; -import com.iluwatar.flux.action.Content; -import com.iluwatar.flux.action.ContentAction; -import com.iluwatar.flux.action.MenuAction; -import com.iluwatar.flux.action.MenuItem; -import com.iluwatar.flux.view.View; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.action.ContentAction; +import com.iluwatar.flux.action.MenuAction; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.view.View; +import org.junit.jupiter.api.Test; /** * Date: 12/12/15 - 10:18 PM @@ -46,10 +46,10 @@ public class MenuStoreTest { @Test - public void testOnAction() throws Exception { - final MenuStore menuStore = new MenuStore(); + public void testOnAction() { + final var menuStore = new MenuStore(); - final View view = mock(View.class); + final var view = mock(View.class); menuStore.registerView(view); verifyZeroInteractions(view); diff --git a/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java b/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java index fe6b46618a6d..15ffc48d0bbd 100644 --- a/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java +++ b/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java @@ -23,15 +23,15 @@ package com.iluwatar.flux.view; -import com.iluwatar.flux.action.Content; -import com.iluwatar.flux.store.ContentStore; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.store.ContentStore; +import org.junit.jupiter.api.Test; /** * Date: 12/12/15 - 10:31 PM @@ -41,11 +41,11 @@ public class ContentViewTest { @Test - public void testStoreChanged() throws Exception { - final ContentStore store = mock(ContentStore.class); + public void testStoreChanged() { + final var store = mock(ContentStore.class); when(store.getContent()).thenReturn(Content.PRODUCTS); - final ContentView view = new ContentView(); + final var view = new ContentView(); view.storeChanged(store); verify(store, times(1)).getContent(); diff --git a/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java b/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java index 4383c0063fb6..2efe0ba025ae 100644 --- a/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java +++ b/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java @@ -23,13 +23,6 @@ package com.iluwatar.flux.view; -import com.iluwatar.flux.action.Action; -import com.iluwatar.flux.action.MenuItem; -import com.iluwatar.flux.dispatcher.Dispatcher; -import com.iluwatar.flux.store.MenuStore; -import com.iluwatar.flux.store.Store; -import org.junit.jupiter.api.Test; - import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -37,6 +30,13 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import com.iluwatar.flux.action.Action; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.dispatcher.Dispatcher; +import com.iluwatar.flux.store.MenuStore; +import com.iluwatar.flux.store.Store; +import org.junit.jupiter.api.Test; + /** * Date: 12/12/15 - 10:31 PM * @@ -45,11 +45,11 @@ public class MenuViewTest { @Test - public void testStoreChanged() throws Exception { - final MenuStore store = mock(MenuStore.class); + public void testStoreChanged() { + final var store = mock(MenuStore.class); when(store.getSelected()).thenReturn(MenuItem.HOME); - final MenuView view = new MenuView(); + final var view = new MenuView(); view.storeChanged(store); verify(store, times(1)).getSelected(); @@ -57,11 +57,11 @@ public void testStoreChanged() throws Exception { } @Test - public void testItemClicked() throws Exception { - final Store store = mock(Store.class); + public void testItemClicked() { + final var store = mock(Store.class); Dispatcher.getInstance().registerStore(store); - final MenuView view = new MenuView(); + final var view = new MenuView(); view.itemClicked(MenuItem.PRODUCTS); // We should receive a menu click action and a content changed action diff --git a/flyweight/README.md b/flyweight/README.md index 4847b828505b..a263cc438a7e 100644 --- a/flyweight/README.md +++ b/flyweight/README.md @@ -72,7 +72,7 @@ public class PotionFactory { } Potion createPotion(PotionType type) { - Potion potion = potions.get(type); + var potion = potions.get(type); if (potion == null) { switch (type) { case HEALING: @@ -99,7 +99,7 @@ public class PotionFactory { And it can be used as below ```java -PotionFactory factory = new PotionFactory(); +var factory = new PotionFactory(); factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818) factory.createPotion(PotionType.HEALING).drink(); // You feel healed. (Potion=648129364) factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818) diff --git a/flyweight/pom.xml b/flyweight/pom.xml index a17b43dcd572..f3a8082b5afb 100644 --- a/flyweight/pom.xml +++ b/flyweight/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.flyweight.App + + + + + + + + diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java index e99cfc8078a8..4fa7312e56c1 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java @@ -23,7 +23,6 @@ package com.iluwatar.flyweight; -import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,7 +41,7 @@ public class AlchemistShop { * Constructor. */ public AlchemistShop() { - PotionFactory factory = new PotionFactory(); + var factory = new PotionFactory(); topShelf = List.of( factory.createPotion(PotionType.INVISIBILITY), factory.createPotion(PotionType.INVISIBILITY), @@ -68,7 +67,7 @@ public AlchemistShop() { * @return The top shelf potions */ public final List getTopShelf() { - return Collections.unmodifiableList(this.topShelf); + return List.copyOf(this.topShelf); } /** @@ -77,24 +76,16 @@ public final List getTopShelf() { * @return The bottom shelf potions */ public final List getBottomShelf() { - return Collections.unmodifiableList(this.bottomShelf); + return List.copyOf(this.bottomShelf); } /** * Enumerate potions. */ public void enumerate() { - LOGGER.info("Enumerating top shelf potions\n"); - - for (Potion p : topShelf) { - p.drink(); - } - + topShelf.forEach(Potion::drink); LOGGER.info("Enumerating bottom shelf potions\n"); - - for (Potion p : bottomShelf) { - p.drink(); - } + bottomShelf.forEach(Potion::drink); } } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/App.java b/flyweight/src/main/java/com/iluwatar/flyweight/App.java index cbea6b9cc97b..8f5ff8742030 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/App.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/App.java @@ -43,7 +43,7 @@ public class App { * @param args command line args */ public static void main(String[] args) { - AlchemistShop alchemistShop = new AlchemistShop(); + var alchemistShop = new AlchemistShop(); alchemistShop.enumerate(); } } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java index 19edf0e21502..a731c03590fb 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java @@ -40,7 +40,7 @@ public PotionFactory() { } Potion createPotion(PotionType type) { - Potion potion = potions.get(type); + var potion = potions.get(type); if (potion == null) { switch (type) { case HEALING: diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java index 16374efb2f95..50053dddf65c 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java @@ -23,14 +23,12 @@ package com.iluwatar.flyweight; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.util.ArrayList; +import org.junit.jupiter.api.Test; + /** * Date: 12/12/15 - 10:54 PM * @@ -39,18 +37,18 @@ public class AlchemistShopTest { @Test - public void testShop() throws Exception { - final AlchemistShop shop = new AlchemistShop(); + public void testShop() { + final var shop = new AlchemistShop(); - final List bottomShelf = shop.getBottomShelf(); + final var bottomShelf = shop.getBottomShelf(); assertNotNull(bottomShelf); assertEquals(5, bottomShelf.size()); - final List topShelf = shop.getTopShelf(); + final var topShelf = shop.getTopShelf(); assertNotNull(topShelf); assertEquals(8, topShelf.size()); - final List allPotions = new ArrayList<>(); + final var allPotions = new ArrayList(); allPotions.addAll(topShelf); allPotions.addAll(bottomShelf); diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java index 8beff17235b5..3d81a6db2e7b 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/front-controller/pom.xml b/front-controller/pom.xml index de0f084a9aa2..34dabc18200f 100644 --- a/front-controller/pom.xml +++ b/front-controller/pom.xml @@ -50,4 +50,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.front.controller.App + + + + + + + + diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/App.java b/front-controller/src/main/java/com/iluwatar/front/controller/App.java index 7388a06f80d1..d1a77887f7f2 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/App.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/App.java @@ -47,7 +47,7 @@ public class App { * @param args command line args */ public static void main(String[] args) { - FrontController controller = new FrontController(); + var controller = new FrontController(); controller.handleRequest("Archer"); controller.handleRequest("Catapult"); controller.handleRequest("foobar"); diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java b/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java index 91535f9e04d6..acdb7b1c8f35 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java @@ -30,12 +30,12 @@ public class FrontController { public void handleRequest(String request) { - Command command = getCommand(request); + var command = getCommand(request); command.process(); } private Command getCommand(String request) { - Class commandClass = getCommandClass(request); + var commandClass = getCommandClass(request); try { return (Command) commandClass.newInstance(); } catch (Exception e) { @@ -44,12 +44,10 @@ private Command getCommand(String request) { } private static Class getCommandClass(String request) { - Class result; try { - result = Class.forName("com.iluwatar.front.controller." + request + "Command"); + return Class.forName("com.iluwatar.front.controller." + request + "Command"); } catch (ClassNotFoundException e) { - result = UnknownCommand.class; + return UnknownCommand.class; } - return result; } } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java index c77da640dbd7..2ea58c6a6da2 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java index 085c317555a4..165d13f44f0d 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java @@ -36,7 +36,7 @@ public class ApplicationExceptionTest { @Test public void testCause() { - final Exception cause = new Exception(); + final var cause = new Exception(); assertSame(cause, new ApplicationException(cause).getCause()); } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java index 82cd4c0da699..46a3ae94b5a1 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java @@ -23,17 +23,15 @@ package com.iluwatar.front.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.front.controller.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Date: 12/13/15 - 1:39 PM * @@ -54,11 +52,11 @@ public void tearDown() { } static List dataProvider() { - final List parameters = new ArrayList<>(); - parameters.add(new Object[]{"Archer", "Displaying archers"}); - parameters.add(new Object[]{"Catapult", "Displaying catapults"}); - parameters.add(new Object[]{"NonExistentCommand", "Error 500"}); - return parameters; + return List.of( + new Object[]{"Archer", "Displaying archers"}, + new Object[]{"Catapult", "Displaying catapults"}, + new Object[]{"NonExistentCommand", "Error 500"} + ); } /** @@ -68,7 +66,7 @@ static List dataProvider() { @ParameterizedTest @MethodSource("dataProvider") public void testDisplay(String request, String displayMessage) { - final FrontController frontController = new FrontController(); + final var frontController = new FrontController(); assertEquals(0, appender.getLogSize()); frontController.handleRequest(request); assertEquals(displayMessage, appender.getLastMessage()); diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java index e1701892b24c..eac3ae3bc845 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java @@ -23,17 +23,15 @@ package com.iluwatar.front.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.front.controller.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Date: 12/13/15 - 1:39 PM * @@ -54,11 +52,11 @@ public void tearDown() { } static List dataProvider() { - final List parameters = new ArrayList<>(); - parameters.add(new Object[]{new ArcherCommand(), "Displaying archers"}); - parameters.add(new Object[]{new CatapultCommand(), "Displaying catapults"}); - parameters.add(new Object[]{new UnknownCommand(), "Error 500"}); - return parameters; + return List.of( + new Object[]{new ArcherCommand(), "Displaying archers"}, + new Object[]{new CatapultCommand(), "Displaying catapults"}, + new Object[]{new UnknownCommand(), "Error 500"} + ); } /** diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java index 3d954a129f1c..6839d4ad0096 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java @@ -23,17 +23,15 @@ package com.iluwatar.front.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.front.controller.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Date: 12/13/15 - 1:39 PM * @@ -54,11 +52,11 @@ public void tearDown() { } static List dataProvider() { - final List parameters = new ArrayList<>(); - parameters.add(new Object[]{new ArcherView(), "Displaying archers"}); - parameters.add(new Object[]{new CatapultView(), "Displaying catapults"}); - parameters.add(new Object[]{new ErrorView(), "Error 500"}); - return parameters; + return List.of( + new Object[]{new ArcherView(), "Displaying archers"}, + new Object[]{new CatapultView(), "Displaying catapults"}, + new Object[]{new ErrorView(), "Error 500"} + ); } /** diff --git a/game-loop/pom.xml b/game-loop/pom.xml index da5c2bb09bc0..2c290827141c 100644 --- a/game-loop/pom.xml +++ b/game-loop/pom.xml @@ -40,6 +40,24 @@ junit - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.gameloop.App + + + + + + + + \ No newline at end of file diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java index 47410382203e..cbb456ccf5d5 100644 --- a/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java @@ -70,7 +70,7 @@ public void stop() { * @return {@code true} if the game is running. */ public boolean isGameRunning() { - return status == GameStatus.RUNNING ? true : false; + return status == GameStatus.RUNNING; } /** @@ -80,7 +80,7 @@ public boolean isGameRunning() { */ protected void processInput() { try { - int lag = new Random().nextInt(200) + 50; + var lag = new Random().nextInt(200) + 50; Thread.sleep(lag); } catch (InterruptedException e) { logger.error(e.getMessage()); diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java index 187fe1537c97..447e4f411faa 100644 --- a/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java +++ b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java @@ -32,8 +32,7 @@ public class AppTest { @Test public void testMain() { - String[] args = {}; - new App().main(args); + new App().main(new String[]{}); } } diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java index 61e2a3bb6ce0..4873cfd47ff0 100644 --- a/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java +++ b/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java @@ -65,7 +65,7 @@ public void testStop() { @Test public void testIsGameRunning() { - Assert.assertEquals(false, gameLoop.isGameRunning()); + Assert.assertFalse(gameLoop.isGameRunning()); } } diff --git a/guarded-suspension/pom.xml b/guarded-suspension/pom.xml index bc1dec09eedc..791c696c158a 100644 --- a/guarded-suspension/pom.xml +++ b/guarded-suspension/pom.xml @@ -41,4 +41,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.guarded.suspension.App + + + + + + + + diff --git a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java index 7c9bc1429c4b..7e300575d2f3 100644 --- a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java +++ b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java @@ -23,7 +23,6 @@ package com.iluwatar.guarded.suspension; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -45,14 +44,11 @@ public class App { * @param args - command line args */ public static void main(String[] args) { - GuardedQueue guardedQueue = new GuardedQueue(); - ExecutorService executorService = Executors.newFixedThreadPool(3); + var guardedQueue = new GuardedQueue(); + var executorService = Executors.newFixedThreadPool(3); //here we create first thread which is supposed to get from guardedQueue - executorService.execute(() -> { - guardedQueue.get(); - } - ); + executorService.execute(guardedQueue::get); // here we wait two seconds to show that the thread which is trying // to get from guardedQueue will be waiting @@ -63,10 +59,7 @@ public static void main(String[] args) { } // now we execute second thread which will put number to guardedQueue // and notify first thread that it could get - executorService.execute(() -> { - guardedQueue.put(20); - } - ); + executorService.execute(() -> guardedQueue.put(20)); executorService.shutdown(); try { executorService.awaitTermination(30, TimeUnit.SECONDS); diff --git a/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java b/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java index 0cd3588222ba..38d451ced9e3 100644 --- a/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java +++ b/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java @@ -23,13 +23,11 @@ package com.iluwatar.guarded.suspension; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * Test for Guarded Queue @@ -39,8 +37,8 @@ public class GuardedQueueTest { @Test public void testGet() { - GuardedQueue g = new GuardedQueue(); - ExecutorService executorService = Executors.newFixedThreadPool(2); + var g = new GuardedQueue(); + var executorService = Executors.newFixedThreadPool(2); executorService.submit(() -> value = g.get()); executorService.submit(() -> g.put(10)); executorService.shutdown(); @@ -54,7 +52,7 @@ public void testGet() { @Test public void testPut() { - GuardedQueue g = new GuardedQueue(); + var g = new GuardedQueue(); g.put(12); assertEquals(Integer.valueOf(12), g.get()); } diff --git a/half-sync-half-async/pom.xml b/half-sync-half-async/pom.xml index 3e86d3a173b2..fdb37edb0106 100644 --- a/half-sync-half-async/pom.xml +++ b/half-sync-half-async/pom.xml @@ -49,4 +49,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.halfsynchalfasync.App + + + + + + + + diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java index c559fca59411..7df2264ab135 100644 --- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java +++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java @@ -70,7 +70,7 @@ public class App { * @param args command line args */ public static void main(String[] args) { - AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); + var service = new AsynchronousService(new LinkedBlockingQueue<>()); /* * A new task to calculate sum is received but as this is main thread, it should not block. So * it passes it to the asynchronous task layer to compute and proceeds with handling other diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java index d0526085afb6..b3cf4839b14f 100644 --- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java +++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java @@ -25,12 +25,8 @@ import org.junit.jupiter.api.Test; -import java.util.concurrent.ExecutionException; - /** - * * Application test - * */ public class AppTest { diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java index f8974bf1c327..91f9f9e2d44a 100644 --- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java +++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java @@ -57,13 +57,13 @@ public void setUp() { @Test public void testPerfectExecution() throws Exception { - final Object result = new Object(); + final var result = new Object(); when(task.call()).thenReturn(result); service.execute(task); verify(task, timeout(2000)).onPostCall(eq(result)); - final InOrder inOrder = inOrder(task); + final var inOrder = inOrder(task); inOrder.verify(task, times(1)).onPreCall(); inOrder.verify(task, times(1)).call(); inOrder.verify(task, times(1)).onPostCall(eq(result)); @@ -73,13 +73,13 @@ public void testPerfectExecution() throws Exception { @Test public void testCallException() throws Exception { - final IOException exception = new IOException(); + final var exception = new IOException(); when(task.call()).thenThrow(exception); service.execute(task); verify(task, timeout(2000)).onError(eq(exception)); - final InOrder inOrder = inOrder(task); + final var inOrder = inOrder(task); inOrder.verify(task, times(1)).onPreCall(); inOrder.verify(task, times(1)).call(); inOrder.verify(task, times(1)).onError(exception); @@ -89,13 +89,13 @@ public void testCallException() throws Exception { @Test public void testPreCallException() { - final IllegalStateException exception = new IllegalStateException(); + final var exception = new IllegalStateException(); doThrow(exception).when(task).onPreCall(); service.execute(task); verify(task, timeout(2000)).onError(eq(exception)); - final InOrder inOrder = inOrder(task); + final var inOrder = inOrder(task); inOrder.verify(task, times(1)).onPreCall(); inOrder.verify(task, times(1)).onError(exception); diff --git a/hexagonal/pom.xml b/hexagonal/pom.xml index 324b9c8b8bf6..4873d0ddb238 100644 --- a/hexagonal/pom.xml +++ b/hexagonal/pom.xml @@ -48,4 +48,23 @@ mongo-java-driver + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.hexagonal.App + + + + + + + + diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java index 4255b3359283..1733ea2ea9f6 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java @@ -24,7 +24,6 @@ package com.iluwatar.hexagonal; import com.google.inject.Guice; -import com.google.inject.Injector; import com.iluwatar.hexagonal.domain.LotteryAdministration; import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.module.LotteryTestingModule; @@ -63,14 +62,14 @@ public class App { */ public static void main(String[] args) { - Injector injector = Guice.createInjector(new LotteryTestingModule()); + var injector = Guice.createInjector(new LotteryTestingModule()); // start new lottery round - LotteryAdministration administration = injector.getInstance(LotteryAdministration.class); + var administration = injector.getInstance(LotteryAdministration.class); administration.resetLottery(); // submit some lottery tickets - LotteryService service = injector.getInstance(LotteryService.class); + var service = injector.getInstance(LotteryService.class); SampleData.submitTickets(service, 20); // perform lottery diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java index ca61b7649c5b..4a62d2d906d9 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java @@ -24,7 +24,6 @@ package com.iluwatar.hexagonal.administration; import com.google.inject.Guice; -import com.google.inject.Injector; import com.iluwatar.hexagonal.domain.LotteryAdministration; import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.module.LotteryModule; @@ -46,17 +45,16 @@ public class ConsoleAdministration { */ public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); - Injector injector = Guice.createInjector(new LotteryModule()); - LotteryAdministration administration = injector.getInstance(LotteryAdministration.class); - LotteryService service = injector.getInstance(LotteryService.class); + var injector = Guice.createInjector(new LotteryModule()); + var administration = injector.getInstance(LotteryAdministration.class); + var service = injector.getInstance(LotteryService.class); SampleData.submitTickets(service, 20); - ConsoleAdministrationSrv consoleAdministration = - new ConsoleAdministrationSrvImpl(administration, LOGGER); - try (Scanner scanner = new Scanner(System.in)) { - boolean exit = false; + var consoleAdministration = new ConsoleAdministrationSrvImpl(administration, LOGGER); + try (var scanner = new Scanner(System.in)) { + var exit = false; while (!exit) { printMainMenu(); - String cmd = readString(scanner); + var cmd = readString(scanner); if ("1".equals(cmd)) { consoleAdministration.getAllSubmittedTickets(); } else if ("2".equals(cmd)) { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java index fbd00aa1f829..7de34ca15217 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java @@ -50,7 +50,7 @@ public void getAllSubmittedTickets() { @Override public void performLottery() { - LotteryNumbers numbers = administration.performLottery(); + var numbers = administration.performLottery(); logger.info("The winning numbers: {}", numbers.getNumbersAsString()); logger.info("Time to reset the database for next round, eh?"); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java index e1c720c115e5..b34da3e17bd5 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java @@ -28,7 +28,6 @@ import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; import java.util.ArrayList; -import java.util.List; import org.bson.Document; /** @@ -107,30 +106,31 @@ public MongoCollection getAccountsCollection() { @Override public void setFunds(String bankAccount, int amount) { - Document search = new Document("_id", bankAccount); - Document update = new Document("_id", bankAccount).append("funds", amount); - accountsCollection - .updateOne(search, new Document("$set", update), new UpdateOptions().upsert(true)); + var search = new Document("_id", bankAccount); + var update = new Document("_id", bankAccount).append("funds", amount); + var updateOptions = new UpdateOptions().upsert(true); + accountsCollection.updateOne(search, new Document("$set", update), updateOptions); } @Override public int getFunds(String bankAccount) { - Document search = new Document("_id", bankAccount); - List results = accountsCollection.find(search).limit(1).into(new ArrayList<>()); - if (results.size() > 0) { - return results.get(0).getInteger("funds"); - } else { - return 0; - } + return accountsCollection + .find(new Document("_id", bankAccount)) + .limit(1) + .into(new ArrayList<>()) + .stream() + .findFirst() + .map(x -> x.getInteger("funds")) + .orElse(0); } @Override public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) { - int sourceFunds = getFunds(sourceAccount); + var sourceFunds = getFunds(sourceAccount); if (sourceFunds < amount) { return false; } else { - int destFunds = getFunds(destinationAccount); + var destFunds = getFunds(destinationAccount); setFunds(sourceAccount, sourceFunds - amount); setFunds(destinationAccount, destFunds + amount); return true; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java index a580a7cf51bb..973747acc7fa 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java @@ -38,17 +38,12 @@ public class InMemoryTicketRepository implements LotteryTicketRepository { @Override public Optional findById(LotteryTicketId id) { - LotteryTicket ticket = tickets.get(id); - if (ticket == null) { - return Optional.empty(); - } else { - return Optional.of(ticket); - } + return Optional.ofNullable(tickets.get(id)); } @Override public Optional save(LotteryTicket ticket) { - LotteryTicketId id = new LotteryTicketId(); + var id = new LotteryTicketId(); tickets.put(id, ticket); return Optional.of(id); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java index 794cd363fdb6..96ab74ba36bf 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java @@ -32,11 +32,9 @@ import com.mongodb.client.MongoDatabase; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; +import java.util.function.Function; import java.util.stream.Collectors; import org.bson.Document; @@ -95,7 +93,7 @@ public void connect(String dbName, String ticketsCollectionName, } private void initCounters() { - Document doc = new Document("_id", "ticketId").append("seq", 1); + var doc = new Document("_id", "ticketId").append("seq", 1); countersCollection.insertOne(doc); } @@ -105,10 +103,10 @@ private void initCounters() { * @return next ticket id */ public int getNextId() { - Document find = new Document("_id", "ticketId"); - Document increase = new Document("seq", 1); - Document update = new Document("$inc", increase); - Document result = countersCollection.findOneAndUpdate(find, update); + var find = new Document("_id", "ticketId"); + var increase = new Document("seq", 1); + var update = new Document("$inc", increase); + var result = countersCollection.findOneAndUpdate(find, update); return result.getInteger("seq"); } @@ -132,20 +130,19 @@ public MongoCollection getCountersCollection() { @Override public Optional findById(LotteryTicketId id) { - Document find = new Document("ticketId", id.getId()); - List results = ticketsCollection.find(find).limit(1).into(new ArrayList<>()); - if (results.size() > 0) { - LotteryTicket lotteryTicket = docToTicket(results.get(0)); - return Optional.of(lotteryTicket); - } else { - return Optional.empty(); - } + return ticketsCollection + .find(new Document("ticketId", id.getId())) + .limit(1) + .into(new ArrayList<>()) + .stream() + .findFirst() + .map(this::docToTicket); } @Override public Optional save(LotteryTicket ticket) { - int ticketId = getNextId(); - Document doc = new Document("ticketId", ticketId); + var ticketId = getNextId(); + var doc = new Document("ticketId", ticketId); doc.put("email", ticket.getPlayerDetails().getEmail()); doc.put("bank", ticket.getPlayerDetails().getBankAccount()); doc.put("phone", ticket.getPlayerDetails().getPhoneNumber()); @@ -156,13 +153,12 @@ public Optional save(LotteryTicket ticket) { @Override public Map findAll() { - Map map = new HashMap<>(); - List docs = ticketsCollection.find(new Document()).into(new ArrayList<>()); - for (Document doc : docs) { - LotteryTicket lotteryTicket = docToTicket(doc); - map.put(lotteryTicket.getId(), lotteryTicket); - } - return map; + return ticketsCollection + .find(new Document()) + .into(new ArrayList<>()) + .stream() + .map(this::docToTicket) + .collect(Collectors.toMap(LotteryTicket::getId, Function.identity())); } @Override @@ -171,13 +167,13 @@ public void deleteAll() { } private LotteryTicket docToTicket(Document doc) { - PlayerDetails playerDetails = new PlayerDetails(doc.getString("email"), doc.getString("bank"), + var playerDetails = new PlayerDetails(doc.getString("email"), doc.getString("bank"), doc.getString("phone")); - Set numbers = Arrays.stream(doc.getString("numbers").split(",")) + var numbers = Arrays.stream(doc.getString("numbers").split(",")) .map(Integer::parseInt) .collect(Collectors.toSet()); - LotteryNumbers lotteryNumbers = LotteryNumbers.create(numbers); - return new LotteryTicket(new LotteryTicketId(doc - .getInteger("ticketId")), playerDetails, lotteryNumbers); + var lotteryNumbers = LotteryNumbers.create(numbers); + var ticketId = new LotteryTicketId(doc.getInteger("ticketId")); + return new LotteryTicket(ticketId, playerDetails, lotteryNumbers); } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java index b9ebff446899..b174a4372433 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java @@ -23,6 +23,9 @@ package com.iluwatar.hexagonal.domain; +import static com.iluwatar.hexagonal.domain.LotteryConstants.PRIZE_AMOUNT; +import static com.iluwatar.hexagonal.domain.LotteryConstants.SERVICE_BANK_ACCOUNT; + import com.google.inject.Inject; import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.database.LotteryTicketRepository; @@ -60,23 +63,21 @@ public Map getAllSubmittedTickets() { * Draw lottery numbers. */ public LotteryNumbers performLottery() { - LotteryNumbers numbers = LotteryNumbers.createRandom(); - Map tickets = getAllSubmittedTickets(); - for (LotteryTicketId id : tickets.keySet()) { - LotteryTicketCheckResult result = LotteryUtils.checkTicketForPrize(repository, id, numbers); - if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { - boolean transferred = wireTransfers.transferFunds(LotteryConstants.PRIZE_AMOUNT, - LotteryConstants.SERVICE_BANK_ACCOUNT, tickets.get(id).getPlayerDetails() - .getBankAccount()); - if (transferred) { - notifications - .ticketWon(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); + var numbers = LotteryNumbers.createRandom(); + var tickets = getAllSubmittedTickets(); + for (var id : tickets.keySet()) { + var lotteryTicket = tickets.get(id); + var playerDetails = lotteryTicket.getPlayerDetails(); + var playerAccount = playerDetails.getBankAccount(); + var result = LotteryUtils.checkTicketForPrize(repository, id, numbers).getResult(); + if (result == LotteryTicketCheckResult.CheckResult.WIN_PRIZE) { + if (wireTransfers.transferFunds(PRIZE_AMOUNT, SERVICE_BANK_ACCOUNT, playerAccount)) { + notifications.ticketWon(playerDetails, PRIZE_AMOUNT); } else { - notifications - .prizeError(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); + notifications.prizeError(playerDetails, PRIZE_AMOUNT); } - } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { - notifications.ticketDidNotWin(tickets.get(id).getPlayerDetails()); + } else if (result == LotteryTicketCheckResult.CheckResult.NO_PRIZE) { + notifications.ticketDidNotWin(playerDetails); } } return numbers; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java index 9dc00ec7695b..8988bba88add 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java @@ -99,9 +99,9 @@ public String getNumbersAsString() { */ private void generateRandomNumbers() { numbers.clear(); - RandomNumberGenerator generator = new RandomNumberGenerator(MIN_NUMBER, MAX_NUMBER); + var generator = new RandomNumberGenerator(MIN_NUMBER, MAX_NUMBER); while (numbers.size() < NUM_NUMBERS) { - int num = generator.nextInt(); + var num = generator.nextInt(); numbers.add(num); } } @@ -141,8 +141,8 @@ public int nextInt() { @Override public int hashCode() { - final int prime = 31; - int result = 1; + final var prime = 31; + var result = 1; result = prime * result + ((numbers == null) ? 0 : numbers.hashCode()); return result; } @@ -158,14 +158,11 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - LotteryNumbers other = (LotteryNumbers) obj; + var other = (LotteryNumbers) obj; if (numbers == null) { - if (other.numbers != null) { - return false; - } - } else if (!numbers.equals(other.numbers)) { - return false; + return other.numbers == null; + } else { + return numbers.equals(other.numbers); } - return true; } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java index 212671d77740..cfd04c45f228 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java @@ -23,6 +23,9 @@ package com.iluwatar.hexagonal.domain; +import static com.iluwatar.hexagonal.domain.LotteryConstants.SERVICE_BANK_ACCOUNT; +import static com.iluwatar.hexagonal.domain.LotteryConstants.TICKET_PRIZE; + import com.google.inject.Inject; import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.database.LotteryTicketRepository; @@ -53,15 +56,16 @@ public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifi * Submit lottery ticket to participate in the lottery. */ public Optional submitTicket(LotteryTicket ticket) { - boolean result = wireTransfers.transferFunds(LotteryConstants.TICKET_PRIZE, - ticket.getPlayerDetails().getBankAccount(), LotteryConstants.SERVICE_BANK_ACCOUNT); + var playerDetails = ticket.getPlayerDetails(); + var playerAccount = playerDetails.getBankAccount(); + var result = wireTransfers.transferFunds(TICKET_PRIZE, playerAccount, SERVICE_BANK_ACCOUNT); if (!result) { - notifications.ticketSubmitError(ticket.getPlayerDetails()); + notifications.ticketSubmitError(playerDetails); return Optional.empty(); } - Optional optional = repository.save(ticket); + var optional = repository.save(ticket); if (optional.isPresent()) { - notifications.ticketSubmitted(ticket.getPlayerDetails()); + notifications.ticketSubmitted(playerDetails); } return optional; } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java index 91c041273fbf..86a5a54878b4 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java @@ -82,8 +82,8 @@ public String toString() { @Override public int hashCode() { - final int prime = 31; - int result = 1; + final var prime = 31; + var result = 1; result = prime * result + ((lotteryNumbers == null) ? 0 : lotteryNumbers.hashCode()); result = prime * result + ((playerDetails == null) ? 0 : playerDetails.hashCode()); return result; @@ -100,7 +100,7 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - LotteryTicket other = (LotteryTicket) obj; + var other = (LotteryTicket) obj; if (lotteryNumbers == null) { if (other.lotteryNumbers != null) { return false; @@ -109,12 +109,9 @@ public boolean equals(Object obj) { return false; } if (playerDetails == null) { - if (other.playerDetails != null) { - return false; - } - } else if (!playerDetails.equals(other.playerDetails)) { - return false; + return other.playerDetails == null; + } else { + return playerDetails.equals(other.playerDetails); } - return true; } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java index c7f07c1df960..640300b62de0 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java @@ -76,8 +76,8 @@ public int getPrizeAmount() { @Override public int hashCode() { - final int prime = 31; - int result = 1; + final var prime = 31; + var result = 1; result = prime * result + ((checkResult == null) ? 0 : checkResult.hashCode()); result = prime * result + prizeAmount; return result; @@ -94,7 +94,7 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - LotteryTicketCheckResult other = (LotteryTicketCheckResult) obj; + var other = (LotteryTicketCheckResult) obj; return checkResult == other.checkResult && prizeAmount == other.prizeAmount; } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java index d4c036ece127..dfa3244498f8 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java @@ -59,10 +59,9 @@ public boolean equals(Object o) { return false; } - LotteryTicketId that = (LotteryTicketId) o; + var that = (LotteryTicketId) o; return id == that.id; - } @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java index 84f9af9e8b3c..ce7cc8aefead 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java @@ -25,7 +25,6 @@ import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; -import java.util.Optional; /** * Lottery utilities. @@ -43,7 +42,7 @@ public static LotteryTicketCheckResult checkTicketForPrize( LotteryTicketId id, LotteryNumbers winningNumbers ) { - Optional optional = repository.findById(id); + var optional = repository.findById(id); if (optional.isPresent()) { if (optional.get().getNumbers().equals(winningNumbers)) { return new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 1000); diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java index f2c09744c178..70a2aa452176 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java @@ -77,8 +77,8 @@ public String toString() { @Override public int hashCode() { - final int prime = 31; - int result = 1; + final var prime = 31; + var result = 1; result = prime * result + ((bankAccountNumber == null) ? 0 : bankAccountNumber.hashCode()); result = prime * result + ((emailAddress == null) ? 0 : emailAddress.hashCode()); result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode()); @@ -96,7 +96,7 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - PlayerDetails other = (PlayerDetails) obj; + var other = (PlayerDetails) obj; if (bankAccountNumber == null) { if (other.bankAccountNumber != null) { return false; @@ -112,12 +112,9 @@ public boolean equals(Object obj) { return false; } if (phoneNumber == null) { - if (other.phoneNumber != null) { - return false; - } - } else if (!phoneNumber.equals(other.phoneNumber)) { - return false; + return other.phoneNumber == null; + } else { + return phoneNumber.equals(other.phoneNumber); } - return true; } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java index f979506e4e3f..ba46f2d9745d 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java @@ -107,7 +107,7 @@ public MongoCollection getEventsCollection() { @Override public void ticketSubmitted(PlayerDetails details) { - Document document = new Document("email", details.getEmail()); + var document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document @@ -118,7 +118,7 @@ public void ticketSubmitted(PlayerDetails details) { @Override public void ticketSubmitError(PlayerDetails details) { - Document document = new Document("email", details.getEmail()); + var document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document.put("message", "Lottery ticket could not be submitted because lack of funds."); @@ -128,7 +128,7 @@ public void ticketSubmitError(PlayerDetails details) { @Override public void ticketDidNotWin(PlayerDetails details) { - Document document = new Document("email", details.getEmail()); + var document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document.put("message", "Lottery ticket was checked and unfortunately did not win this time."); @@ -138,7 +138,7 @@ public void ticketDidNotWin(PlayerDetails details) { @Override public void ticketWon(PlayerDetails details, int prizeAmount) { - Document document = new Document("email", details.getEmail()); + var document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document.put("message", String @@ -150,7 +150,7 @@ public void ticketWon(PlayerDetails details, int prizeAmount) { @Override public void prizeError(PlayerDetails details, int prizeAmount) { - Document document = new Document("email", details.getEmail()); + var document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); document.put("message", String diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java index 284fc4d1cccd..474ab980e9b8 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java @@ -42,9 +42,8 @@ public void ticketSubmitted(PlayerDetails details) { @Override public void ticketDidNotWin(PlayerDetails details) { - LOGGER - .info("Lottery ticket for {} was checked and unfortunately did not win this time.", details - .getEmail()); + LOGGER.info("Lottery ticket for {} was checked and unfortunately did not win this time.", + details.getEmail()); } @Override @@ -55,9 +54,8 @@ public void ticketWon(PlayerDetails details, int prizeAmount) { @Override public void prizeError(PlayerDetails details, int prizeAmount) { - LOGGER - .error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of" - + " {} failed.", details.getEmail(), prizeAmount); + LOGGER.error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of" + + " {} failed.", details.getEmail(), prizeAmount); } @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java index 2d8463f7f50f..c5888cd8fbe7 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java @@ -38,12 +38,12 @@ public class MongoConnectionPropertiesLoader { * Try to load connection properties from file. Fall back to default connection properties. */ public static void load() { - String host = DEFAULT_HOST; - int port = DEFAULT_PORT; - String path = System.getProperty("hexagonal.properties.path"); - Properties properties = new Properties(); + var host = DEFAULT_HOST; + var port = DEFAULT_PORT; + var path = System.getProperty("hexagonal.properties.path"); + var properties = new Properties(); if (path != null) { - try (FileInputStream fin = new FileInputStream(path)) { + try (var fin = new FileInputStream(path)) { properties.load(fin); host = properties.getProperty("mongo-host"); port = Integer.parseInt(properties.getProperty("mongo-port")); diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java index ccda4a2086c0..42e49713d497 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java @@ -30,8 +30,10 @@ import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; +import java.util.AbstractMap.SimpleEntry; import java.util.List; import java.util.Random; +import java.util.stream.Collectors; /** * Utilities for creating sample lottery tickets. @@ -83,26 +85,28 @@ public class SampleData { new PlayerDetails("xavier@google.com", "143-947", "+375245"), new PlayerDetails("harriet@google.com", "842-404", "+131243252") ); - InMemoryBank wireTransfers = new InMemoryBank(); - for (PlayerDetails player : PLAYERS) { - wireTransfers.setFunds(player.getBankAccount(), - RANDOM.nextInt(LotteryConstants.PLAYER_MAX_BALANCE)); - } + var wireTransfers = new InMemoryBank(); + PLAYERS.stream() + .map(PlayerDetails::getBankAccount) + .map(e -> new SimpleEntry<>(e, RANDOM.nextInt(LotteryConstants.PLAYER_MAX_BALANCE))) + .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)) + .forEach(wireTransfers::setFunds); } /** * Inserts lottery tickets into the database based on the sample data. */ public static void submitTickets(LotteryService lotteryService, int numTickets) { - for (int i = 0; i < numTickets; i++) { - LotteryTicket ticket = new LotteryTicket(new LotteryTicketId(), - getRandomPlayerDetails(), LotteryNumbers.createRandom()); + for (var i = 0; i < numTickets; i++) { + var randomPlayerDetails = getRandomPlayerDetails(); + var lotteryNumbers = LotteryNumbers.createRandom(); + var lotteryTicketId = new LotteryTicketId(); + var ticket = new LotteryTicket(lotteryTicketId, randomPlayerDetails, lotteryNumbers); lotteryService.submitTicket(ticket); } } private static PlayerDetails getRandomPlayerDetails() { - int idx = RANDOM.nextInt(PLAYERS.size()); - return PLAYERS.get(idx); + return PLAYERS.get(RANDOM.nextInt(PLAYERS.size())); } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java index dccbf68ebf4b..d77204b92bd0 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java @@ -24,7 +24,6 @@ package com.iluwatar.hexagonal.service; import com.google.inject.Guice; -import com.google.inject.Injector; import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.module.LotteryModule; @@ -45,15 +44,15 @@ public class ConsoleLottery { */ public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); - Injector injector = Guice.createInjector(new LotteryModule()); - LotteryService service = injector.getInstance(LotteryService.class); - WireTransfers bank = injector.getInstance(WireTransfers.class); + var injector = Guice.createInjector(new LotteryModule()); + var service = injector.getInstance(LotteryService.class); + var bank = injector.getInstance(WireTransfers.class); try (Scanner scanner = new Scanner(System.in)) { - boolean exit = false; + var exit = false; while (!exit) { printMainMenu(); - String cmd = readString(scanner); - LotteryConsoleService lotteryConsoleService = new LotteryConsoleServiceImpl(LOGGER); + var cmd = readString(scanner); + var lotteryConsoleService = new LotteryConsoleServiceImpl(LOGGER); if ("1".equals(cmd)) { lotteryConsoleService.queryLotteryAccountFunds(bank, scanner); } else if ("2".equals(cmd)) { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java index d100dba03c83..c32ede62e371 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java @@ -31,10 +31,7 @@ import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; import java.util.Arrays; -import java.util.HashSet; -import java.util.Optional; import java.util.Scanner; -import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; @@ -55,20 +52,18 @@ public LotteryConsoleServiceImpl(Logger logger) { @Override public void checkTicket(LotteryService service, Scanner scanner) { logger.info("What is the ID of the lottery ticket?"); - String id = readString(scanner); + var id = readString(scanner); logger.info("Give the 4 comma separated winning numbers?"); - String numbers = readString(scanner); + var numbers = readString(scanner); try { - String[] parts = numbers.split(","); - Set winningNumbers = new HashSet<>(); - for (int i = 0; i < 4; i++) { - winningNumbers.add(Integer.parseInt(parts[i])); - } + var winningNumbers = Arrays.stream(numbers.split(",")) + .map(Integer::parseInt) + .limit(4) + .collect(Collectors.toSet()); - final LotteryTicketId lotteryTicketId = new LotteryTicketId(Integer.parseInt(id)); - final LotteryNumbers lotteryNumbers = LotteryNumbers.create(winningNumbers); - LotteryTicketCheckResult result = - service.checkTicketForPrize(lotteryTicketId, lotteryNumbers); + final var lotteryTicketId = new LotteryTicketId(Integer.parseInt(id)); + final var lotteryNumbers = LotteryNumbers.create(winningNumbers); + var result = service.checkTicketForPrize(lotteryTicketId, lotteryNumbers); if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { logger.info("Congratulations! The lottery ticket has won!"); @@ -85,26 +80,24 @@ public void checkTicket(LotteryService service, Scanner scanner) { @Override public void submitTicket(LotteryService service, Scanner scanner) { logger.info("What is your email address?"); - String email = readString(scanner); + var email = readString(scanner); logger.info("What is your bank account number?"); - String account = readString(scanner); + var account = readString(scanner); logger.info("What is your phone number?"); - String phone = readString(scanner); - PlayerDetails details = new PlayerDetails(email, account, phone); + var phone = readString(scanner); + var details = new PlayerDetails(email, account, phone); logger.info("Give 4 comma separated lottery numbers?"); - String numbers = readString(scanner); + var numbers = readString(scanner); try { - String[] parts = numbers.split(","); - Set chosen = Arrays.stream(parts).map(Integer::parseInt).collect(Collectors.toSet()); - LotteryNumbers lotteryNumbers = LotteryNumbers.create(chosen); - LotteryTicket lotteryTicket = - new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); - Optional id = service.submitTicket(lotteryTicket); - if (id.isPresent()) { - logger.info("Submitted lottery ticket with id: {}", id.get()); - } else { - logger.info("Failed submitting lottery ticket - please try again."); - } + var chosen = Arrays.stream(numbers.split(",")) + .map(Integer::parseInt) + .collect(Collectors.toSet()); + var lotteryNumbers = LotteryNumbers.create(chosen); + var lotteryTicket = new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); + service.submitTicket(lotteryTicket).ifPresentOrElse( + (id) -> logger.info("Submitted lottery ticket with id: {}", id), + () -> logger.info("Failed submitting lottery ticket - please try again.") + ); } catch (Exception e) { logger.info("Failed submitting lottery ticket - please try again."); } @@ -113,9 +106,9 @@ public void submitTicket(LotteryService service, Scanner scanner) { @Override public void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) { logger.info("What is the account number?"); - String account = readString(scanner); + var account = readString(scanner); logger.info("How many credits do you want to deposit?"); - String amount = readString(scanner); + var amount = readString(scanner); bank.setFunds(account, Integer.parseInt(amount)); logger.info("The account {} now has {} credits.", account, bank.getFunds(account)); } @@ -123,7 +116,7 @@ public void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) { @Override public void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner) { logger.info("What is the account number?"); - String account = readString(scanner); + var account = readString(scanner); logger.info("The account {} has {} credits.", account, bank.getFunds(account)); } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java index c3fd915bd62b..05d51a283a2e 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java @@ -32,7 +32,6 @@ class AppTest { @Test void testApp() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java index d7c511357644..5c8ca44e4569 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java @@ -23,20 +23,18 @@ package com.iluwatar.hexagonal.banking; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** - * * Tests for banking - * */ class InMemoryBankTest { private final WireTransfers bank = new InMemoryBank(); - + @Test void testInit() { assertEquals(0, bank.getFunds("foo")); diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java index 3815a7899a79..b6a7e2a37d85 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java @@ -23,14 +23,14 @@ package com.iluwatar.hexagonal.banking; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; import com.mongodb.MongoClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Tests for Mongo banking adapter */ @@ -45,7 +45,7 @@ class MongoBankTest { @BeforeEach void init() { MongoConnectionPropertiesLoader.load(); - MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), + var mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); mongoClient.dropDatabase(TEST_DB); mongoClient.close(); diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java index 065425dee8f9..d016b096633b 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java @@ -23,40 +23,34 @@ package com.iluwatar.hexagonal.database; -import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.test.LotteryTestUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** - * * Tests for {@link LotteryTicketRepository} - * */ class InMemoryTicketRepositoryTest { private final LotteryTicketRepository repository = new InMemoryTicketRepository(); - + @BeforeEach void clear() { repository.deleteAll(); } - + @Test void testCrudOperations() { - LotteryTicketRepository repository = new InMemoryTicketRepository(); + var repository = new InMemoryTicketRepository(); assertTrue(repository.findAll().isEmpty()); - LotteryTicket ticket = LotteryTestUtils.createLotteryTicket(); - Optional id = repository.save(ticket); + var ticket = LotteryTestUtils.createLotteryTicket(); + var id = repository.save(ticket); assertTrue(id.isPresent()); assertEquals(1, repository.findAll().size()); - Optional optionalTicket = repository.findById(id.get()); + var optionalTicket = repository.findById(id.get()); assertTrue(optionalTicket.isPresent()); } } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java index fb3d0c4253d2..e926e1afb2bb 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java @@ -23,6 +23,9 @@ package com.iluwatar.hexagonal.database; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.hexagonal.domain.LotteryNumbers; import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; @@ -33,11 +36,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Tests for Mongo based ticket repository */ @@ -53,7 +51,7 @@ class MongoTicketRepositoryTest { @BeforeEach void init() { MongoConnectionPropertiesLoader.load(); - MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), + var mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); mongoClient.dropDatabase(TEST_DB); mongoClient.close(); @@ -77,16 +75,16 @@ void testNextId() { @Test void testCrudOperations() { // create new lottery ticket and save it - PlayerDetails details = new PlayerDetails("foo@bar.com", "123-123", "07001234"); - LotteryNumbers random = LotteryNumbers.createRandom(); - LotteryTicket original = new LotteryTicket(new LotteryTicketId(), details, random); - Optional saved = repository.save(original); + var details = new PlayerDetails("foo@bar.com", "123-123", "07001234"); + var random = LotteryNumbers.createRandom(); + var original = new LotteryTicket(new LotteryTicketId(), details, random); + var saved = repository.save(original); assertEquals(1, repository.getTicketsCollection().count()); assertTrue(saved.isPresent()); // fetch the saved lottery ticket from database and check its contents - Optional found = repository.findById(saved.get()); + var found = repository.findById(saved.get()); assertTrue(found.isPresent()); - LotteryTicket ticket = found.get(); + var ticket = found.get(); assertEquals("foo@bar.com", ticket.getPlayerDetails().getEmail()); assertEquals("123-123", ticket.getPlayerDetails().getBankAccount()); assertEquals("07001234", ticket.getPlayerDetails().getPhoneNumber()); diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java index c17c5c1fdc39..696fd0f98770 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java @@ -23,47 +23,47 @@ package com.iluwatar.hexagonal.domain; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Set; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /** - * * Unit tests for {@link LotteryNumbers} - * */ class LotteryNumbersTest { - + @Test void testGivenNumbers() { - LotteryNumbers numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + var numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4)); assertEquals(numbers.getNumbers().size(), 4); assertTrue(numbers.getNumbers().contains(1)); assertTrue(numbers.getNumbers().contains(2)); assertTrue(numbers.getNumbers().contains(3)); assertTrue(numbers.getNumbers().contains(4)); } - + @Test void testNumbersCantBeModified() { - LotteryNumbers numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + var numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4)); assertThrows(UnsupportedOperationException.class, () -> numbers.getNumbers().add(5)); } - + @Test void testRandomNumbers() { - LotteryNumbers numbers = LotteryNumbers.createRandom(); + var numbers = LotteryNumbers.createRandom(); assertEquals(numbers.getNumbers().size(), LotteryNumbers.NUM_NUMBERS); } - + @Test void testEquals() { - LotteryNumbers numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); - LotteryNumbers numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + var numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + var numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); assertEquals(numbers1, numbers2); - LotteryNumbers numbers3 = LotteryNumbers.create(Set.of(11, 12, 13, 14)); + var numbers3 = LotteryNumbers.create(Set.of(11, 12, 13, 14)); assertNotEquals(numbers1, numbers3); } } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java index 927e2fcd19a9..6d3ba8bc579e 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java @@ -23,6 +23,10 @@ package com.iluwatar.hexagonal.domain; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; @@ -30,17 +34,12 @@ import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; import com.iluwatar.hexagonal.module.LotteryTestingModule; import com.iluwatar.hexagonal.test.LotteryTestUtils; +import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.*; - /** - * * Test the lottery system - * */ class LotteryTest { @@ -62,38 +61,38 @@ void setup() { // add funds to the test player's bank account wireTransfers.setFunds("123-12312", 100); } - + @Test void testLottery() { // admin resets the lottery administration.resetLottery(); assertEquals(0, administration.getAllSubmittedTickets().size()); - + // players submit the lottery tickets - Optional ticket1 = service.submitTicket(LotteryTestUtils.createLotteryTicket("cvt@bbb.com", + var ticket1 = service.submitTicket(LotteryTestUtils.createLotteryTicket("cvt@bbb.com", "123-12312", "+32425255", Set.of(1, 2, 3, 4))); assertTrue(ticket1.isPresent()); - Optional ticket2 = service.submitTicket(LotteryTestUtils.createLotteryTicket("ant@bac.com", + var ticket2 = service.submitTicket(LotteryTestUtils.createLotteryTicket("ant@bac.com", "123-12312", "+32423455", Set.of(11, 12, 13, 14))); assertTrue(ticket2.isPresent()); - Optional ticket3 = service.submitTicket(LotteryTestUtils.createLotteryTicket("arg@boo.com", + var ticket3 = service.submitTicket(LotteryTestUtils.createLotteryTicket("arg@boo.com", "123-12312", "+32421255", Set.of(6, 8, 13, 19))); assertTrue(ticket3.isPresent()); assertEquals(3, administration.getAllSubmittedTickets().size()); - + // perform lottery - LotteryNumbers winningNumbers = administration.performLottery(); + var winningNumbers = administration.performLottery(); // cheat a bit for testing sake, use winning numbers to submit another ticket - Optional ticket4 = service.submitTicket(LotteryTestUtils.createLotteryTicket("lucky@orb.com", + var ticket4 = service.submitTicket(LotteryTestUtils.createLotteryTicket("lucky@orb.com", "123-12312", "+12421255", winningNumbers.getNumbers())); assertTrue(ticket4.isPresent()); assertEquals(4, administration.getAllSubmittedTickets().size()); - + // check winners - Map tickets = administration.getAllSubmittedTickets(); - for (LotteryTicketId id: tickets.keySet()) { - LotteryTicketCheckResult checkResult = service.checkTicketForPrize(id, winningNumbers); + var tickets = administration.getAllSubmittedTickets(); + for (var id : tickets.keySet()) { + var checkResult = service.checkTicketForPrize(id, winningNumbers); assertNotEquals(CheckResult.TICKET_NOT_SUBMITTED, checkResult.getResult()); if (checkResult.getResult().equals(CheckResult.WIN_PRIZE)) { assertTrue(checkResult.getPrizeAmount() > 0); @@ -101,9 +100,9 @@ void testLottery() { assertEquals(0, checkResult.getPrizeAmount()); } } - + // check another ticket that has not been submitted - LotteryTicketCheckResult checkResult = service.checkTicketForPrize(new LotteryTicketId(), winningNumbers); + var checkResult = service.checkTicketForPrize(new LotteryTicketId(), winningNumbers); assertEquals(CheckResult.TICKET_NOT_SUBMITTED, checkResult.getResult()); assertEquals(0, checkResult.getPrizeAmount()); } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java index 06de817263d0..4ad872f69003 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java @@ -23,25 +23,23 @@ package com.iluwatar.hexagonal.domain; -import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; +import org.junit.jupiter.api.Test; + /** - * * Unit tests for {@link LotteryTicketCheckResult} - * */ class LotteryTicketCheckResultTest { @Test void testEquals() { - LotteryTicketCheckResult result1 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); - LotteryTicketCheckResult result2 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); + var result1 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); + var result2 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); assertEquals(result1, result2); - LotteryTicketCheckResult result3 = new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 300000); + var result3 = new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 300000); assertNotEquals(result1, result3); - } + } } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java index b60e550d23e5..e6815ea08e06 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java @@ -23,11 +23,11 @@ package com.iluwatar.hexagonal.domain; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import org.junit.jupiter.api.Test; + /** * Tests for lottery ticket id */ @@ -35,12 +35,12 @@ class LotteryTicketIdTest { @Test void testEquals() { - LotteryTicketId ticketId1 = new LotteryTicketId(); - LotteryTicketId ticketId2 = new LotteryTicketId(); - LotteryTicketId ticketId3 = new LotteryTicketId(); + var ticketId1 = new LotteryTicketId(); + var ticketId2 = new LotteryTicketId(); + var ticketId3 = new LotteryTicketId(); assertNotEquals(ticketId1, ticketId2); assertNotEquals(ticketId2, ticketId3); - LotteryTicketId ticketId4 = new LotteryTicketId(ticketId1.getId()); + var ticketId4 = new LotteryTicketId(ticketId1.getId()); assertEquals(ticketId1, ticketId4); } } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java index 6d2e371c4bd0..445bdd27c498 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java @@ -23,13 +23,12 @@ package com.iluwatar.hexagonal.domain; -import org.junit.jupiter.api.Test; - -import java.util.Set; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import java.util.Set; +import org.junit.jupiter.api.Test; + /** * Test Lottery Tickets for equality */ @@ -37,16 +36,16 @@ class LotteryTicketTest { @Test void testEquals() { - PlayerDetails details1 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); - LotteryNumbers numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); - LotteryTicket ticket1 = new LotteryTicket(new LotteryTicketId(), details1, numbers1); - PlayerDetails details2 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); - LotteryNumbers numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); - LotteryTicket ticket2 = new LotteryTicket(new LotteryTicketId(), details2, numbers2); + var details1 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); + var numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + var ticket1 = new LotteryTicket(new LotteryTicketId(), details1, numbers1); + var details2 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); + var numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + var ticket2 = new LotteryTicket(new LotteryTicketId(), details2, numbers2); assertEquals(ticket1, ticket2); - PlayerDetails details3 = new PlayerDetails("elsa@foo.bar", "1223-121212", "+49332322"); - LotteryNumbers numbers3 = LotteryNumbers.create(Set.of(1, 2, 3, 8)); - LotteryTicket ticket3 = new LotteryTicket(new LotteryTicketId(), details3, numbers3); + var details3 = new PlayerDetails("elsa@foo.bar", "1223-121212", "+49332322"); + var numbers3 = LotteryNumbers.create(Set.of(1, 2, 3, 8)); + var ticket3 = new LotteryTicket(new LotteryTicketId(), details3, numbers3); assertNotEquals(ticket1, ticket3); } } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java index 2ecc0ab03d98..ba6b5f5579d6 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java @@ -23,24 +23,22 @@ package com.iluwatar.hexagonal.domain; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import org.junit.jupiter.api.Test; + /** - * * Unit tests for {@link PlayerDetails} - * */ class PlayerDetailsTest { @Test void testEquals() { - PlayerDetails details1 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); - PlayerDetails details2 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); + var details1 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); + var details2 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); assertEquals(details1, details2); - PlayerDetails details3 = new PlayerDetails("john@foo.bar", "16412-123439", "+34323432"); + var details3 = new PlayerDetails("john@foo.bar", "16412-123439", "+34323432"); assertNotEquals(details1, details3); - } + } } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java index 63222095828c..b0c4e13832c7 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java @@ -23,6 +23,8 @@ package com.iluwatar.hexagonal.eventlog; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.hexagonal.domain.PlayerDetails; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; import com.mongodb.MongoClient; @@ -30,8 +32,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Tests for Mongo event log */ @@ -46,7 +46,7 @@ class MongoEventLogTest { @BeforeEach void init() { MongoConnectionPropertiesLoader.load(); - MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), + var mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); mongoClient.dropDatabase(TEST_DB); mongoClient.close(); @@ -60,7 +60,7 @@ void testSetup() { @Test void testFundTransfers() { - PlayerDetails playerDetails = new PlayerDetails("john@wayne.com", "000-000", "03432534543"); + var playerDetails = new PlayerDetails("john@wayne.com", "000-000", "03432534543"); mongoEventLog.prizeError(playerDetails, 1000); assertEquals(1, mongoEventLog.getEventsCollection().count()); mongoEventLog.prizeError(playerDetails, 1000); diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java index 2f02ca34e9f2..4686478d3892 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java @@ -27,13 +27,10 @@ import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; - import java.util.Set; /** - * * Utilities for lottery tests - * */ public class LotteryTestUtils { @@ -43,14 +40,14 @@ public class LotteryTestUtils { public static LotteryTicket createLotteryTicket() { return createLotteryTicket("foo@bar.com", "12231-213132", "+99324554", Set.of(1, 2, 3, 4)); } - + /** * @return lottery ticket */ public static LotteryTicket createLotteryTicket(String email, String account, String phone, - Set givenNumbers) { - PlayerDetails details = new PlayerDetails(email, account, phone); - LotteryNumbers numbers = LotteryNumbers.create(givenNumbers); + Set givenNumbers) { + var details = new PlayerDetails(email, account, phone); + var numbers = LotteryNumbers.create(givenNumbers); return new LotteryTicket(new LotteryTicketId(), details, numbers); } } diff --git a/intercepting-filter/pom.xml b/intercepting-filter/pom.xml index acc9f2268cfb..ea8597374576 100644 --- a/intercepting-filter/pom.xml +++ b/intercepting-filter/pom.xml @@ -49,4 +49,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.intercepting.filter.App + + + + + + + + diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java index 6b9a15382b8e..5f13aa7d7f53 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java @@ -33,7 +33,7 @@ public class AddressFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); + var result = super.execute(order); if (order.getAddress() == null || order.getAddress().isEmpty()) { return result + "Invalid address! "; } else { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java index b81f1e229284..db1c4830f596 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java @@ -54,14 +54,14 @@ public class App { * @param args command line args */ public static void main(String[] args) { - FilterManager filterManager = new FilterManager(); + var filterManager = new FilterManager(); filterManager.addFilter(new NameFilter()); filterManager.addFilter(new ContactFilter()); filterManager.addFilter(new AddressFilter()); filterManager.addFilter(new DepositFilter()); filterManager.addFilter(new OrderFilter()); - Client client = new Client(); + var client = new Client(); client.setFilterManager(filterManager); } } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java index 865dbbb381da..656008c10363 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java @@ -25,7 +25,8 @@ import java.awt.BorderLayout; import java.awt.GridLayout; - +import java.awt.event.ActionEvent; +import java.util.Arrays; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; @@ -65,11 +66,11 @@ public Client() { setSize(300, 300); jl = new JLabel("RUNNING..."); jtFields = new JTextField[3]; - for (int i = 0; i < 3; i++) { + for (var i = 0; i < 3; i++) { jtFields[i] = new JTextField(); } jtAreas = new JTextArea[2]; - for (int i = 0; i < 2; i++) { + for (var i = 0; i < 2; i++) { jtAreas[i] = new JTextArea(); } clearButton = new JButton("Clear"); @@ -80,7 +81,7 @@ public Client() { private void setup() { setLayout(new BorderLayout()); - JPanel panel = new JPanel(); + var panel = new JPanel(); add(jl, BorderLayout.SOUTH); add(panel, BorderLayout.CENTER); panel.setLayout(new GridLayout(6, 2)); @@ -98,21 +99,11 @@ private void setup() { panel.add(processButton); clearButton.addActionListener(e -> { - for (JTextArea i : jtAreas) { - i.setText(""); - } - for (JTextField i : jtFields) { - i.setText(""); - } + Arrays.stream(jtAreas).forEach(i -> i.setText("")); + Arrays.stream(jtFields).forEach(i -> i.setText("")); }); - processButton.addActionListener(e -> { - Order order = - new Order(jtFields[0].getText(), jtFields[1].getText(), jtAreas[0].getText(), jtFields[2] - .getText(), - jtAreas[1].getText()); - jl.setText(sendRequest(order)); - }); + processButton.addActionListener(this::actionPerformed); JRootPane rootPane = SwingUtilities.getRootPane(processButton); rootPane.setDefaultButton(processButton); @@ -126,4 +117,14 @@ public void setFilterManager(FilterManager filterManager) { public String sendRequest(Order order) { return filterManager.filterRequest(order); } + + private void actionPerformed(ActionEvent e) { + var fieldText1 = jtFields[0].getText(); + var fieldText2 = jtFields[1].getText(); + var areaText1 = jtAreas[0].getText(); + var fieldText3 = jtFields[2].getText(); + var areaText2 = jtAreas[1].getText(); + var order = new Order(fieldText1, fieldText2, areaText1, fieldText3, areaText2); + jl.setText(sendRequest(order)); + } } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java index 9acdec31966b..0e76ac1c009b 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java @@ -34,10 +34,11 @@ public class ContactFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); - if (order.getContactNumber() == null || order.getContactNumber().isEmpty() - || order.getContactNumber().matches(".*[^\\d]+.*") - || order.getContactNumber().length() != 11) { + var result = super.execute(order); + var contactNumber = order.getContactNumber(); + if (contactNumber == null || contactNumber.isEmpty() + || contactNumber.matches(".*[^\\d]+.*") + || contactNumber.length() != 11) { return result + "Invalid contact number! "; } else { return result; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java index e7457c9bec5b..da802616d5f0 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java @@ -32,8 +32,9 @@ public class DepositFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); - if (order.getDepositNumber() == null || order.getDepositNumber().isEmpty()) { + var result = super.execute(order); + var depositNumber = order.getDepositNumber(); + if (depositNumber == null || depositNumber.isEmpty()) { return result + "Invalid deposit number! "; } else { return result; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java index 95ef54fe1d82..358c9fd8501d 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java @@ -33,9 +33,9 @@ public class NameFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); - if (order.getName() == null || order.getName().isEmpty() - || order.getName().matches(".*[^\\w|\\s]+.*")) { + var result = super.execute(order); + var name = order.getName(); + if (name == null || name.isEmpty() || name.matches(".*[^\\w|\\s]+.*")) { return result + "Invalid name! "; } else { return result; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java index de91386f3f57..c555322f7288 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java @@ -32,8 +32,9 @@ public class OrderFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); - if (order.getOrderItem() == null || order.getOrderItem().isEmpty()) { + var result = super.execute(order); + var orderItem = order.getOrderItem(); + if (orderItem == null || orderItem.isEmpty()) { return result + "Invalid order! "; } else { return result; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java index 9ded355c757a..08ed715b1aa2 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java @@ -27,11 +27,10 @@ import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - +import java.util.stream.IntStream; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; -import javax.swing.JRootPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; @@ -58,9 +57,8 @@ public Target() { super("Order System"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(640, 480); - dtm = - new DefaultTableModel(new Object[]{"Name", "Contact Number", "Address", "Deposit Number", - "Order"}, 0); + dtm = new DefaultTableModel( + new Object[]{"Name", "Contact Number", "Address", "Deposit Number", "Order"}, 0); jt = new JTable(dtm); del = new JButton("Delete"); setup(); @@ -68,18 +66,18 @@ public Target() { private void setup() { setLayout(new BorderLayout()); - JPanel bot = new JPanel(); + var bot = new JPanel(); add(jt.getTableHeader(), BorderLayout.NORTH); bot.setLayout(new BorderLayout()); bot.add(del, BorderLayout.EAST); add(bot, BorderLayout.SOUTH); - JScrollPane jsp = new JScrollPane(jt); + var jsp = new JScrollPane(jt); jsp.setPreferredSize(new Dimension(500, 250)); add(jsp, BorderLayout.CENTER); del.addActionListener(new DListener()); - JRootPane rootPane = SwingUtilities.getRootPane(del); + var rootPane = SwingUtilities.getRootPane(del); rootPane.setDefaultButton(del); setVisible(true); } @@ -91,14 +89,12 @@ public void execute(String[] request) { class DListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { - int temp = jt.getSelectedRow(); + var temp = jt.getSelectedRow(); if (temp == -1) { return; } - int temp2 = jt.getSelectedRowCount(); - for (int i = 0; i < temp2; i++) { - dtm.removeRow(temp); - } + var temp2 = jt.getSelectedRowCount(); + IntStream.range(0, temp2).forEach(i -> dtm.removeRow(temp)); } } } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java index 4ee7897ed111..8fbe9f1d20c1 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test. - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java index feffbd7bef52..605db4de295b 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java @@ -23,8 +23,6 @@ package com.iluwatar.intercepting.filter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; @@ -33,6 +31,8 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; +import org.junit.jupiter.api.Test; + /** * Date: 12/13/15 - 3:01 PM * @@ -42,20 +42,20 @@ public class FilterManagerTest { @Test public void testFilterRequest() { - final Target target = mock(Target.class); - final FilterManager filterManager = new FilterManager(); + final var target = mock(Target.class); + final var filterManager = new FilterManager(); assertEquals("RUNNING...", filterManager.filterRequest(mock(Order.class))); verifyZeroInteractions(target); } @Test public void testAddFilter() { - final Target target = mock(Target.class); - final FilterManager filterManager = new FilterManager(); + final var target = mock(Target.class); + final var filterManager = new FilterManager(); verifyZeroInteractions(target); - final Filter filter = mock(Filter.class); + final var filter = mock(Filter.class); when(filter.execute(any(Order.class))).thenReturn("filter"); filterManager.addFilter(filter); diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java index 2e9a9641f165..7a0ce915019c 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java @@ -23,17 +23,15 @@ package com.iluwatar.intercepting.filter; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; +import java.util.List; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + /** * Date: 12/13/15 - 2:17 PM * @@ -41,7 +39,8 @@ */ public class FilterTest { - private static final Order PERFECT_ORDER = new Order("name", "12345678901", "addr", "dep", "order"); + private static final Order PERFECT_ORDER = + new Order("name", "12345678901", "addr", "dep", "order"); private static final Order WRONG_ORDER = new Order("name", "12345678901", "addr", "dep", ""); private static final Order WRONG_DEPOSIT = new Order("name", "12345678901", "addr", "", "order"); private static final Order WRONG_ADDRESS = new Order("name", "12345678901", "", "dep", "order"); @@ -49,49 +48,48 @@ public class FilterTest { private static final Order WRONG_NAME = new Order("", "12345678901", "addr", "dep", "order"); static List getTestData() { - final List testData = new ArrayList<>(); - testData.add(new Object[]{new NameFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new NameFilter(), WRONG_NAME, "Invalid name!"}); - testData.add(new Object[]{new NameFilter(), WRONG_CONTACT, ""}); - testData.add(new Object[]{new NameFilter(), WRONG_ADDRESS, ""}); - testData.add(new Object[]{new NameFilter(), WRONG_DEPOSIT, ""}); - testData.add(new Object[]{new NameFilter(), WRONG_ORDER, ""}); - - testData.add(new Object[]{new ContactFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new ContactFilter(), WRONG_NAME, ""}); - testData.add(new Object[]{new ContactFilter(), WRONG_CONTACT, "Invalid contact number!"}); - testData.add(new Object[]{new ContactFilter(), WRONG_ADDRESS, ""}); - testData.add(new Object[]{new ContactFilter(), WRONG_DEPOSIT, ""}); - testData.add(new Object[]{new ContactFilter(), WRONG_ORDER, ""}); + return List.of( + new Object[]{new NameFilter(), PERFECT_ORDER, ""}, + new Object[]{new NameFilter(), WRONG_NAME, "Invalid name!"}, + new Object[]{new NameFilter(), WRONG_CONTACT, ""}, + new Object[]{new NameFilter(), WRONG_ADDRESS, ""}, + new Object[]{new NameFilter(), WRONG_DEPOSIT, ""}, + new Object[]{new NameFilter(), WRONG_ORDER, ""}, - testData.add(new Object[]{new AddressFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new AddressFilter(), WRONG_NAME, ""}); - testData.add(new Object[]{new AddressFilter(), WRONG_CONTACT, ""}); - testData.add(new Object[]{new AddressFilter(), WRONG_ADDRESS, "Invalid address!"}); - testData.add(new Object[]{new AddressFilter(), WRONG_DEPOSIT, ""}); - testData.add(new Object[]{new AddressFilter(), WRONG_ORDER, ""}); + new Object[]{new ContactFilter(), PERFECT_ORDER, ""}, + new Object[]{new ContactFilter(), WRONG_NAME, ""}, + new Object[]{new ContactFilter(), WRONG_CONTACT, "Invalid contact number!"}, + new Object[]{new ContactFilter(), WRONG_ADDRESS, ""}, + new Object[]{new ContactFilter(), WRONG_DEPOSIT, ""}, + new Object[]{new ContactFilter(), WRONG_ORDER, ""}, - testData.add(new Object[]{new DepositFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new DepositFilter(), WRONG_NAME, ""}); - testData.add(new Object[]{new DepositFilter(), WRONG_CONTACT, ""}); - testData.add(new Object[]{new DepositFilter(), WRONG_ADDRESS, ""}); - testData.add(new Object[]{new DepositFilter(), WRONG_DEPOSIT, "Invalid deposit number!"}); - testData.add(new Object[]{new DepositFilter(), WRONG_ORDER, ""}); + new Object[]{new AddressFilter(), PERFECT_ORDER, ""}, + new Object[]{new AddressFilter(), WRONG_NAME, ""}, + new Object[]{new AddressFilter(), WRONG_CONTACT, ""}, + new Object[]{new AddressFilter(), WRONG_ADDRESS, "Invalid address!"}, + new Object[]{new AddressFilter(), WRONG_DEPOSIT, ""}, + new Object[]{new AddressFilter(), WRONG_ORDER, ""}, - testData.add(new Object[]{new OrderFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_NAME, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_CONTACT, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_ADDRESS, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_DEPOSIT, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_ORDER, "Invalid order!"}); + new Object[]{new DepositFilter(), PERFECT_ORDER, ""}, + new Object[]{new DepositFilter(), WRONG_NAME, ""}, + new Object[]{new DepositFilter(), WRONG_CONTACT, ""}, + new Object[]{new DepositFilter(), WRONG_ADDRESS, ""}, + new Object[]{new DepositFilter(), WRONG_DEPOSIT, "Invalid deposit number!"}, + new Object[]{new DepositFilter(), WRONG_ORDER, ""}, - return testData; + new Object[]{new OrderFilter(), PERFECT_ORDER, ""}, + new Object[]{new OrderFilter(), WRONG_NAME, ""}, + new Object[]{new OrderFilter(), WRONG_CONTACT, ""}, + new Object[]{new OrderFilter(), WRONG_ADDRESS, ""}, + new Object[]{new OrderFilter(), WRONG_DEPOSIT, ""}, + new Object[]{new OrderFilter(), WRONG_ORDER, "Invalid order!"} + ); } @ParameterizedTest @MethodSource("getTestData") public void testExecute(Filter filter, Order order, String expectedResult) { - final String result = filter.execute(order); + final var result = filter.execute(order); assertNotNull(result); assertEquals(expectedResult, result.trim()); } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java index a4862c4a828d..21643986e1ac 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java @@ -23,10 +23,10 @@ package com.iluwatar.intercepting.filter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + /** * Date: 12/13/15 - 2:57 PM * @@ -38,35 +38,35 @@ public class OrderTest { @Test public void testSetName() { - final Order order = new Order(); + final var order = new Order(); order.setName(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getName()); } @Test public void testSetContactNumber() { - final Order order = new Order(); + final var order = new Order(); order.setContactNumber(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getContactNumber()); } @Test public void testSetAddress() { - final Order order = new Order(); + final var order = new Order(); order.setAddress(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getAddress()); } @Test public void testSetDepositNumber() { - final Order order = new Order(); + final var order = new Order(); order.setDepositNumber(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getDepositNumber()); } @Test public void testSetOrder() { - final Order order = new Order(); + final var order = new Order(); order.setOrderItem(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getOrderItem()); } diff --git a/interpreter/pom.xml b/interpreter/pom.xml index 1789069f757a..118cfcdf645e 100644 --- a/interpreter/pom.xml +++ b/interpreter/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.interpreter.App + + + + + + + + diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/App.java b/interpreter/src/main/java/com/iluwatar/interpreter/App.java index d63c78506014..909c333451ae 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/App.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/App.java @@ -49,24 +49,24 @@ public class App { * @param args command line args */ public static void main(String[] args) { - String tokenString = "4 3 2 - 1 + *"; - Stack stack = new Stack<>(); + var tokenString = "4 3 2 - 1 + *"; + var stack = new Stack(); - String[] tokenList = tokenString.split(" "); - for (String s : tokenList) { + var tokenList = tokenString.split(" "); + for (var s : tokenList) { if (isOperator(s)) { - Expression rightExpression = stack.pop(); - Expression leftExpression = stack.pop(); + var rightExpression = stack.pop(); + var leftExpression = stack.pop(); LOGGER.info("popped from stack left: {} right: {}", leftExpression.interpret(), rightExpression.interpret()); - Expression operator = getOperatorInstance(s, leftExpression, rightExpression); + var operator = getOperatorInstance(s, leftExpression, rightExpression); LOGGER.info("operator: {}", operator); - int result = operator.interpret(); - NumberExpression resultExpression = new NumberExpression(result); + var result = operator.interpret(); + var resultExpression = new NumberExpression(result); stack.push(resultExpression); LOGGER.info("push result to stack: {}", resultExpression.interpret()); } else { - Expression i = new NumberExpression(s); + var i = new NumberExpression(s); stack.push(i); LOGGER.info("push to stack: {}", i.interpret()); } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java index 1bc978735354..505dc559c6ca 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java index be12e00b5d8c..85f836dabe5f 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java @@ -23,25 +23,23 @@ package com.iluwatar.interpreter; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; -import java.util.List; import java.util.function.BiFunction; import java.util.function.IntBinaryOperator; import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Date: 12/14/15 - 11:48 AM - * + *

* Test Case for Expressions + * * @param Type of Expression * @author Jeroen Meulemeester */ @@ -55,13 +53,13 @@ public abstract class ExpressionTest { * @return A stream with test entries */ static Stream prepareParameters(final IntBinaryOperator resultCalc) { - final List testData = new ArrayList<>(); - for (int i = -10; i < 10; i++) { - for (int j = -10; j < 10; j++) { + final var testData = new ArrayList(); + for (var i = -10; i < 10; i++) { + for (var j = -10; j < 10; j++) { testData.add(Arguments.of( - new NumberExpression(i), - new NumberExpression(j), - resultCalc.applyAsInt(i, j) + new NumberExpression(i), + new NumberExpression(j), + resultCalc.applyAsInt(i, j) )); } } @@ -104,7 +102,7 @@ static Stream prepareParameters(final IntBinaryOperator resultCalc) { @ParameterizedTest @MethodSource("expressionProvider") public void testInterpret(NumberExpression first, NumberExpression second, int result) { - final E expression = factory.apply(first, second); + final var expression = factory.apply(first, second); assertNotNull(expression); assertEquals(result, expression.interpret()); } @@ -115,7 +113,7 @@ public void testInterpret(NumberExpression first, NumberExpression second, int r @ParameterizedTest @MethodSource("expressionProvider") public void testToString(NumberExpression first, NumberExpression second) { - final E expression = factory.apply(first, second); + final var expression = factory.apply(first, second); assertNotNull(expression); assertEquals(expectedToString, expression.toString()); } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java index f5c51f72323d..19f74171bee4 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java @@ -23,9 +23,8 @@ package com.iluwatar.interpreter; -import org.junit.jupiter.params.provider.Arguments; - import java.util.stream.Stream; +import org.junit.jupiter.params.provider.Arguments; /** * Date: 12/14/15 - 12:08 PM diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java index 5c956beb25d2..678048e1c2bf 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java @@ -23,9 +23,8 @@ package com.iluwatar.interpreter; -import org.junit.jupiter.params.provider.Arguments; - import java.util.stream.Stream; +import org.junit.jupiter.params.provider.Arguments; /** * Date: 12/14/15 - 12:08 PM @@ -46,7 +45,6 @@ public Stream expressionProvider() { /** * Create a new test instance using the given test parameters and expected result - * */ public MultiplyExpressionTest() { super("*", MultiplyExpression::new); diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java index 593c08a9bbca..16fc0a429926 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java @@ -23,14 +23,13 @@ package com.iluwatar.interpreter; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Date: 12/14/15 - 12:08 PM * @@ -61,9 +60,9 @@ public NumberExpressionTest() { @ParameterizedTest @MethodSource("expressionProvider") public void testFromString(NumberExpression first) throws Exception { - final int expectedValue = first.interpret(); - final String testStringValue = String.valueOf(expectedValue); - final NumberExpression numberExpression = new NumberExpression(testStringValue); + final var expectedValue = first.interpret(); + final var testStringValue = String.valueOf(expectedValue); + final var numberExpression = new NumberExpression(testStringValue); assertEquals(expectedValue, numberExpression.interpret()); } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java index 7fc5efa12d77..1f53f3606b14 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java @@ -23,9 +23,8 @@ package com.iluwatar.interpreter; -import org.junit.jupiter.params.provider.Arguments; - import java.util.stream.Stream; +import org.junit.jupiter.params.provider.Arguments; /** * Date: 12/14/15 - 12:08 PM @@ -41,7 +40,7 @@ public class PlusExpressionTest extends ExpressionTest { */ @Override public Stream expressionProvider() { - return prepareParameters((f, s) -> f + s); + return prepareParameters(Integer::sum); } /** diff --git a/iterator/pom.xml b/iterator/pom.xml index a1f1b29100ec..514cedbea90e 100644 --- a/iterator/pom.xml +++ b/iterator/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.iterator.App + + + + + + + + diff --git a/iterator/src/main/java/com/iluwatar/iterator/App.java b/iterator/src/main/java/com/iluwatar/iterator/App.java index 6e72b4ae991d..b81e765beb4a 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/App.java +++ b/iterator/src/main/java/com/iluwatar/iterator/App.java @@ -30,7 +30,6 @@ import com.iluwatar.iterator.bst.BstIterator; import com.iluwatar.iterator.bst.TreeNode; -import com.iluwatar.iterator.list.Item; import com.iluwatar.iterator.list.ItemType; import com.iluwatar.iterator.list.TreasureChest; import org.slf4j.Logger; @@ -53,7 +52,7 @@ public class App { private static void demonstrateTreasureChestIteratorForType(ItemType itemType) { LOGGER.info("------------------------"); LOGGER.info("Item Iterator for ItemType " + itemType + ": "); - Iterator itemIterator = TREASURE_CHEST.iterator(itemType); + var itemIterator = TREASURE_CHEST.iterator(itemType); while (itemIterator.hasNext()) { LOGGER.info(itemIterator.next().toString()); } @@ -62,15 +61,15 @@ private static void demonstrateTreasureChestIteratorForType(ItemType itemType) { private static void demonstrateBstIterator() { LOGGER.info("------------------------"); LOGGER.info("BST Iterator: "); - TreeNode root = buildIntegerBst(); - BstIterator bstIterator = new BstIterator<>(root); + var root = buildIntegerBst(); + var bstIterator = new BstIterator(root); while (bstIterator.hasNext()) { LOGGER.info("Next node: " + bstIterator.next().getVal()); } } private static TreeNode buildIntegerBst() { - TreeNode root = new TreeNode<>(8); + var root = new TreeNode<>(8); root.insert(3); root.insert(10); diff --git a/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java b/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java index 87511c7eaad3..b3e0dc3d649b 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java +++ b/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java @@ -78,7 +78,7 @@ public TreeNode next() throws NoSuchElementException { if (pathStack.isEmpty()) { throw new NoSuchElementException(); } - TreeNode next = pathStack.pop(); + var next = pathStack.pop(); pushPathToNextSmallest(next.getRight()); return next; } diff --git a/iterator/src/main/java/com/iluwatar/iterator/bst/README.md b/iterator/src/main/java/com/iluwatar/iterator/bst/README.md index 02e8eefcb25b..816d1a4fe291 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/bst/README.md +++ b/iterator/src/main/java/com/iluwatar/iterator/bst/README.md @@ -63,7 +63,7 @@ public TreeNode next() throws IllegalStateException { if (pathStack.isEmpty()) { throw new IllegalStateException(); } - TreeNode next = pathStack.pop(); + var next = pathStack.pop(); // follow right child to next smallest node pushPathToNextSmallest(next.getRight()); return next; diff --git a/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java b/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java index 9d03fdf86743..87f16e96cc16 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java +++ b/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java @@ -72,7 +72,7 @@ private void setRight(TreeNode right) { * @param valToInsert The value to insert as a new TreeNode */ public void insert(T valToInsert) { - TreeNode parent = getParentNodeOfValueToBeInserted(valToInsert); + var parent = getParentNodeOfValueToBeInserted(valToInsert); parent.insertNewChild(valToInsert); } @@ -84,7 +84,7 @@ public void insert(T valToInsert) { */ private TreeNode getParentNodeOfValueToBeInserted(T valToInsert) { TreeNode parent = null; - TreeNode curr = this; + var curr = this; while (curr != null) { parent = curr; diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java index 43dbc82fa3b0..90461c420ffb 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java @@ -24,7 +24,6 @@ package com.iluwatar.iterator.list; import com.iluwatar.iterator.Iterator; -import java.util.List; /** * TreasureChestItemIterator. @@ -59,10 +58,9 @@ public Item next() { } private int findNextIdx() { - List items = chest.getItems(); - boolean found = false; - int tempIdx = idx; - while (!found) { + var items = chest.getItems(); + var tempIdx = idx; + while (true) { tempIdx++; if (tempIdx >= items.size()) { tempIdx = -1; diff --git a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java index 9076c5174c5e..ccb33307c9c1 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java @@ -32,7 +32,6 @@ class AppTest { @Test void testApp() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } \ No newline at end of file diff --git a/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java b/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java index e7f81e0d3f86..fba9ae8e3bbb 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java @@ -28,13 +28,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.NoSuchElementException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; -import java.util.NoSuchElementException; - @TestInstance(Lifecycle.PER_CLASS) class BstIteratorTest { @@ -55,14 +54,14 @@ void createTrees() { @Test void nextForEmptyTree() { - BstIterator iter = new BstIterator<>(emptyRoot); + var iter = new BstIterator<>(emptyRoot); assertThrows(NoSuchElementException.class, iter::next, "next() should throw an IllegalStateException if hasNext() is false."); } @Test void nextOverEntirePopulatedTree() { - BstIterator iter = new BstIterator<>(nonEmptyRoot); + var iter = new BstIterator<>(nonEmptyRoot); assertEquals(Integer.valueOf(1), iter.next().getVal(), "First Node is 1."); assertEquals(Integer.valueOf(3), iter.next().getVal(), "Second Node is 3."); assertEquals(Integer.valueOf(4), iter.next().getVal(), "Third Node is 4."); @@ -73,19 +72,19 @@ void nextOverEntirePopulatedTree() { @Test void hasNextForEmptyTree() { - BstIterator iter = new BstIterator<>(emptyRoot); + var iter = new BstIterator<>(emptyRoot); assertFalse(iter.hasNext(), "hasNext() should return false for empty tree."); } @Test void hasNextForPopulatedTree() { - BstIterator iter = new BstIterator<>(nonEmptyRoot); + var iter = new BstIterator<>(nonEmptyRoot); assertTrue(iter.hasNext(), "hasNext() should return true for populated tree."); } @Test void nextAndHasNextOverEntirePopulatedTree() { - BstIterator iter = new BstIterator<>(nonEmptyRoot); + var iter = new BstIterator<>(nonEmptyRoot); assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); assertEquals(Integer.valueOf(1), iter.next().getVal(), "First Node is 1."); assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); diff --git a/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java b/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java index 350934590e51..5e4f85e6b6f0 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java @@ -27,7 +27,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; -import com.iluwatar.iterator.Iterator; import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -46,16 +45,16 @@ public class TreasureChestTest { */ public static List dataProvider() { return List.of( - new Object[]{new Item(ItemType.POTION, "Potion of courage")}, - new Object[]{new Item(ItemType.RING, "Ring of shadows")}, - new Object[]{new Item(ItemType.POTION, "Potion of wisdom")}, - new Object[]{new Item(ItemType.POTION, "Potion of blood")}, - new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")}, - new Object[]{new Item(ItemType.POTION, "Potion of rust")}, - new Object[]{new Item(ItemType.POTION, "Potion of healing")}, - new Object[]{new Item(ItemType.RING, "Ring of armor")}, - new Object[]{new Item(ItemType.WEAPON, "Steel halberd")}, - new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")} + new Object[]{new Item(ItemType.POTION, "Potion of courage")}, + new Object[]{new Item(ItemType.RING, "Ring of shadows")}, + new Object[]{new Item(ItemType.POTION, "Potion of wisdom")}, + new Object[]{new Item(ItemType.POTION, "Potion of blood")}, + new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")}, + new Object[]{new Item(ItemType.POTION, "Potion of rust")}, + new Object[]{new Item(ItemType.POTION, "Potion of healing")}, + new Object[]{new Item(ItemType.RING, "Ring of armor")}, + new Object[]{new Item(ItemType.WEAPON, "Steel halberd")}, + new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")} ); } @@ -66,16 +65,16 @@ public static List dataProvider() { @ParameterizedTest @MethodSource("dataProvider") public void testIterator(Item expectedItem) { - final TreasureChest chest = new TreasureChest(); - final Iterator iterator = chest.iterator(expectedItem.getType()); + final var chest = new TreasureChest(); + final var iterator = chest.iterator(expectedItem.getType()); assertNotNull(iterator); while (iterator.hasNext()) { - final Item item = iterator.next(); + final var item = iterator.next(); assertNotNull(item); assertEquals(expectedItem.getType(), item.getType()); - final String name = item.toString(); + final var name = item.toString(); assertNotNull(name); if (expectedItem.toString().equals(name)) { return; @@ -93,17 +92,17 @@ public void testIterator(Item expectedItem) { @ParameterizedTest @MethodSource("dataProvider") public void testGetItems(Item expectedItem) throws Exception { - final TreasureChest chest = new TreasureChest(); - final List items = chest.getItems(); + final var chest = new TreasureChest(); + final var items = chest.getItems(); assertNotNull(items); - for (final Item item : items) { + for (final var item : items) { assertNotNull(item); assertNotNull(item.getType()); assertNotNull(item.toString()); - final boolean sameType = expectedItem.getType() == item.getType(); - final boolean sameName = expectedItem.toString().equals(item.toString()); + final var sameType = expectedItem.getType() == item.getType(); + final var sameName = expectedItem.toString().equals(item.toString()); if (sameType && sameName) { return; } diff --git a/layers/pom.xml b/layers/pom.xml index 0627fdf9b103..2ebace18b4f1 100644 --- a/layers/pom.xml +++ b/layers/pom.xml @@ -66,4 +66,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.layers.app.App + + + + + + + + diff --git a/lazy-loading/pom.xml b/lazy-loading/pom.xml index c0245aac018a..a6a5d3a4510a 100644 --- a/lazy-loading/pom.xml +++ b/lazy-loading/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.lazy.loading.App + + + + + + + + diff --git a/leader-election/pom.xml b/leader-election/pom.xml index 9e94ce32f241..8fc833f18072 100644 --- a/leader-election/pom.xml +++ b/leader-election/pom.xml @@ -40,4 +40,36 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + bully + + + + com.iluwatar.leaderelection.bully.BullyApp + + + ${project.artifactId}-Bully + + + + ring + + + + com.iluwatar.leaderelection.ring.RingApp + + + ${project.artifactId}-Ring + + + + + + \ No newline at end of file diff --git a/marker/pom.xml b/marker/pom.xml index fa794b5959da..5212832d8476 100644 --- a/marker/pom.xml +++ b/marker/pom.xml @@ -47,6 +47,23 @@ test - - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + App + + + + + + + + diff --git a/master-worker-pattern/pom.xml b/master-worker-pattern/pom.xml index 7ace130d8a9e..9924d6a5a5f0 100644 --- a/master-worker-pattern/pom.xml +++ b/master-worker-pattern/pom.xml @@ -37,4 +37,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.masterworker.App + + + + + + + + diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java index b8036b91199a..547636066a49 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java @@ -24,6 +24,11 @@ package com.iluwatar.masterworker; import com.iluwatar.masterworker.system.ArrayTransposeMasterWorker; +import com.iluwatar.masterworker.system.MasterWorker; +import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster; +import com.iluwatar.masterworker.system.systemmaster.Master; +import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker; +import com.iluwatar.masterworker.system.systemworkers.Worker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/mediator/pom.xml b/mediator/pom.xml index 2c0bfd4135b6..23d28726bdc5 100644 --- a/mediator/pom.xml +++ b/mediator/pom.xml @@ -49,4 +49,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.mediator.App + + + + + + + + diff --git a/memento/pom.xml b/memento/pom.xml index 07e4f0b839e5..70121cea3e56 100644 --- a/memento/pom.xml +++ b/memento/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.memento.App + + + + + + + + diff --git a/model-view-controller/pom.xml b/model-view-controller/pom.xml index 4759bf2d3158..a8ef230e85d6 100644 --- a/model-view-controller/pom.xml +++ b/model-view-controller/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.model.view.controller.App + + + + + + + + diff --git a/model-view-presenter/pom.xml b/model-view-presenter/pom.xml index 21ba3f14c56d..97b47f82c361 100644 --- a/model-view-presenter/pom.xml +++ b/model-view-presenter/pom.xml @@ -46,4 +46,23 @@ 1.0.2 + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.model.view.presenter.App + + + + + + + + diff --git a/module/pom.xml b/module/pom.xml index d30353070a15..25ad707ebc20 100644 --- a/module/pom.xml +++ b/module/pom.xml @@ -38,4 +38,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.module.App + + + + + + + + diff --git a/monad/pom.xml b/monad/pom.xml index 868cc871059b..f553c3079767 100644 --- a/monad/pom.xml +++ b/monad/pom.xml @@ -39,5 +39,24 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.monostate.App + + + + + + + + diff --git a/multiton/pom.xml b/multiton/pom.xml index 39deb9e4dcbe..ef1e9c8921a9 100644 --- a/multiton/pom.xml +++ b/multiton/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.multiton.App + + + + + + + + diff --git a/mute-idiom/pom.xml b/mute-idiom/pom.xml index 91f5063a7a0e..a32f6a3ea2fa 100644 --- a/mute-idiom/pom.xml +++ b/mute-idiom/pom.xml @@ -40,4 +40,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.mute.App + + + + + + + + diff --git a/mutex/README.md b/mutex/README.md index 43ed8d94732d..997c37a35eb0 100644 --- a/mutex/README.md +++ b/mutex/README.md @@ -27,5 +27,5 @@ Use a Mutex when ## Credits -* [Lock (computer science)] (http://en.wikipedia.org/wiki/Lock_(computer_science)) -* [Semaphores] (http://tutorials.jenkov.com/java-concurrency/semaphores.html) +* [Lock (computer science)](http://en.wikipedia.org/wiki/Lock_(computer_science)) +* [Semaphores](http://tutorials.jenkov.com/java-concurrency/semaphores.html) diff --git a/mutex/pom.xml b/mutex/pom.xml index c1cad3d8aae4..9cdff25e42e2 100644 --- a/mutex/pom.xml +++ b/mutex/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.mutex.App + + + + + + + + diff --git a/null-object/pom.xml b/null-object/pom.xml index d80b97d95734..7b88fca790a5 100644 --- a/null-object/pom.xml +++ b/null-object/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.nullobject.App + + + + + + + + diff --git a/object-pool/pom.xml b/object-pool/pom.xml index fdd247476d12..2adad8942c92 100644 --- a/object-pool/pom.xml +++ b/object-pool/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.object.pool.App + + + + + + + + diff --git a/observer/pom.xml b/observer/pom.xml index fc8a53eae564..1e48268d885d 100644 --- a/observer/pom.xml +++ b/observer/pom.xml @@ -49,4 +49,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.observer.App + + + + + + + + diff --git a/page-object/pom.xml b/page-object/pom.xml index 99c67dbc5f38..4bf31d72eaa8 100644 --- a/page-object/pom.xml +++ b/page-object/pom.xml @@ -26,6 +26,23 @@ 4.0.0 + + 11 + 11 + + + + net.sourceforge.htmlunit + htmlunit + test + + + org.junit.jupiter + junit-jupiter + RELEASE + test + + com.iluwatar java-design-patterns @@ -37,4 +54,23 @@ sample-application test-automation + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.pageobject.App + + + + + + + + \ No newline at end of file diff --git a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java index e3a86599c3fb..edf7e12581b9 100644 --- a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java +++ b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java @@ -71,8 +71,8 @@ private App() { public static void main(String[] args) { try { - File applicationFile = - new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath()); + var classLoader = App.class.getClassLoader(); + var applicationFile = new File(classLoader.getResource("sample-ui/login.html").getPath()); // should work for unix like OS (mac, unix etc...) if (Desktop.isDesktopSupported()) { diff --git a/page-object/src/main/java/com/iluwatar/pageobject/App.java b/page-object/src/main/java/com/iluwatar/pageobject/App.java index ee9f58504a0b..1acc63419f53 100644 --- a/page-object/src/main/java/com/iluwatar/pageobject/App.java +++ b/page-object/src/main/java/com/iluwatar/pageobject/App.java @@ -67,8 +67,8 @@ private App() { public static void main(String[] args) { try { - File applicationFile = - new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath()); + var classLoader = App.class.getClassLoader(); + var applicationFile = new File(classLoader.getResource("sample-ui/login.html").getPath()); // Should work for unix like OS (mac, unix etc...) if (Desktop.isDesktopSupported()) { diff --git a/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java b/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java index 29704fe387cc..779458e059a0 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java @@ -23,14 +23,14 @@ package com.iluwatar.pageobject; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.gargoylesoftware.htmlunit.WebClient; import com.iluwatar.pageobject.pages.AlbumListPage; import com.iluwatar.pageobject.pages.AlbumPage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Test Album Selection and Album Listing */ @@ -45,7 +45,7 @@ public void setUp() { @Test public void testSelectAlbum() { - AlbumPage albumPage = albumListPage.selectAlbum("21"); + var albumPage = albumListPage.selectAlbum("21"); albumPage.navigateToPage(); assertTrue(albumPage.isAt()); } diff --git a/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java b/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java index 488dcc0bb878..601093343374 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java @@ -23,14 +23,14 @@ package com.iluwatar.pageobject; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.gargoylesoftware.htmlunit.WebClient; import com.iluwatar.pageobject.pages.AlbumListPage; import com.iluwatar.pageobject.pages.AlbumPage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Test Album Page Operations */ @@ -46,7 +46,7 @@ public void setUp() { @Test public void testSaveAlbum() { - AlbumPage albumPageAfterChanges = albumPage + var albumPageAfterChanges = albumPage .changeAlbumTitle("25") .changeArtist("Adele Laurie Blue Adkins") .changeAlbumYear(2015) @@ -60,7 +60,7 @@ public void testSaveAlbum() { @Test public void testCancelChanges() { - AlbumListPage albumListPage = albumPage.cancelChanges(); + var albumListPage = albumPage.cancelChanges(); albumListPage.navigateToPage(); assertTrue(albumListPage.isAt()); } diff --git a/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java b/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java index 70458eb643e5..022f736cacae 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java @@ -23,14 +23,14 @@ package com.iluwatar.pageobject; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.gargoylesoftware.htmlunit.WebClient; import com.iluwatar.pageobject.pages.AlbumListPage; import com.iluwatar.pageobject.pages.LoginPage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Test Login Page Object */ @@ -45,7 +45,7 @@ public void setUp() { @Test public void testLogin() { - AlbumListPage albumListPage = loginPage + var albumListPage = loginPage .enterUsername("admin") .enterPassword("password") .login(); diff --git a/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumListPage.java b/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumListPage.java index f64c7cec2803..6d68960b4d8e 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumListPage.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumListPage.java @@ -26,7 +26,6 @@ import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlPage; - import java.io.IOException; import java.util.List; @@ -79,8 +78,8 @@ public boolean isAt() { */ public AlbumPage selectAlbum(String albumTitle) { // uses XPath to find list of html anchor tags with the class album in it - List albumLinks = (List) page.getByXPath("//tr[@class='album']//a"); - for (HtmlAnchor anchor : albumLinks) { + var albumLinks = (List) page.getByXPath("//tr[@class='album']//a"); + for (var anchor : albumLinks) { if (anchor.getTextContent().equals(albumTitle)) { try { anchor.click(); diff --git a/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumPage.java b/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumPage.java index 9115603147f7..e9e2605ab04a 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumPage.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumPage.java @@ -30,7 +30,6 @@ import com.gargoylesoftware.htmlunit.html.HtmlSelect; import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; import com.gargoylesoftware.htmlunit.html.HtmlTextInput; - import java.io.IOException; /** @@ -83,7 +82,7 @@ public boolean isAt() { * @return {@link AlbumPage} */ public AlbumPage changeAlbumTitle(String albumTitle) { - HtmlTextInput albumTitleInputTextField = (HtmlTextInput) page.getElementById("albumTitle"); + var albumTitleInputTextField = (HtmlTextInput) page.getElementById("albumTitle"); albumTitleInputTextField.setText(albumTitle); return this; } @@ -96,7 +95,7 @@ public AlbumPage changeAlbumTitle(String albumTitle) { * @return {@link AlbumPage} */ public AlbumPage changeArtist(String artist) { - HtmlTextInput artistInputTextField = (HtmlTextInput) page.getElementById("albumArtist"); + var artistInputTextField = (HtmlTextInput) page.getElementById("albumArtist"); artistInputTextField.setText(artist); return this; } @@ -109,8 +108,8 @@ public AlbumPage changeArtist(String artist) { * @return {@link AlbumPage} */ public AlbumPage changeAlbumYear(int year) { - HtmlSelect albumYearSelectOption = (HtmlSelect) page.getElementById("albumYear"); - HtmlOption yearOption = albumYearSelectOption.getOptionByValue(Integer.toString(year)); + var albumYearSelectOption = (HtmlSelect) page.getElementById("albumYear"); + var yearOption = albumYearSelectOption.getOptionByValue(Integer.toString(year)); albumYearSelectOption.setSelectedAttribute(yearOption, true); return this; } @@ -123,7 +122,7 @@ public AlbumPage changeAlbumYear(int year) { * @return {@link AlbumPage} */ public AlbumPage changeAlbumRating(String albumRating) { - HtmlTextInput albumRatingInputTextField = (HtmlTextInput) page.getElementById("albumRating"); + var albumRatingInputTextField = (HtmlTextInput) page.getElementById("albumRating"); albumRatingInputTextField.setText(albumRating); return this; } @@ -135,7 +134,7 @@ public AlbumPage changeAlbumRating(String albumRating) { * @return {@link AlbumPage} */ public AlbumPage changeNumberOfSongs(int numberOfSongs) { - HtmlNumberInput numberOfSongsNumberField = (HtmlNumberInput) page.getElementById("numberOfSongs"); + var numberOfSongsNumberField = (HtmlNumberInput) page.getElementById("numberOfSongs"); numberOfSongsNumberField.setText(Integer.toString(numberOfSongs)); return this; } @@ -147,7 +146,7 @@ public AlbumPage changeNumberOfSongs(int numberOfSongs) { * @return {@link AlbumListPage} */ public AlbumListPage cancelChanges() { - HtmlSubmitInput cancelButton = (HtmlSubmitInput) page.getElementById("cancelButton"); + var cancelButton = (HtmlSubmitInput) page.getElementById("cancelButton"); try { cancelButton.click(); } catch (IOException e) { @@ -163,7 +162,7 @@ public AlbumListPage cancelChanges() { * @return {@link AlbumPage} */ public AlbumPage saveChanges() { - HtmlSubmitInput saveButton = (HtmlSubmitInput) page.getElementById("saveButton"); + var saveButton = (HtmlSubmitInput) page.getElementById("saveButton"); try { saveButton.click(); } catch (IOException e) { diff --git a/page-object/src/test/java/com/iluwatar/pageobject/pages/LoginPage.java b/page-object/src/test/java/com/iluwatar/pageobject/pages/LoginPage.java index 81debb5fb681..e245f4b23622 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/pages/LoginPage.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/pages/LoginPage.java @@ -79,7 +79,7 @@ public boolean isAt() { * @return {@link LoginPage} */ public LoginPage enterUsername(String username) { - HtmlTextInput usernameInputTextField = (HtmlTextInput) page.getElementById("username"); + var usernameInputTextField = (HtmlTextInput) page.getElementById("username"); usernameInputTextField.setText(username); return this; } @@ -92,7 +92,7 @@ public LoginPage enterUsername(String username) { * @return {@link LoginPage} */ public LoginPage enterPassword(String password) { - HtmlPasswordInput passwordInputPasswordField = (HtmlPasswordInput) page.getElementById("password"); + var passwordInputPasswordField = (HtmlPasswordInput) page.getElementById("password"); passwordInputPasswordField.setText(password); return this; } @@ -101,11 +101,11 @@ public LoginPage enterPassword(String password) { /** * Clicking on the login button to 'login' * - * @return {@link AlbumListPage} - * - this is the page that user gets navigated to once successfully logged in + * @return {@link AlbumListPage} - this is the page that user gets navigated to once successfully + * logged in */ public AlbumListPage login() { - HtmlSubmitInput loginButton = (HtmlSubmitInput) page.getElementById("loginButton"); + var loginButton = (HtmlSubmitInput) page.getElementById("loginButton"); try { loginButton.click(); } catch (IOException e) { diff --git a/page-object/src/test/java/com/iluwatar/pageobject/pages/Page.java b/page-object/src/test/java/com/iluwatar/pageobject/pages/Page.java index 3cebd94e94e4..81d148dd3f16 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/pages/Page.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/pages/Page.java @@ -31,8 +31,7 @@ public abstract class Page { /** - * Application Under Test path - * This directory location is where html web pages are located + * Application Under Test path This directory location is where html web pages are located */ public static final String AUT_PATH = "src/main/resources/sample-ui/"; diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java index 2851d24d54c1..807582cb78be 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java @@ -81,8 +81,8 @@ public boolean isAt() { */ public AlbumPage selectAlbum(String albumTitle) { // uses XPath to find list of html anchor tags with the class album in it - List albumLinks = (List) page.getByXPath("//tr[@class='album']//a"); - for (HtmlAnchor anchor : albumLinks) { + var albumLinks = (List) page.getByXPath("//tr[@class='album']//a"); + for (var anchor : albumLinks) { if (anchor.getTextContent().equals(albumTitle)) { try { anchor.click(); diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java index 953a47ba2e39..837cb630720b 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java @@ -25,7 +25,6 @@ import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlNumberInput; -import com.gargoylesoftware.htmlunit.html.HtmlOption; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlSelect; import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; @@ -85,7 +84,7 @@ public boolean isAt() { * @return {@link AlbumPage} */ public AlbumPage changeAlbumTitle(String albumTitle) { - HtmlTextInput albumTitleInputTextField = (HtmlTextInput) page.getElementById("albumTitle"); + var albumTitleInputTextField = (HtmlTextInput) page.getElementById("albumTitle"); albumTitleInputTextField.setText(albumTitle); return this; } @@ -98,7 +97,7 @@ public AlbumPage changeAlbumTitle(String albumTitle) { * @return {@link AlbumPage} */ public AlbumPage changeArtist(String artist) { - HtmlTextInput artistInputTextField = (HtmlTextInput) page.getElementById("albumArtist"); + var artistInputTextField = (HtmlTextInput) page.getElementById("albumArtist"); artistInputTextField.setText(artist); return this; } @@ -111,8 +110,8 @@ public AlbumPage changeArtist(String artist) { * @return {@link AlbumPage} */ public AlbumPage changeAlbumYear(int year) { - HtmlSelect albumYearSelectOption = (HtmlSelect) page.getElementById("albumYear"); - HtmlOption yearOption = albumYearSelectOption.getOptionByValue(Integer.toString(year)); + var albumYearSelectOption = (HtmlSelect) page.getElementById("albumYear"); + var yearOption = albumYearSelectOption.getOptionByValue(Integer.toString(year)); albumYearSelectOption.setSelectedAttribute(yearOption, true); return this; } @@ -125,7 +124,7 @@ public AlbumPage changeAlbumYear(int year) { * @return {@link AlbumPage} */ public AlbumPage changeAlbumRating(String albumRating) { - HtmlTextInput albumRatingInputTextField = (HtmlTextInput) page.getElementById("albumRating"); + var albumRatingInputTextField = (HtmlTextInput) page.getElementById("albumRating"); albumRatingInputTextField.setText(albumRating); return this; } @@ -137,8 +136,7 @@ public AlbumPage changeAlbumRating(String albumRating) { * @return {@link AlbumPage} */ public AlbumPage changeNumberOfSongs(int numberOfSongs) { - HtmlNumberInput numberOfSongsNumberField = - (HtmlNumberInput) page.getElementById("numberOfSongs"); + var numberOfSongsNumberField = (HtmlNumberInput) page.getElementById("numberOfSongs"); numberOfSongsNumberField.setText(Integer.toString(numberOfSongs)); return this; } @@ -150,7 +148,7 @@ public AlbumPage changeNumberOfSongs(int numberOfSongs) { * @return {@link AlbumListPage} */ public AlbumListPage cancelChanges() { - HtmlSubmitInput cancelButton = (HtmlSubmitInput) page.getElementById("cancelButton"); + var cancelButton = (HtmlSubmitInput) page.getElementById("cancelButton"); try { cancelButton.click(); } catch (IOException e) { @@ -166,7 +164,7 @@ public AlbumListPage cancelChanges() { * @return {@link AlbumPage} */ public AlbumPage saveChanges() { - HtmlSubmitInput saveButton = (HtmlSubmitInput) page.getElementById("saveButton"); + var saveButton = (HtmlSubmitInput) page.getElementById("saveButton"); try { saveButton.click(); } catch (IOException e) { diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java index 78d3fa329ab5..b9ec57ff964c 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java @@ -82,7 +82,7 @@ public boolean isAt() { * @return {@link LoginPage} */ public LoginPage enterUsername(String username) { - HtmlTextInput usernameInputTextField = (HtmlTextInput) page.getElementById("username"); + var usernameInputTextField = (HtmlTextInput) page.getElementById("username"); usernameInputTextField.setText(username); return this; } @@ -95,8 +95,7 @@ public LoginPage enterUsername(String username) { * @return {@link LoginPage} */ public LoginPage enterPassword(String password) { - HtmlPasswordInput passwordInputPasswordField = - (HtmlPasswordInput) page.getElementById("password"); + var passwordInputPasswordField = (HtmlPasswordInput) page.getElementById("password"); passwordInputPasswordField.setText(password); return this; } @@ -109,7 +108,7 @@ public LoginPage enterPassword(String password) { * logged in */ public AlbumListPage login() { - HtmlSubmitInput loginButton = (HtmlSubmitInput) page.getElementById("loginButton"); + var loginButton = (HtmlSubmitInput) page.getElementById("loginButton"); try { loginButton.click(); } catch (IOException e) { diff --git a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java index 8e8173c04ea5..d1b450a24474 100644 --- a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java +++ b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java @@ -23,14 +23,12 @@ package com.iluwatar.pageobject; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.gargoylesoftware.htmlunit.WebClient; -import com.iluwatar.pageobject.AlbumListPage; -import com.iluwatar.pageobject.AlbumPage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Test Album Selection and Album Listing */ @@ -45,7 +43,7 @@ public void setUp() { @Test public void testSelectAlbum() { - AlbumPage albumPage = albumListPage.selectAlbum("21"); + var albumPage = albumListPage.selectAlbum("21"); albumPage.navigateToPage(); assertTrue(albumPage.isAt()); } diff --git a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java index f3fea0ee6b1c..8e694a592cbd 100644 --- a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java +++ b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java @@ -25,11 +25,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; +import com.gargoylesoftware.htmlunit.WebClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import com.gargoylesoftware.htmlunit.WebClient; - /** * Test Album Page Operations */ @@ -45,7 +44,7 @@ public void setUp() { @Test public void testSaveAlbum() { - AlbumPage albumPageAfterChanges = albumPage + var albumPageAfterChanges = albumPage .changeAlbumTitle("25") .changeArtist("Adele Laurie Blue Adkins") .changeAlbumYear(2015) @@ -59,7 +58,7 @@ public void testSaveAlbum() { @Test public void testCancelChanges() { - AlbumListPage albumListPage = albumPage.cancelChanges(); + var albumListPage = albumPage.cancelChanges(); albumListPage.navigateToPage(); assertTrue(albumListPage.isAt()); } diff --git a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java index f6ec3978f706..89668882d668 100644 --- a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java +++ b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java @@ -25,11 +25,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; +import com.gargoylesoftware.htmlunit.WebClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import com.gargoylesoftware.htmlunit.WebClient; - /** * Test Login Page Object */ @@ -44,7 +43,7 @@ public void setUp() { @Test public void testLogin() { - AlbumListPage albumListPage = loginPage + var albumListPage = loginPage .enterUsername("admin") .enterPassword("password") .login(); diff --git a/partial-response/pom.xml b/partial-response/pom.xml index 6bca7007329d..83d81bf828f1 100644 --- a/partial-response/pom.xml +++ b/partial-response/pom.xml @@ -49,6 +49,23 @@ mockito-core - - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.partialresponse.App + + + + + + + + \ No newline at end of file diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java index 5a3e7d950e0d..18c3461428ea 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java @@ -44,30 +44,31 @@ public class App { * @param args program argument. */ public static void main(String[] args) throws Exception { - Map videos = Map.of( + var videos = Map.of( 1, new Video(1, "Avatar", 178, "epic science fiction film", "James Cameron", "English"), 2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", "Hideaki Anno", "Japanese"), 3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", - "Christopher Nolan", "English")); - VideoResource videoResource = new VideoResource(new FieldJsonMapper(), videos); + "Christopher Nolan", "English") + ); + var videoResource = new VideoResource(new FieldJsonMapper(), videos); LOGGER.info("Retrieving full response from server:-"); LOGGER.info("Get all video information:"); - String videoDetails = videoResource.getDetails(1); + var videoDetails = videoResource.getDetails(1); LOGGER.info(videoDetails); LOGGER.info("----------------------------------------------------------"); LOGGER.info("Retrieving partial response from server:-"); LOGGER.info("Get video @id, @title, @director:"); - String specificFieldsDetails = videoResource.getDetails(3, "id", "title", "director"); + var specificFieldsDetails = videoResource.getDetails(3, "id", "title", "director"); LOGGER.info(specificFieldsDetails); LOGGER.info("Get video @id, @length:"); - String videoLength = videoResource.getDetails(3, "id", "length"); + var videoLength = videoResource.getDetails(3, "id", "length"); LOGGER.info(videoLength); } } diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java index f735b4d2b847..92180b9d0b21 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java @@ -38,13 +38,16 @@ public class FieldJsonMapper { * @return json of required fields from video */ public String toJson(Video video, String[] fields) throws Exception { - StringBuilder json = new StringBuilder().append("{"); + var json = new StringBuilder().append("{"); - for (int i = 0, fieldsLength = fields.length; i < fieldsLength; i++) { + var i = 0; + var fieldsLength = fields.length; + while (i < fieldsLength) { json.append(getString(video, Video.class.getDeclaredField(fields[i]))); if (i != fieldsLength - 1) { json.append(","); } + i++; } json.append("}"); return json.toString(); @@ -52,7 +55,7 @@ public String toJson(Video video, String[] fields) throws Exception { private String getString(Video video, Field declaredField) throws IllegalAccessException { declaredField.setAccessible(true); - Object value = declaredField.get(video); + var value = declaredField.get(video); if (declaredField.get(video) instanceof Integer) { return "\"" + declaredField.getName() + "\"" + ": " + value; } diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java index afd2c70e253b..d50084a36846 100644 --- a/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java +++ b/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java @@ -32,8 +32,7 @@ public class AppTest { @Test public void main() throws Exception { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } \ No newline at end of file diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java index c71cc21f4e58..57741c1d7260 100644 --- a/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java +++ b/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java @@ -23,11 +23,11 @@ package com.iluwatar.partialresponse; +import static org.junit.Assert.assertEquals; + import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; - /** * tests {@link FieldJsonMapper}. */ @@ -41,12 +41,15 @@ public void setUp() { @Test public void shouldReturnJsonForSpecifiedFieldsInVideo() throws Exception { - String[] fields = new String[]{"id", "title", "length"}; - Video video = new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", "Hideaki Anno", "Japanese"); + var fields = new String[]{"id", "title", "length"}; + var video = new Video( + 2, "Godzilla Resurgence", 120, + "Action & drama movie|", "Hideaki Anno", "Japanese" + ); - String jsonFieldResponse = mapper.toJson(video, fields); + var jsonFieldResponse = mapper.toJson(video, fields); - String expectedDetails = "{\"id\": 2,\"title\": \"Godzilla Resurgence\",\"length\": 120}"; + var expectedDetails = "{\"id\": 2,\"title\": \"Godzilla Resurgence\",\"length\": 120}"; assertEquals(expectedDetails, jsonFieldResponse); } } \ No newline at end of file diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java index 85f240fa03db..2524998039a3 100644 --- a/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java +++ b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java @@ -23,19 +23,18 @@ package com.iluwatar.partialresponse; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.when; - /** * tests {@link VideoResource}. */ @@ -48,33 +47,33 @@ public class VideoResourceTest { @Before public void setUp() { - Map videos = Map.of( - 1, new Video(1, "Avatar", 178, "epic science fiction film", - "James Cameron", "English"), - 2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", - "Hideaki Anno", "Japanese"), - 3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", - "Christopher Nolan", "English")); + var videos = Map.of( + 1, new Video(1, "Avatar", 178, "epic science fiction film", + "James Cameron", "English"), + 2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", + "Hideaki Anno", "Japanese"), + 3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", + "Christopher Nolan", "English")); resource = new VideoResource(fieldJsonMapper, videos); } @Test public void shouldGiveVideoDetailsById() throws Exception { - String actualDetails = resource.getDetails(1); + var actualDetails = resource.getDetails(1); - String expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": " + var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": " + "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\",}"; assertEquals(expectedDetails, actualDetails); } @Test public void shouldGiveSpecifiedFieldsInformationOfVideo() throws Exception { - String[] fields = new String[]{"id", "title", "length"}; + var fields = new String[]{"id", "title", "length"}; - String expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178}"; + var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178}"; when(fieldJsonMapper.toJson(any(Video.class), eq(fields))).thenReturn(expectedDetails); - String actualFieldsDetails = resource.getDetails(2, fields); + var actualFieldsDetails = resource.getDetails(2, fields); assertEquals(expectedDetails, actualFieldsDetails); } diff --git a/pipeline/pom.xml b/pipeline/pom.xml index e7d879d4a5ce..8c511cd8aff5 100644 --- a/pipeline/pom.xml +++ b/pipeline/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.pipeline.App + + + + + + + + diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java index 365fc1cdc2e4..f57a815118bb 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java @@ -36,11 +36,12 @@ class ConvertToCharArrayHandler implements Handler { @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)); + var characters = input.toCharArray(); + var string = Arrays.toString(characters); + LOGGER.info( + String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", + ConvertToCharArrayHandler.class, input, String.class, string, Character[].class) + ); return characters; } diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java index b2ed938cf100..50c158fc4317 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java @@ -23,6 +23,7 @@ package com.iluwatar.pipeline; +import java.util.function.IntPredicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,18 +37,14 @@ class RemoveAlphabetsHandler implements Handler { @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(); + var inputWithoutAlphabets = new StringBuilder(); + var isAlphabetic = (IntPredicate) Character::isAlphabetic; + input.chars() + .filter(isAlphabetic.negate()) + .mapToObj(x -> (char) x) + .forEachOrdered(inputWithoutAlphabets::append); + + var inputWithoutAlphabetsStr = inputWithoutAlphabets.toString(); LOGGER.info( String.format( "Current handler: %s, input is %s of type %s, output is %s, of type %s", diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java index 450bef7177ea..dba50bbb3fff 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java @@ -23,6 +23,7 @@ package com.iluwatar.pipeline; +import java.util.function.IntPredicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,21 +37,20 @@ class RemoveDigitsHandler implements Handler { @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)); + var inputWithoutDigits = new StringBuilder(); + var isDigit = (IntPredicate) Character::isDigit; + input.chars() + .filter(isDigit.negate()) + .mapToObj(x -> (char) x) + .forEachOrdered(inputWithoutDigits::append); + + var 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; } diff --git a/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java b/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java index d5a892d91809..8ea6a4c60f45 100644 --- a/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java +++ b/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java @@ -32,7 +32,6 @@ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java b/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java index 1de692222dbe..062d796b1a59 100644 --- a/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java +++ b/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java @@ -23,10 +23,10 @@ package com.iluwatar.pipeline; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import org.junit.jupiter.api.Test; + /** * Test for {@link Pipeline} */ @@ -34,12 +34,12 @@ public class PipelineTest { @Test public void testAddHandlersToPipeline() { - Pipeline filters = new Pipeline<>(new RemoveAlphabetsHandler()) + var filters = new Pipeline<>(new RemoveAlphabetsHandler()) .addHandler(new RemoveDigitsHandler()) .addHandler(new ConvertToCharArrayHandler()); assertArrayEquals( - new char[] {'#', '!', '(', '&', '%', '#', '!'}, + new char[]{'#', '!', '(', '&', '%', '#', '!'}, filters.execute("#H!E(L&L0O%THE3R#34E!") ); } diff --git a/poison-pill/pom.xml b/poison-pill/pom.xml index b751fad04837..4989581d7b97 100644 --- a/poison-pill/pom.xml +++ b/poison-pill/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.poison.pill.App + + + + + + + + diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java index 7fdf71a09b3b..841745b7591c 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java @@ -42,26 +42,18 @@ public class App { * @param args command line args */ public static void main(String[] args) { - MessageQueue queue = new SimpleMessageQueue(10000); + var queue = new SimpleMessageQueue(10000); - final Producer producer = new Producer("PRODUCER_1", queue); - final Consumer consumer = new Consumer("CONSUMER_1", queue); + final var producer = new Producer("PRODUCER_1", queue); + final var consumer = new Consumer("CONSUMER_1", queue); - new Thread() { - @Override - public void run() { - consumer.consume(); - } - }.start(); + new Thread(consumer::consume).start(); - new Thread() { - @Override - public void run() { - producer.send("hand shake"); - producer.send("some very important information"); - producer.send("bye!"); - producer.stop(); - } - }.start(); + new Thread(() -> { + producer.send("hand shake"); + producer.send("some very important information"); + producer.send("bye!"); + producer.stop(); + }).start(); } } diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java index 25d2338e1226..ac0e5782993d 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java @@ -47,22 +47,20 @@ public Consumer(String name, MqSubscribePoint queue) { */ public void consume() { while (true) { - Message msg; try { - msg = queue.take(); + var msg = queue.take(); if (Message.POISON_PILL.equals(msg)) { LOGGER.info("Consumer {} receive request to terminate.", name); break; } + var sender = msg.getHeader(Headers.SENDER); + var body = msg.getBody(); + LOGGER.info("Message [{}] from [{}] received by [{}]", body, sender, name); } catch (InterruptedException e) { // allow thread to exit LOGGER.error("Exception caught.", e); return; } - - String sender = msg.getHeader(Headers.SENDER); - String body = msg.getBody(); - LOGGER.info("Message [{}] from [{}] received by [{}]", body, sender, name); } } } diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java index 679500e43317..8cc4466972ce 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java @@ -57,7 +57,7 @@ public void send(String body) { throw new IllegalStateException(String.format( "Producer %s was stopped and fail to deliver requested message [%s].", body, name)); } - Message msg = new SimpleMessage(); + var msg = new SimpleMessage(); msg.addHeader(Headers.DATE, new Date().toString()); msg.addHeader(Headers.SENDER, name); msg.setBody(body); diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java index b921f6bc7c7f..c23fe556378e 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java index c874d36293fb..100565fbcd76 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java @@ -23,20 +23,19 @@ package com.iluwatar.poison.pill; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.time.LocalDateTime; +import java.util.LinkedList; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import java.time.LocalDateTime; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Date: 12/27/15 - 9:45 PM * @@ -58,15 +57,15 @@ public void tearDown() { @Test public void testConsume() throws Exception { - final Message[] messages = new Message[]{ + final var messages = List.of( createMessage("you", "Hello!"), createMessage("me", "Hi!"), Message.POISON_PILL, - createMessage("late_for_the_party", "Hello? Anyone here?"), - }; + createMessage("late_for_the_party", "Hello? Anyone here?") + ); - final MessageQueue queue = new SimpleMessageQueue(messages.length); - for (final Message message : messages) { + final var queue = new SimpleMessageQueue(messages.size()); + for (final var message : messages) { queue.put(message); } @@ -85,7 +84,7 @@ public void testConsume() throws Exception { * @return The message instance */ private static Message createMessage(final String sender, final String message) { - final SimpleMessage msg = new SimpleMessage(); + final var msg = new SimpleMessage(); msg.addHeader(Message.Headers.SENDER, sender); msg.addHeader(Message.Headers.DATE, LocalDateTime.now().toString()); msg.setBody(message); @@ -106,7 +105,7 @@ protected void append(ILoggingEvent eventObject) { } public boolean logContains(String message) { - return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + return log.stream().map(ILoggingEvent::getFormattedMessage).anyMatch(message::equals); } } diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java index 6b310d431116..159b9658ea5e 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java @@ -23,12 +23,12 @@ package com.iluwatar.poison.pill; -import org.junit.jupiter.api.Test; - import static com.iluwatar.poison.pill.Message.Headers; import static com.iluwatar.poison.pill.Message.POISON_PILL; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + /** * Date: 12/27/15 - 10:30 PM * diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java index 76f2373da017..e1781f9e497a 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java @@ -23,9 +23,6 @@ package com.iluwatar.poison.pill; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; @@ -35,6 +32,9 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + /** * Date: 12/27/15 - 10:32 PM * @@ -44,16 +44,16 @@ public class ProducerTest { @Test public void testSend() throws Exception { - final MqPublishPoint publishPoint = mock(MqPublishPoint.class); - final Producer producer = new Producer("producer", publishPoint); + final var publishPoint = mock(MqPublishPoint.class); + final var producer = new Producer("producer", publishPoint); verifyZeroInteractions(publishPoint); producer.send("Hello!"); - final ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); + final var messageCaptor = ArgumentCaptor.forClass(Message.class); verify(publishPoint).put(messageCaptor.capture()); - final Message message = messageCaptor.getValue(); + final var message = messageCaptor.getValue(); assertNotNull(message); assertEquals("producer", message.getHeader(Message.Headers.SENDER)); assertNotNull(message.getHeader(Message.Headers.DATE)); @@ -64,8 +64,8 @@ public void testSend() throws Exception { @Test public void testStop() throws Exception { - final MqPublishPoint publishPoint = mock(MqPublishPoint.class); - final Producer producer = new Producer("producer", publishPoint); + final var publishPoint = mock(MqPublishPoint.class); + final var producer = new Producer("producer", publishPoint); verifyZeroInteractions(publishPoint); producer.stop(); @@ -78,7 +78,7 @@ public void testStop() throws Exception { assertNotNull(e); assertNotNull(e.getMessage()); assertEquals("Producer Hello! was stopped and fail to deliver requested message [producer].", - e.getMessage()); + e.getMessage()); } verifyNoMoreInteractions(publishPoint); diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java index 3eebecb01845..d5486ddd2b37 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java @@ -23,16 +23,14 @@ package com.iluwatar.poison.pill; -import org.junit.jupiter.api.Test; - -import java.util.Map; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * Date: 12/27/15 - 10:25 PM * @@ -42,11 +40,11 @@ public class SimpleMessageTest { @Test public void testGetHeaders() { - final SimpleMessage message = new SimpleMessage(); + final var message = new SimpleMessage(); assertNotNull(message.getHeaders()); assertTrue(message.getHeaders().isEmpty()); - final String senderName = "test"; + final var senderName = "test"; message.addHeader(Message.Headers.SENDER, senderName); assertNotNull(message.getHeaders()); assertFalse(message.getHeaders().isEmpty()); @@ -55,8 +53,8 @@ public void testGetHeaders() { @Test public void testUnModifiableHeaders() { - final SimpleMessage message = new SimpleMessage(); - final Map headers = message.getHeaders(); + final var message = new SimpleMessage(); + final var headers = message.getHeaders(); assertThrows(UnsupportedOperationException.class, () -> { headers.put(Message.Headers.SENDER, "test"); }); diff --git a/pom.xml b/pom.xml index 7c2789da5346..d035cfe405b1 100644 --- a/pom.xml +++ b/pom.xml @@ -42,13 +42,13 @@ 1.10.19 2.22 4.0 - 3.3.0 - 1.7.28 + 3.12.1 + 1.7.30 1.2.3 1.1.0 1.11.289 2.0.1 - 2.8.5 + 2.10.2 2.3.1 2.3.2 1.3.2 @@ -322,7 +322,7 @@ org.javassist javassist - 3.25.0-GA + 3.26.0-GA com.github.stefanbirkner diff --git a/priority-queue/pom.xml b/priority-queue/pom.xml index 3ba564b55583..7f435f489883 100644 --- a/priority-queue/pom.xml +++ b/priority-queue/pom.xml @@ -41,5 +41,23 @@ test - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.priority.queue.Application + + + + + + + + \ No newline at end of file diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java index e803489b28d2..433a72d74c98 100644 --- a/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java +++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java @@ -37,22 +37,22 @@ public class Application { */ public static void main(String[] args) throws Exception { - QueueManager queueManager = new QueueManager(100); + var queueManager = new QueueManager(100); // push some message to queue // Low Priority message - for (int i = 0; i < 100; i++) { + for (var i = 0; i < 100; i++) { queueManager.publishMessage(new Message("Low Message Priority", 0)); } // High Priority message - for (int i = 0; i < 100; i++) { + for (var i = 0; i < 100; i++) { queueManager.publishMessage(new Message("High Message Priority", 1)); } // run worker - Worker worker = new Worker(queueManager); + var worker = new Worker(queueManager); worker.run(); diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java index 66f4d4f591f6..a161a97005dc 100644 --- a/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java +++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java @@ -57,7 +57,7 @@ public T remove() { return null; } - final T root = queue[0]; + final var root = queue[0]; queue[0] = queue[size - 1]; size--; maxHeapifyDown(); @@ -83,10 +83,10 @@ public boolean isEmpty() { private void maxHeapifyDown() { - int index = 0; + var index = 0; while (hasLeftChild(index)) { - int smallerIndex = leftChildIndex(index); + var smallerIndex = leftChildIndex(index); if (hasRightChild(index) && right(index).compareTo(left(index)) > 0) { smallerIndex = rightChildIndex(index); @@ -106,7 +106,7 @@ private void maxHeapifyDown() { } private void maxHeapifyUp() { - int index = size - 1; + var index = size - 1; while (hasParent(index) && parent(index).compareTo(queue[index]) < 0) { swap(parentIndex(index), index); index = parentIndex(index); @@ -154,7 +154,7 @@ private boolean hasParent(int index) { } private void swap(int fpos, int tpos) { - T tmp = queue[fpos]; + var tmp = queue[fpos]; queue[fpos] = queue[tpos]; queue[tpos] = tmp; } @@ -170,7 +170,7 @@ private void ensureCapacity() { * For debug .. print current state of queue */ public void print() { - for (int i = 0; i <= size / 2; i++) { + for (var i = 0; i <= size / 2; i++) { LOGGER.info(" PARENT : " + queue[i] + " LEFT CHILD : " + left(i) + " RIGHT CHILD :" + right(i)); } diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java index 7eca0aca6d3d..0b4be910f2e5 100644 --- a/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java +++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java @@ -33,7 +33,7 @@ public class QueueManager { private final PriorityMessageQueue messagePriorityMessageQueue; public QueueManager(int initialCapacity) { - messagePriorityMessageQueue = new PriorityMessageQueue(new Message[initialCapacity]); + messagePriorityMessageQueue = new PriorityMessageQueue<>(new Message[initialCapacity]); } /** diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java index 18ed16199584..95417c500d4d 100644 --- a/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java +++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java @@ -45,7 +45,7 @@ public Worker(QueueManager queueManager) { @SuppressWarnings("squid:S2189") public void run() throws Exception { while (true) { - Message message = queueManager.receiveMessage(); + var message = queueManager.receiveMessage(); if (message == null) { LOGGER.info("No Message ... waiting"); Thread.sleep(200); diff --git a/priority-queue/src/test/java/com/iluwatar/priority/queue/PriorityMessageQueueTest.java b/priority-queue/src/test/java/com/iluwatar/priority/queue/PriorityMessageQueueTest.java index 4fd1f06a6454..541310dd0295 100644 --- a/priority-queue/src/test/java/com/iluwatar/priority/queue/PriorityMessageQueueTest.java +++ b/priority-queue/src/test/java/com/iluwatar/priority/queue/PriorityMessageQueueTest.java @@ -23,11 +23,11 @@ package com.iluwatar.priority.queue; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * Test case for order of messages */ @@ -36,25 +36,25 @@ public class PriorityMessageQueueTest { @Test public void remove() { - PriorityMessageQueue stringPriorityMessageQueue = new PriorityMessageQueue<>(new String[2]); - String pushMessage = "test"; + var stringPriorityMessageQueue = new PriorityMessageQueue<>(new String[2]); + var pushMessage = "test"; stringPriorityMessageQueue.add(pushMessage); assertEquals(stringPriorityMessageQueue.remove(), pushMessage); } @Test public void add() { - PriorityMessageQueue stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]); + var stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]); stringPriorityMessageQueue.add(1); stringPriorityMessageQueue.add(5); stringPriorityMessageQueue.add(10); stringPriorityMessageQueue.add(3); - assertTrue(stringPriorityMessageQueue.remove() == 10); + assertEquals(10, (int) stringPriorityMessageQueue.remove()); } @Test public void isEmpty() { - PriorityMessageQueue stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]); + var stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]); assertTrue(stringPriorityMessageQueue.isEmpty()); stringPriorityMessageQueue.add(1); stringPriorityMessageQueue.remove(); @@ -63,12 +63,12 @@ public void isEmpty() { @Test public void testEnsureSize() { - PriorityMessageQueue stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]); + var stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]); assertTrue(stringPriorityMessageQueue.isEmpty()); stringPriorityMessageQueue.add(1); stringPriorityMessageQueue.add(2); stringPriorityMessageQueue.add(2); stringPriorityMessageQueue.add(3); - assertTrue(stringPriorityMessageQueue.remove() == 3); + assertEquals(3, (int) stringPriorityMessageQueue.remove()); } } \ No newline at end of file diff --git a/priority-queue/src/test/java/com/iluwatar/priority/queue/QueueManagerTest.java b/priority-queue/src/test/java/com/iluwatar/priority/queue/QueueManagerTest.java index 17aad88b396c..3f5dc067665c 100644 --- a/priority-queue/src/test/java/com/iluwatar/priority/queue/QueueManagerTest.java +++ b/priority-queue/src/test/java/com/iluwatar/priority/queue/QueueManagerTest.java @@ -23,10 +23,10 @@ package com.iluwatar.priority.queue; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + /** * Check queue manager */ @@ -34,21 +34,21 @@ public class QueueManagerTest { @Test public void publishMessage() { - QueueManager queueManager = new QueueManager(2); - Message testMessage = new Message("Test Message", 1); + var queueManager = new QueueManager(2); + var testMessage = new Message("Test Message", 1); queueManager.publishMessage(testMessage); - Message recivedMessage = queueManager.receiveMessage(); + var recivedMessage = queueManager.receiveMessage(); assertEquals(testMessage, recivedMessage); } @Test public void receiveMessage() { - QueueManager queueManager = new QueueManager(2); - Message testMessage1 = new Message("Test Message 1", 1); + var queueManager = new QueueManager(2); + var testMessage1 = new Message("Test Message 1", 1); queueManager.publishMessage(testMessage1); - Message testMessage2 = new Message("Test Message 2", 2); + var testMessage2 = new Message("Test Message 2", 2); queueManager.publishMessage(testMessage2); - Message recivedMessage = queueManager.receiveMessage(); + var recivedMessage = queueManager.receiveMessage(); assertEquals(testMessage2, recivedMessage); } } \ No newline at end of file diff --git a/private-class-data/pom.xml b/private-class-data/pom.xml index ecc2933d9ef7..cb81ca3fc9e1 100644 --- a/private-class-data/pom.xml +++ b/private-class-data/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.privateclassdata.App + + + + + + + + diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java index 367baaf8b86c..52e18b1256bb 100644 --- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java +++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java @@ -46,13 +46,13 @@ public class App { */ public static void main(String[] args) { // stew is mutable - Stew stew = new Stew(1, 2, 3, 4); + var stew = new Stew(1, 2, 3, 4); stew.mix(); stew.taste(); stew.mix(); // immutable stew protected with Private Class Data pattern - ImmutableStew immutableStew = new ImmutableStew(2, 4, 3, 6); + var immutableStew = new ImmutableStew(2, 4, 3, 6); immutableStew.mix(); } } diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java index cfdb73fd478f..166ddbdee33d 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java index b866b31eacd7..f789408282f0 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java @@ -23,13 +23,13 @@ package com.iluwatar.privateclassdata; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.privateclassdata.utils.InMemoryAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Date: 12/27/15 - 10:46 PM * @@ -54,10 +54,10 @@ public void tearDown() { */ @Test public void testMix() { - final Stew stew = new Stew(1, 2, 3, 4); - final String expectedMessage = "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers"; + var stew = new Stew(1, 2, 3, 4); + var expectedMessage = "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers"; - for (int i = 0; i < 20; i++) { + for (var i = 0; i < 20; i++) { stew.mix(); assertEquals(expectedMessage, appender.getLastMessage()); } @@ -70,15 +70,17 @@ public void testMix() { */ @Test public void testDrink() { - final Stew stew = new Stew(1, 2, 3, 4); + final var stew = new Stew(1, 2, 3, 4); stew.mix(); - assertEquals("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers", appender.getLastMessage()); + assertEquals("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers", appender + .getLastMessage()); stew.taste(); - assertEquals("Tasting the stew", appender.getLastMessage()); + assertEquals("Tasting the stew", appender.getLastMessage()); stew.mix(); - assertEquals("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers", appender.getLastMessage()); + assertEquals("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers", appender + .getLastMessage()); } } diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java index 3c30fc02122f..722e8354abf8 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java @@ -23,13 +23,13 @@ package com.iluwatar.privateclassdata; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.privateclassdata.utils.InMemoryAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Date: 12/27/15 - 10:46 PM * @@ -54,11 +54,11 @@ public void tearDown() { */ @Test public void testMix() { - final ImmutableStew stew = new ImmutableStew(1, 2, 3, 4); - final String expectedMessage = "Mixing the immutable stew we find: 1 potatoes, " + final var stew = new ImmutableStew(1, 2, 3, 4); + final var expectedMessage = "Mixing the immutable stew we find: 1 potatoes, " + "2 carrots, 3 meat and 4 peppers"; - for (int i = 0; i < 20; i++) { + for (var i = 0; i < 20; i++) { stew.mix(); assertEquals(expectedMessage, appender.getLastMessage()); } diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java index dceaee29b989..6fbe638aed40 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java @@ -26,10 +26,9 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.slf4j.LoggerFactory; - import java.util.LinkedList; import java.util.List; +import org.slf4j.LoggerFactory; /** * InMemory Log Appender Util. diff --git a/producer-consumer/pom.xml b/producer-consumer/pom.xml index 479bd321aed2..ab1872c51562 100644 --- a/producer-consumer/pom.xml +++ b/producer-consumer/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.producer.consumer.App + + + + + + + + diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java index 0ead44307b7d..0096cc7ca939 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java @@ -26,20 +26,18 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces - * coupling between Producer and Consumer by separating Identification of work with - * Execution of Work. + * coupling between Producer and Consumer by separating Identification of work with Execution of + * Work. * *

In producer consumer design pattern a shared queue is used to control the flow and this - * separation allows you to code producer and consumer separately. It also addresses the issue - * of different timing require to produce item or consuming item. by using producer consumer - * pattern both Producer and Consumer Thread can work with different speed. - * + * separation allows you to code producer and consumer separately. It also addresses the issue of + * different timing require to produce item or consuming item. by using producer consumer pattern + * both Producer and Consumer Thread can work with different speed. */ public class App { @@ -47,18 +45,17 @@ public class App { /** * Program entry point. - * - * @param args - * command line args + * + * @param args command line args */ public static void main(String[] args) { - ItemQueue queue = new ItemQueue(); + var queue = new ItemQueue(); - ExecutorService executorService = Executors.newFixedThreadPool(5); - for (int i = 0; i < 2; i++) { + var executorService = Executors.newFixedThreadPool(5); + for (var i = 0; i < 2; i++) { - final Producer producer = new Producer("Producer_" + i, queue); + final var producer = new Producer("Producer_" + i, queue); executorService.submit(() -> { while (true) { producer.produce(); @@ -66,8 +63,8 @@ public static void main(String[] args) { }); } - for (int i = 0; i < 3; i++) { - final Consumer consumer = new Consumer("Consumer_" + i, queue); + for (var i = 0; i < 3; i++) { + final var consumer = new Consumer("Consumer_" + i, queue); executorService.submit(() -> { while (true) { consumer.consume(); diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java index 5598f3e45dca..347b4a052231 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java @@ -46,10 +46,9 @@ public Consumer(String name, ItemQueue queue) { * Consume item from the queue. */ public void consume() throws InterruptedException { - - Item item = queue.take(); + var item = queue.take(); LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name, - item.getId(), item.getProducer()); + item.getId(), item.getProducer()); } } diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java index 6d4ca0096d6d..28f6c053d76c 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java @@ -30,7 +30,7 @@ * to queue. */ public class Producer { - + private static final Random RANDOM = new Random(); private final ItemQueue queue; @@ -49,7 +49,7 @@ public Producer(String name, ItemQueue queue) { */ public void produce() throws InterruptedException { - Item item = new Item(name, itemId++); + var item = new Item(name, itemId++); queue.put(item); Thread.sleep(RANDOM.nextInt(2000)); } diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java index e14e963a1150..bf4b6cc66570 100644 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java +++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java @@ -26,16 +26,13 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test - public void test() throws Exception { - String[] args = {}; - App.main(args); + public void test() { + App.main(new String[]{}); } } diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java index c4b3a17a7a97..24425c3d61ef 100644 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java +++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java @@ -23,13 +23,13 @@ package com.iluwatar.producer.consumer; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import org.junit.jupiter.api.Test; + /** * Date: 12/27/15 - 11:01 PM * @@ -41,15 +41,15 @@ public class ConsumerTest { @Test public void testConsume() throws Exception { - final ItemQueue queue = spy(new ItemQueue()); - for (int id = 0; id < ITEM_COUNT; id++) { + final var queue = spy(new ItemQueue()); + for (var id = 0; id < ITEM_COUNT; id++) { queue.put(new Item("producer", id)); } reset(queue); // Don't count the preparation above as interactions with the queue - final Consumer consumer = new Consumer("consumer", queue); + final var consumer = new Consumer("consumer", queue); - for (int id = 0; id < ITEM_COUNT; id++) { + for (var id = 0; id < ITEM_COUNT; id++) { consumer.consume(); } diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java index 6e93450115cd..6d772ec6a9f5 100644 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java +++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java @@ -23,8 +23,6 @@ package com.iluwatar.producer.consumer; -import org.junit.jupiter.api.Test; - import static java.time.Duration.ofMillis; import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.mockito.Matchers.any; @@ -32,6 +30,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; +import org.junit.jupiter.api.Test; + /** * Date: 12/28/15 - 12:12 AM * @@ -42,8 +42,8 @@ public class ProducerTest { @Test public void testProduce() { assertTimeout(ofMillis(6000), () -> { - final ItemQueue queue = mock(ItemQueue.class); - final Producer producer = new Producer("producer", queue); + final var queue = mock(ItemQueue.class); + final var producer = new Producer("producer", queue); producer.produce(); verify(queue).put(any(Item.class)); diff --git a/promise/pom.xml b/promise/pom.xml index 369e95748a87..4a9d76df1c84 100644 --- a/promise/pom.xml +++ b/promise/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.promise.App + + + + + + + + diff --git a/promise/src/main/java/com/iluwatar/promise/App.java b/promise/src/main/java/com/iluwatar/promise/App.java index c016b67ff0b5..fb2f14bd5492 100644 --- a/promise/src/main/java/com/iluwatar/promise/App.java +++ b/promise/src/main/java/com/iluwatar/promise/App.java @@ -29,19 +29,18 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * The Promise object is used for asynchronous computations. A Promise represents an operation - * that hasn't completed yet, but is expected in the future. + * The Promise object is used for asynchronous computations. A Promise represents an operation that + * hasn't completed yet, but is expected in the future. * - *

A Promise represents a proxy for a value not necessarily known when the promise is created. It - * allows you to associate dependent promises to an asynchronous action's eventual success value or - * failure reason. This lets asynchronous methods return values like synchronous methods: instead - * of the final value, the asynchronous method returns a promise of having a value at some point - * in the future. + *

A Promise represents a proxy for a value not necessarily known when the promise is created. + * It allows you to associate dependent promises to an asynchronous action's eventual success value + * or failure reason. This lets asynchronous methods return values like synchronous methods: instead + * of the final value, the asynchronous method returns a promise of having a value at some point in + * the future. * *

Promises provide a few advantages over callback objects: *

    @@ -58,14 +57,15 @@ * a file download promise, then a promise of character frequency, then a promise of lowest * frequency character which is finally consumed and result is printed on console. *
- * + * * @see CompletableFuture */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - private static final String DEFAULT_URL = "https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md"; + private static final String DEFAULT_URL = + "https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md"; private final ExecutorService executor; private final CountDownLatch stopLatch; @@ -76,12 +76,13 @@ private App() { /** * Program entry point. + * * @param args arguments * @throws InterruptedException if main thread is interrupted. - * @throws ExecutionException if an execution error occurs. + * @throws ExecutionException if an execution error occurs. */ public static void main(String[] args) throws InterruptedException, ExecutionException { - App app = new App(); + var app = new App(); try { app.promiseUsage(); } finally { @@ -100,13 +101,12 @@ private void promiseUsage() { * consume the result in a Consumer */ private void calculateLowestFrequencyChar() { - lowestFrequencyChar() - .thenAccept( - charFrequency -> { - LOGGER.info("Char with lowest frequency is: {}", charFrequency); - taskCompleted(); - } - ); + lowestFrequencyChar().thenAccept( + charFrequency -> { + LOGGER.info("Char with lowest frequency is: {}", charFrequency); + taskCompleted(); + } + ); } /* @@ -114,13 +114,12 @@ private void calculateLowestFrequencyChar() { * in a Consumer */ private void calculateLineCount() { - countLines() - .thenAccept( - count -> { - LOGGER.info("Line count is: {}", count); - taskCompleted(); - } - ); + countLines().thenAccept( + count -> { + LOGGER.info("Line count is: {}", count); + taskCompleted(); + } + ); } /* @@ -128,17 +127,15 @@ private void calculateLineCount() { * then promise to apply function to calculate lowest character frequency. */ private Promise lowestFrequencyChar() { - return characterFrequency() - .thenApply(Utility::lowestFrequencyChar); + return characterFrequency().thenApply(Utility::lowestFrequencyChar); } /* * Download the file at DEFAULT_URL and when that promise is fulfilled, * then promise to apply function to calculate character frequency. */ - private Promise> characterFrequency() { - return download(DEFAULT_URL) - .thenApply(Utility::characterFrequency); + private Promise> characterFrequency() { + return download(DEFAULT_URL).thenApply(Utility::characterFrequency); } /* @@ -146,8 +143,7 @@ private Promise> characterFrequency() { * then promise to apply function to count lines in that file. */ private Promise countLines() { - return download(DEFAULT_URL) - .thenApply(Utility::countLines); + return download(DEFAULT_URL).thenApply(Utility::countLines); } /* diff --git a/promise/src/main/java/com/iluwatar/promise/Promise.java b/promise/src/main/java/com/iluwatar/promise/Promise.java index eadcc5bd9a7d..9eecf00eb85c 100644 --- a/promise/src/main/java/com/iluwatar/promise/Promise.java +++ b/promise/src/main/java/com/iluwatar/promise/Promise.java @@ -32,10 +32,10 @@ /** * A Promise represents a proxy for a value not necessarily known when the promise is created. It * allows you to associate dependent promises to an asynchronous action's eventual success value or - * failure reason. This lets asynchronous methods return values like synchronous methods: instead - * of the final value, the asynchronous method returns a promise of having a value at some point - * in the future. - * + * failure reason. This lets asynchronous methods return values like synchronous methods: instead of + * the final value, the asynchronous method returns a promise of having a value at some point in the + * future. + * * @param type of result. */ public class Promise extends PromiseSupport { @@ -51,6 +51,7 @@ public Promise() { /** * Fulfills the promise with the provided value. + * * @param value the fulfilled value that can be accessed using {@link #get()}. */ @Override @@ -61,8 +62,9 @@ public void fulfill(T value) { /** * Fulfills the promise with exception due to error in execution. - * @param exception the exception will be wrapped in {@link ExecutionException} - * when accessing the value using {@link #get()}. + * + * @param exception the exception will be wrapped in {@link ExecutionException} when accessing the + * value using {@link #get()}. */ @Override public void fulfillExceptionally(Exception exception) { @@ -86,10 +88,10 @@ private void postFulfillment() { } /** - * Executes the task using the executor in other thread and fulfills the promise returned - * once the task completes either successfully or with an exception. - * - * @param task the task that will provide the value to fulfill the promise. + * Executes the task using the executor in other thread and fulfills the promise returned once the + * task completes either successfully or with an exception. + * + * @param task the task that will provide the value to fulfill the promise. * @param executor the executor in which the task should be run. * @return a promise that represents the result of running the task provided. */ @@ -105,21 +107,23 @@ public Promise fulfillInAsync(final Callable task, Executor executor) { } /** - * Returns a new promise that, when this promise is fulfilled normally, is fulfilled with - * result of this promise as argument to the action provided. + * Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result + * of this promise as argument to the action provided. + * * @param action action to be executed. * @return a new promise. */ public Promise thenAccept(Consumer action) { - Promise dest = new Promise<>(); + var dest = new Promise(); fulfillmentAction = new ConsumeAction(this, dest, action); return dest; } - + /** * Set the exception handler on this promise. - * @param exceptionHandler a consumer that will handle the exception occurred while fulfilling - * the promise. + * + * @param exceptionHandler a consumer that will handle the exception occurred while fulfilling the + * promise. * @return this */ public Promise onError(Consumer exceptionHandler) { @@ -128,8 +132,9 @@ public Promise onError(Consumer exceptionHandler) { } /** - * Returns a new promise that, when this promise is fulfilled normally, is fulfilled with - * result of this promise as argument to the function provided. + * Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result + * of this promise as argument to the function provided. + * * @param func function to be executed. * @return a new promise. */ @@ -140,8 +145,8 @@ public Promise thenApply(Function func) { } /** - * Accesses the value from source promise and calls the consumer, then fulfills the - * destination promise. + * Accesses the value from source promise and calls the consumer, then fulfills the destination + * promise. */ private class ConsumeAction implements Runnable { diff --git a/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java b/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java index 058e899d0b39..7a12f0a0f271 100644 --- a/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java +++ b/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java @@ -27,16 +27,15 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A really simplified implementation of future that allows completing it successfully with a value + * A really simplified implementation of future that allows completing it successfully with a value * or exceptionally with an exception. */ class PromiseSupport implements Future { - + private static final Logger LOGGER = LoggerFactory.getLogger(PromiseSupport.class); private static final int RUNNING = 1; @@ -93,13 +92,12 @@ public T get() throws InterruptedException, ExecutionException { } if (state == COMPLETED) { return value; - } + } throw new ExecutionException(exception); } @Override - public T get(long timeout, TimeUnit unit) - throws ExecutionException, TimeoutException { + public T get(long timeout, TimeUnit unit) throws ExecutionException { synchronized (lock) { while (state == RUNNING) { try { @@ -110,10 +108,10 @@ public T get(long timeout, TimeUnit unit) } } } - + if (state == COMPLETED) { return value; - } + } throw new ExecutionException(exception); } } \ No newline at end of file diff --git a/promise/src/main/java/com/iluwatar/promise/Utility.java b/promise/src/main/java/com/iluwatar/promise/Utility.java index 09c7f6ddc7b3..47755975ab9a 100644 --- a/promise/src/main/java/com/iluwatar/promise/Utility.java +++ b/promise/src/main/java/com/iluwatar/promise/Utility.java @@ -29,13 +29,13 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; -import java.io.Reader; import java.net.URL; -import java.util.HashMap; -import java.util.Iterator; +import java.util.Collections; +import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; - +import java.util.function.Function; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,86 +48,68 @@ public class Utility { /** * Calculates character frequency of the file provided. + * * @param fileLocation location of the file. * @return a map of character to its frequency, an empty map if file does not exist. */ - public static Map characterFrequency(String fileLocation) { - Map characterToFrequency = new HashMap<>(); - try (Reader reader = new FileReader(fileLocation); - BufferedReader bufferedReader = new BufferedReader(reader)) { - for (String line; (line = bufferedReader.readLine()) != null;) { - for (char c : line.toCharArray()) { - if (!characterToFrequency.containsKey(c)) { - characterToFrequency.put(c, 1); - } else { - characterToFrequency.put(c, characterToFrequency.get(c) + 1); - } - } - } + public static Map characterFrequency(String fileLocation) { + try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) { + return bufferedReader.lines() + .flatMapToInt(String::chars) + .mapToObj(x -> (char) x) + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); } catch (IOException ex) { ex.printStackTrace(); } - return characterToFrequency; + return Collections.emptyMap(); } /** * Return the character with the lowest frequency, if exists. + * * @return the character, {@code Optional.empty()} otherwise. */ - public static Character lowestFrequencyChar(Map charFrequency) { - Character lowestFrequencyChar = null; - Iterator> iterator = charFrequency.entrySet().iterator(); - Entry entry = iterator.next(); - int minFrequency = entry.getValue(); - lowestFrequencyChar = entry.getKey(); - - while (iterator.hasNext()) { - entry = iterator.next(); - if (entry.getValue() < minFrequency) { - minFrequency = entry.getValue(); - lowestFrequencyChar = entry.getKey(); - } - } - - return lowestFrequencyChar; + public static Character lowestFrequencyChar(Map charFrequency) { + return charFrequency + .entrySet() + .stream() + .min(Comparator.comparingLong(Entry::getValue)) + .map(Entry::getKey) + .orElseThrow(); } /** * Count the number of lines in a file. + * * @return number of lines, 0 if file does not exist. */ public static Integer countLines(String fileLocation) { - int lineCount = 0; - try (Reader reader = new FileReader(fileLocation); - BufferedReader bufferedReader = new BufferedReader(reader)) { - while (bufferedReader.readLine() != null) { - lineCount++; - } + try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) { + return (int) bufferedReader.lines().count(); } catch (IOException ex) { ex.printStackTrace(); } - return lineCount; + return 0; } /** * Downloads the contents from the given urlString, and stores it in a temporary directory. + * * @return the absolute path of the file downloaded. */ public static String downloadFile(String urlString) throws IOException { LOGGER.info("Downloading contents from url: {}", urlString); - URL url = new URL(urlString); - File file = File.createTempFile("promise_pattern", null); - try (Reader reader = new InputStreamReader(url.openStream()); - BufferedReader bufferedReader = new BufferedReader(reader); - FileWriter writer = new FileWriter(file)) { - for (String line; (line = bufferedReader.readLine()) != null; ) { + var url = new URL(urlString); + var file = File.createTempFile("promise_pattern", null); + try (var bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); + var writer = new FileWriter(file)) { + String line; + while ((line = bufferedReader.readLine()) != null) { writer.write(line); writer.write("\n"); } LOGGER.info("File downloaded at: {}", file.getAbsolutePath()); return file.getAbsolutePath(); - } catch (IOException ex) { - throw ex; } } } diff --git a/promise/src/test/java/com/iluwatar/promise/AppTest.java b/promise/src/test/java/com/iluwatar/promise/AppTest.java index 0913d5911ac5..63ac06aec0af 100644 --- a/promise/src/test/java/com/iluwatar/promise/AppTest.java +++ b/promise/src/test/java/com/iluwatar/promise/AppTest.java @@ -23,12 +23,10 @@ package com.iluwatar.promise; -import org.junit.jupiter.api.Test; - import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Test; /** - * * Application test. */ public class AppTest { diff --git a/promise/src/test/java/com/iluwatar/promise/PromiseTest.java b/promise/src/test/java/com/iluwatar/promise/PromiseTest.java index 9b02191ee007..a72faf01e81c 100644 --- a/promise/src/test/java/com/iluwatar/promise/PromiseTest.java +++ b/promise/src/test/java/com/iluwatar/promise/PromiseTest.java @@ -23,8 +23,13 @@ package com.iluwatar.promise; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; @@ -33,15 +38,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; -import java.util.function.Function; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests Promise class. @@ -58,7 +56,7 @@ public void setUp() { } @Test - public void promiseIsFulfilledWithTheResultantValueOfExecutingTheTask() + public void promiseIsFulfilledWithTheResultantValueOfExecutingTheTask() throws InterruptedException, ExecutionException { promise.fulfillInAsync(new NumberCrunchingTask(), executor); @@ -66,21 +64,20 @@ public void promiseIsFulfilledWithTheResultantValueOfExecutingTheTask() assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); } - + @Test - public void promiseIsFulfilledWithAnExceptionIfTaskThrowsAnException() - throws InterruptedException, ExecutionException, TimeoutException { + public void promiseIsFulfilledWithAnExceptionIfTaskThrowsAnException() + throws InterruptedException, TimeoutException { testWaitingForeverForPromiseToBeFulfilled(); testWaitingSomeTimeForPromiseToBeFulfilled(); } - private void testWaitingForeverForPromiseToBeFulfilled() - throws InterruptedException, TimeoutException { - Promise promise = new Promise<>(); + private void testWaitingForeverForPromiseToBeFulfilled() throws InterruptedException { + var promise = new Promise(); promise.fulfillInAsync(() -> { throw new RuntimeException("Barf!"); }, executor); - + try { promise.get(); fail("Fetching promise should result in exception if the task threw an exception"); @@ -88,7 +85,7 @@ private void testWaitingForeverForPromiseToBeFulfilled() assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); } - + try { promise.get(1000, TimeUnit.SECONDS); fail("Fetching promise should result in exception if the task threw an exception"); @@ -97,14 +94,13 @@ private void testWaitingForeverForPromiseToBeFulfilled() assertFalse(promise.isCancelled()); } } - - private void testWaitingSomeTimeForPromiseToBeFulfilled() - throws InterruptedException, TimeoutException { - Promise promise = new Promise<>(); + + private void testWaitingSomeTimeForPromiseToBeFulfilled() throws InterruptedException { + var promise = new Promise(); promise.fulfillInAsync(() -> { throw new RuntimeException("Barf!"); }, executor); - + try { promise.get(1000, TimeUnit.SECONDS); fail("Fetching promise should result in exception if the task threw an exception"); @@ -112,7 +108,7 @@ private void testWaitingSomeTimeForPromiseToBeFulfilled() assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); } - + try { promise.get(); fail("Fetching promise should result in exception if the task threw an exception"); @@ -120,18 +116,15 @@ private void testWaitingSomeTimeForPromiseToBeFulfilled() assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); } - + } @Test - public void dependentPromiseIsFulfilledAfterTheConsumerConsumesTheResultOfThisPromise() + public void dependentPromiseIsFulfilledAfterTheConsumerConsumesTheResultOfThisPromise() throws InterruptedException, ExecutionException { - Promise dependentPromise = promise + var dependentPromise = promise .fulfillInAsync(new NumberCrunchingTask(), executor) - .thenAccept(value -> { - assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value); - }); - + .thenAccept(value -> assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value)); dependentPromise.get(); assertTrue(dependentPromise.isDone()); @@ -139,9 +132,9 @@ public void dependentPromiseIsFulfilledAfterTheConsumerConsumesTheResultOfThisPr } @Test - public void dependentPromiseIsFulfilledWithAnExceptionIfConsumerThrowsAnException() - throws InterruptedException, ExecutionException, TimeoutException { - Promise dependentPromise = promise + public void dependentPromiseIsFulfilledWithAnExceptionIfConsumerThrowsAnException() + throws InterruptedException { + var dependentPromise = promise .fulfillInAsync(new NumberCrunchingTask(), executor) .thenAccept(value -> { throw new RuntimeException("Barf!"); @@ -155,7 +148,7 @@ public void dependentPromiseIsFulfilledWithAnExceptionIfConsumerThrowsAnExceptio assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); } - + try { dependentPromise.get(1000, TimeUnit.SECONDS); fail("Fetching dependent promise should result in exception " @@ -167,12 +160,12 @@ public void dependentPromiseIsFulfilledWithAnExceptionIfConsumerThrowsAnExceptio } @Test - public void dependentPromiseIsFulfilledAfterTheFunctionTransformsTheResultOfThisPromise() + public void dependentPromiseIsFulfilledAfterTheFunctionTransformsTheResultOfThisPromise() throws InterruptedException, ExecutionException { - Promise dependentPromise = promise + var dependentPromise = promise .fulfillInAsync(new NumberCrunchingTask(), executor) .thenApply(value -> { - assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value); + assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value); return String.valueOf(value); }); @@ -181,11 +174,11 @@ public void dependentPromiseIsFulfilledAfterTheFunctionTransformsTheResultOfThis assertTrue(dependentPromise.isDone()); assertFalse(dependentPromise.isCancelled()); } - + @Test - public void dependentPromiseIsFulfilledWithAnExceptionIfTheFunctionThrowsException() - throws InterruptedException, ExecutionException, TimeoutException { - Promise dependentPromise = promise + public void dependentPromiseIsFulfilledWithAnExceptionIfTheFunctionThrowsException() + throws InterruptedException { + var dependentPromise = promise .fulfillInAsync(new NumberCrunchingTask(), executor) .thenApply(value -> { throw new RuntimeException("Barf!"); @@ -199,7 +192,7 @@ public void dependentPromiseIsFulfilledWithAnExceptionIfTheFunctionThrowsExcepti assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); } - + try { dependentPromise.get(1000, TimeUnit.SECONDS); fail("Fetching dependent promise should result in exception " @@ -209,26 +202,26 @@ public void dependentPromiseIsFulfilledWithAnExceptionIfTheFunctionThrowsExcepti assertFalse(promise.isCancelled()); } } - + @Test - public void fetchingAnAlreadyFulfilledPromiseReturnsTheFulfilledValueImmediately() - throws InterruptedException, ExecutionException, TimeoutException { - Promise promise = new Promise<>(); + public void fetchingAnAlreadyFulfilledPromiseReturnsTheFulfilledValueImmediately() + throws ExecutionException { + var promise = new Promise(); promise.fulfill(NumberCrunchingTask.CRUNCHED_NUMBER); - + promise.get(1000, TimeUnit.SECONDS); } - + @SuppressWarnings("unchecked") @Test public void exceptionHandlerIsCalledWhenPromiseIsFulfilledExceptionally() { - Promise promise = new Promise<>(); - Consumer exceptionHandler = mock(Consumer.class); + var promise = new Promise<>(); + var exceptionHandler = mock(Consumer.class); promise.onError(exceptionHandler); - - Exception exception = new Exception("barf!"); + + var exception = new Exception("barf!"); promise.fulfillExceptionally(exception); - + verify(exceptionHandler).accept(eq(exception)); } diff --git a/property/pom.xml b/property/pom.xml index 4e1a16a0d9f4..d271af036b47 100644 --- a/property/pom.xml +++ b/property/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.property.App + + + + + + + + diff --git a/property/src/main/java/com/iluwatar/property/App.java b/property/src/main/java/com/iluwatar/property/App.java index d37dd5fd7deb..912388e55556 100644 --- a/property/src/main/java/com/iluwatar/property/App.java +++ b/property/src/main/java/com/iluwatar/property/App.java @@ -49,36 +49,36 @@ public class App { */ public static void main(String[] args) { /* set up */ - Prototype charProto = new Character(); + var charProto = new Character(); charProto.set(Stats.STRENGTH, 10); charProto.set(Stats.AGILITY, 10); charProto.set(Stats.ARMOR, 10); charProto.set(Stats.ATTACK_POWER, 10); - Character mageProto = new Character(Type.MAGE, charProto); + var mageProto = new Character(Type.MAGE, charProto); mageProto.set(Stats.INTELLECT, 15); mageProto.set(Stats.SPIRIT, 10); - Character warProto = new Character(Type.WARRIOR, charProto); + var warProto = new Character(Type.WARRIOR, charProto); warProto.set(Stats.RAGE, 15); warProto.set(Stats.ARMOR, 15); // boost default armor for warrior - Character rogueProto = new Character(Type.ROGUE, charProto); + var rogueProto = new Character(Type.ROGUE, charProto); rogueProto.set(Stats.ENERGY, 15); rogueProto.set(Stats.AGILITY, 15); // boost default agility for rogue /* usage */ - Character mag = new Character("Player_1", mageProto); + var mag = new Character("Player_1", mageProto); mag.set(Stats.ARMOR, 8); LOGGER.info(mag.toString()); - Character warrior = new Character("Player_2", warProto); + var warrior = new Character("Player_2", warProto); LOGGER.info(warrior.toString()); - Character rogue = new Character("Player_3", rogueProto); + var rogue = new Character("Player_3", rogueProto); LOGGER.info(rogue.toString()); - Character rogueDouble = new Character("Player_4", rogue); + var rogueDouble = new Character("Player_4", rogue); rogueDouble.set(Stats.ATTACK_POWER, 12); LOGGER.info(rogueDouble.toString()); } diff --git a/property/src/main/java/com/iluwatar/property/Character.java b/property/src/main/java/com/iluwatar/property/Character.java index bbe7014599f2..afe9fe16c644 100644 --- a/property/src/main/java/com/iluwatar/property/Character.java +++ b/property/src/main/java/com/iluwatar/property/Character.java @@ -93,7 +93,7 @@ public Type type() { @Override public Integer get(Stats stat) { - boolean containsValue = properties.containsKey(stat); + var containsValue = properties.containsKey(stat); if (containsValue) { return properties.get(stat); } else { @@ -118,7 +118,7 @@ public void remove(Stats stat) { @Override public String toString() { - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); if (name != null) { builder.append("Player: ").append(name).append('\n'); } @@ -128,8 +128,8 @@ public String toString() { } builder.append("Stats:\n"); - for (Stats stat : Stats.values()) { - Integer value = this.get(stat); + for (var stat : Stats.values()) { + var value = this.get(stat); if (value == null) { continue; } diff --git a/property/src/test/java/com/iluwatar/property/AppTest.java b/property/src/test/java/com/iluwatar/property/AppTest.java index f8096b865c6d..89c0dcbf6a2b 100644 --- a/property/src/test/java/com/iluwatar/property/AppTest.java +++ b/property/src/test/java/com/iluwatar/property/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/property/src/test/java/com/iluwatar/property/CharacterTest.java b/property/src/test/java/com/iluwatar/property/CharacterTest.java index 6bbd693a7d13..d7a67e52c646 100644 --- a/property/src/test/java/com/iluwatar/property/CharacterTest.java +++ b/property/src/test/java/com/iluwatar/property/CharacterTest.java @@ -23,14 +23,15 @@ package com.iluwatar.property; -import org.junit.jupiter.api.Test; - import static com.iluwatar.property.Character.Type; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + /** * Date: 12/28/15 - 7:46 PM * @@ -40,13 +41,13 @@ public class CharacterTest { @Test public void testPrototypeStats() throws Exception { - final Character prototype = new Character(); + final var prototype = new Character(); - for (final Stats stat : Stats.values()) { + for (final var stat : Stats.values()) { assertFalse(prototype.has(stat)); assertNull(prototype.get(stat)); - final Integer expectedValue = stat.ordinal(); + final var expectedValue = stat.ordinal(); prototype.set(stat, expectedValue); assertTrue(prototype.has(stat)); assertEquals(expectedValue, prototype.get(stat)); @@ -59,15 +60,13 @@ public void testPrototypeStats() throws Exception { } @Test - public void testCharacterStats() throws Exception { - final Character prototype = new Character(); - for (final Stats stat : Stats.values()) { - prototype.set(stat, stat.ordinal()); - } + public void testCharacterStats() { + final var prototype = new Character(); + Arrays.stream(Stats.values()).forEach(stat -> prototype.set(stat, stat.ordinal())); - final Character mage = new Character(Type.MAGE, prototype); - for (final Stats stat : Stats.values()) { - final Integer expectedValue = stat.ordinal(); + final var mage = new Character(Type.MAGE, prototype); + for (final var stat : Stats.values()) { + final var expectedValue = stat.ordinal(); assertTrue(mage.has(stat)); assertEquals(expectedValue, mage.get(stat)); } @@ -75,17 +74,17 @@ public void testCharacterStats() throws Exception { @Test public void testToString() { - final Character prototype = new Character(); + final var prototype = new Character(); prototype.set(Stats.ARMOR, 1); prototype.set(Stats.AGILITY, 2); prototype.set(Stats.INTELLECT, 3); assertEquals("Stats:\n - AGILITY:2\n - ARMOR:1\n - INTELLECT:3\n", prototype.toString()); - final Character stupid = new Character(Type.ROGUE, prototype); + final var stupid = new Character(Type.ROGUE, prototype); stupid.remove(Stats.INTELLECT); assertEquals("Character type: ROGUE\nStats:\n - AGILITY:2\n - ARMOR:1\n", stupid.toString()); - final Character weak = new Character("weak", prototype); + final var weak = new Character("weak", prototype); weak.remove(Stats.ARMOR); assertEquals("Player: weak\nStats:\n - AGILITY:2\n - INTELLECT:3\n", weak.toString()); @@ -93,32 +92,32 @@ public void testToString() { @Test public void testName() { - final Character prototype = new Character(); + final var prototype = new Character(); prototype.set(Stats.ARMOR, 1); prototype.set(Stats.INTELLECT, 2); assertNull(prototype.name()); - final Character stupid = new Character(Type.ROGUE, prototype); + final var stupid = new Character(Type.ROGUE, prototype); stupid.remove(Stats.INTELLECT); assertNull(stupid.name()); - final Character weak = new Character("weak", prototype); + final var weak = new Character("weak", prototype); weak.remove(Stats.ARMOR); assertEquals("weak", weak.name()); } @Test public void testType() { - final Character prototype = new Character(); + final var prototype = new Character(); prototype.set(Stats.ARMOR, 1); prototype.set(Stats.INTELLECT, 2); assertNull(prototype.type()); - final Character stupid = new Character(Type.ROGUE, prototype); + final var stupid = new Character(Type.ROGUE, prototype); stupid.remove(Stats.INTELLECT); assertEquals(Type.ROGUE, stupid.type()); - final Character weak = new Character("weak", prototype); + final var weak = new Character("weak", prototype); weak.remove(Stats.ARMOR); assertNull(weak.type()); } diff --git a/prototype/README.md b/prototype/README.md index 1cbe6724479b..65d0dbb88cb0 100644 --- a/prototype/README.md +++ b/prototype/README.md @@ -52,11 +52,11 @@ class Sheep implements Cloneable { Then it can be cloned like below ```java -Sheep original = new Sheep("Jolly"); +var original = new Sheep("Jolly"); System.out.println(original.getName()); // Jolly // Clone and modify what is required -Sheep cloned = original.clone(); +var cloned = original.clone(); cloned.setName("Dolly"); System.out.println(cloned.getName()); // Dolly ``` diff --git a/prototype/pom.xml b/prototype/pom.xml index 7a8a685cc260..e68b11892ef2 100644 --- a/prototype/pom.xml +++ b/prototype/pom.xml @@ -49,4 +49,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.prototype.App + + + + + + + + diff --git a/prototype/src/main/java/com/iluwatar/prototype/App.java b/prototype/src/main/java/com/iluwatar/prototype/App.java index 9b1d4eb320b3..526a13848c60 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/App.java +++ b/prototype/src/main/java/com/iluwatar/prototype/App.java @@ -46,24 +46,23 @@ public class App { * @param args command line args */ public static void main(String[] args) { - HeroFactory factory = new HeroFactoryImpl( + var factory = new HeroFactoryImpl( new ElfMage("cooking"), new ElfWarlord("cleaning"), new ElfBeast("protecting") ); - Mage mage = factory.createMage(); - Warlord warlord = factory.createWarlord(); - Beast beast = factory.createBeast(); + var mage = factory.createMage(); + var warlord = factory.createWarlord(); + var beast = factory.createBeast(); LOGGER.info(mage.toString()); LOGGER.info(warlord.toString()); LOGGER.info(beast.toString()); - factory = - new HeroFactoryImpl( - new OrcMage("axe"), - new OrcWarlord("sword"), - new OrcBeast("laser") - ); + factory = new HeroFactoryImpl( + new OrcMage("axe"), + new OrcWarlord("sword"), + new OrcBeast("laser") + ); mage = factory.createMage(); warlord = factory.createWarlord(); beast = factory.createBeast(); diff --git a/prototype/src/main/java/com/iluwatar/prototype/Beast.java b/prototype/src/main/java/com/iluwatar/prototype/Beast.java index c6797fd29a0b..a5fc0158eee8 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Beast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Beast.java @@ -28,9 +28,11 @@ */ public abstract class Beast implements Prototype { - public Beast() { } + public Beast() { + } - public Beast(Beast source) { } + public Beast(Beast source) { + } @Override public abstract Beast copy(); diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java index e88f11699c83..1401460d62e0 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java @@ -60,15 +60,11 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - ElfBeast other = (ElfBeast) obj; + var other = (ElfBeast) obj; if (helpType == null) { - if (other.helpType != null) { - return false; - } - } else if (!helpType.equals(other.helpType)) { - return false; + return other.helpType == null; } - return true; + return helpType.equals(other.helpType); } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java index d569a18c2482..4a7eea98f9b3 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java @@ -60,14 +60,10 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - ElfMage other = (ElfMage) obj; + var other = (ElfMage) obj; if (helpType == null) { - if (other.helpType != null) { - return false; - } - } else if (!helpType.equals(other.helpType)) { - return false; + return other.helpType == null; } - return true; + return helpType.equals(other.helpType); } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java index 3484198d5316..101cd59427e6 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java @@ -60,14 +60,10 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - ElfWarlord other = (ElfWarlord) obj; + var other = (ElfWarlord) obj; if (helpType == null) { - if (other.helpType != null) { - return false; - } - } else if (!helpType.equals(other.helpType)) { - return false; + return other.helpType == null; } - return true; + return helpType.equals(other.helpType); } } \ No newline at end of file diff --git a/prototype/src/main/java/com/iluwatar/prototype/Mage.java b/prototype/src/main/java/com/iluwatar/prototype/Mage.java index f8a597805feb..ca2cc6db49ea 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Mage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Mage.java @@ -28,9 +28,11 @@ */ public abstract class Mage implements Prototype { - public Mage() { } + public Mage() { + } - public Mage(Mage source) { } + public Mage(Mage source) { + } @Override public abstract Mage copy(); diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java index 020063616f19..cf3dc18d8758 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java @@ -60,15 +60,11 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - OrcBeast other = (OrcBeast) obj; + var other = (OrcBeast) obj; if (weapon == null) { - if (other.weapon != null) { - return false; - } - } else if (!weapon.equals(other.weapon)) { - return false; + return other.weapon == null; } - return true; + return weapon.equals(other.weapon); } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java index e14145434f43..cb8239c3fc9b 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java @@ -60,14 +60,10 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - OrcMage other = (OrcMage) obj; + var other = (OrcMage) obj; if (weapon == null) { - if (other.weapon != null) { - return false; - } - } else if (!weapon.equals(other.weapon)) { - return false; + return other.weapon == null; } - return true; + return weapon.equals(other.weapon); } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java index cc5e17d8e9c3..39facc41ee22 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java @@ -60,14 +60,10 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - OrcWarlord other = (OrcWarlord) obj; + var other = (OrcWarlord) obj; if (weapon == null) { - if (other.weapon != null) { - return false; - } - } else if (!weapon.equals(other.weapon)) { - return false; + return other.weapon == null; } - return true; + return weapon.equals(other.weapon); } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java index 30a3cd75cd92..3df514be479a 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java @@ -28,9 +28,11 @@ */ public abstract class Warlord implements Prototype { - public Warlord() { } + public Warlord() { + } - public Warlord(Warlord source) { } + public Warlord(Warlord source) { + } @Override public abstract Warlord copy(); diff --git a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java index 4943339e8c5c..489b6365ce6f 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java index 579746ecc6c1..c3a8d89999f7 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java @@ -23,37 +23,40 @@ package com.iluwatar.prototype; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; import java.util.Collection; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Date: 12/28/15 - 8:45 PM + * * @param

Prototype * @author Jeroen Meulemeester */ public class PrototypeTest

{ static Collection dataProvider() { return List.of( - new Object[]{new OrcBeast("axe"), "Orcish wolf attacks with axe"}, - new Object[]{new OrcMage("sword"), "Orcish mage attacks with sword"}, - new Object[]{new OrcWarlord("laser"), "Orcish warlord attacks with laser"}, - new Object[]{new ElfBeast("cooking"), "Elven eagle helps in cooking"}, - new Object[]{new ElfMage("cleaning"), "Elven mage helps in cleaning"}, - new Object[]{new ElfWarlord("protecting"), "Elven warlord helps in protecting"} + new Object[]{new OrcBeast("axe"), "Orcish wolf attacks with axe"}, + new Object[]{new OrcMage("sword"), "Orcish mage attacks with sword"}, + new Object[]{new OrcWarlord("laser"), "Orcish warlord attacks with laser"}, + new Object[]{new ElfBeast("cooking"), "Elven eagle helps in cooking"}, + new Object[]{new ElfMage("cleaning"), "Elven mage helps in cleaning"}, + new Object[]{new ElfWarlord("protecting"), "Elven warlord helps in protecting"} ); } @ParameterizedTest @MethodSource("dataProvider") - public void testPrototype(P testedPrototype, String expectedToString) throws Exception { + public void testPrototype(P testedPrototype, String expectedToString) { assertEquals(expectedToString, testedPrototype.toString()); - final Object clone = testedPrototype.copy(); + final var clone = testedPrototype.copy(); assertNotNull(clone); assertNotSame(clone, testedPrototype); assertSame(testedPrototype.getClass(), clone.getClass()); diff --git a/proxy/README.md b/proxy/README.md index b5fae677de1c..f9538f4cda82 100644 --- a/proxy/README.md +++ b/proxy/README.md @@ -100,7 +100,7 @@ public class WizardTowerProxy implements WizardTower { And here is tower entering scenario ```java -WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower()); +var proxy = new WizardTowerProxy(new IvoryTower()); proxy.enter(new Wizard("Red wizard")); // Red wizard enters the tower. proxy.enter(new Wizard("White wizard")); // White wizard enters the tower. proxy.enter(new Wizard("Black wizard")); // Black wizard enters the tower. diff --git a/proxy/pom.xml b/proxy/pom.xml index e08c6ad87b51..f54c77dcf137 100644 --- a/proxy/pom.xml +++ b/proxy/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.proxy.App + + + + + + + + diff --git a/proxy/src/main/java/com/iluwatar/proxy/App.java b/proxy/src/main/java/com/iluwatar/proxy/App.java index ff02a6074fec..18a4f1348f98 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/App.java +++ b/proxy/src/main/java/com/iluwatar/proxy/App.java @@ -44,7 +44,7 @@ public class App { */ public static void main(String[] args) { - WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower()); + var proxy = new WizardTowerProxy(new IvoryTower()); proxy.enter(new Wizard("Red wizard")); proxy.enter(new Wizard("White wizard")); proxy.enter(new Wizard("Black wizard")); diff --git a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java index 7fcae7530aa4..2fdd5253e2b0 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java b/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java index ed3d6416c608..8c29df9b67f2 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java @@ -23,14 +23,15 @@ package com.iluwatar.proxy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.proxy.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Tests for {@link IvoryTower} */ @@ -49,18 +50,16 @@ public void tearDown() { } @Test - public void testEnter() throws Exception { - final Wizard[] wizards = new Wizard[]{ + public void testEnter() { + final var wizards = List.of( new Wizard("Gandalf"), new Wizard("Dumbledore"), new Wizard("Oz"), new Wizard("Merlin") - }; + ); - IvoryTower tower = new IvoryTower(); - for (Wizard wizard : wizards) { - tower.enter(wizard); - } + var tower = new IvoryTower(); + wizards.forEach(tower::enter); assertTrue(appender.logContains("Gandalf enters the tower.")); assertTrue(appender.logContains("Dumbledore enters the tower.")); diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java index db6ae5c33921..82df04b0dc4d 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java @@ -23,20 +23,19 @@ package com.iluwatar.proxy; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.List; +import org.junit.jupiter.api.Test; + /** * Tests for {@link Wizard} */ public class WizardTest { @Test - public void testToString() throws Exception { - final String[] wizardNames = {"Gandalf", "Dumbledore", "Oz", "Merlin"}; - for (String name : wizardNames) { - assertEquals(name, new Wizard(name).toString()); - } + public void testToString() { + List.of("Gandalf", "Dumbledore", "Oz", "Merlin") + .forEach(name -> assertEquals(name, new Wizard(name).toString())); } } \ No newline at end of file diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java index 6a51e4cbbda1..ff023b81846b 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java @@ -23,14 +23,15 @@ package com.iluwatar.proxy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.proxy.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Tests for {@link WizardTowerProxy} */ @@ -50,17 +51,15 @@ public void tearDown() { @Test public void testEnter() throws Exception { - final Wizard[] wizards = new Wizard[]{ + final var wizards = List.of( new Wizard("Gandalf"), new Wizard("Dumbledore"), new Wizard("Oz"), new Wizard("Merlin") - }; + ); - final WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower()); - for (Wizard wizard : wizards) { - proxy.enter(wizard); - } + final var proxy = new WizardTowerProxy(new IvoryTower()); + wizards.forEach(proxy::enter); assertTrue(appender.logContains("Gandalf enters the tower.")); assertTrue(appender.logContains("Dumbledore enters the tower.")); diff --git a/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java b/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java index ebe841f2b26c..2187c33002e2 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java +++ b/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java @@ -26,10 +26,9 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.slf4j.LoggerFactory; - import java.util.LinkedList; import java.util.List; +import org.slf4j.LoggerFactory; /** @@ -54,7 +53,7 @@ protected void append(ILoggingEvent eventObject) { } public boolean logContains(String message) { - return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + return log.stream().map(ILoggingEvent::getFormattedMessage).anyMatch(message::equals); } public int getLogSize() { diff --git a/queue-load-leveling/pom.xml b/queue-load-leveling/pom.xml index b77466934933..ee6e6c623288 100644 --- a/queue-load-leveling/pom.xml +++ b/queue-load-leveling/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.queue.load.leveling.App + + + + + + + + diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java index ba7aac954d65..c73caf242920 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java @@ -78,17 +78,17 @@ public static void main(String[] args) { try { // Create a MessageQueue object. - MessageQueue msgQueue = new MessageQueue(); + var msgQueue = new MessageQueue(); LOGGER.info("Submitting TaskGenerators and ServiceExecutor threads."); // Create three TaskGenerator threads. Each of them will submit different number of jobs. - final Runnable taskRunnable1 = new TaskGenerator(msgQueue, 5); - final Runnable taskRunnable2 = new TaskGenerator(msgQueue, 1); - final Runnable taskRunnable3 = new TaskGenerator(msgQueue, 2); + final var taskRunnable1 = new TaskGenerator(msgQueue, 5); + final var taskRunnable2 = new TaskGenerator(msgQueue, 1); + final var taskRunnable3 = new TaskGenerator(msgQueue, 2); // Create e service which should process the submitted jobs. - final Runnable srvRunnable = new ServiceExecutor(msgQueue); + final var srvRunnable = new ServiceExecutor(msgQueue); // Create a ThreadPool of 2 threads and // submit all Runnable task for execution to executor.. diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java index 6d55d026b5be..339ea28676ee 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java @@ -40,7 +40,7 @@ public class MessageQueue { // Default constructor when called creates Blocking Queue object. public MessageQueue() { - this.blkQueue = new ArrayBlockingQueue(1024); + this.blkQueue = new ArrayBlockingQueue<>(1024); } /** @@ -62,13 +62,11 @@ public void submitMsg(Message msg) { * them. Retrieves and removes the head of this queue, or returns null if this queue is empty. */ public Message retrieveMsg() { - Message retrievedMsg = null; try { - retrievedMsg = blkQueue.poll(); + return blkQueue.poll(); } catch (Exception e) { LOGGER.error(e.getMessage()); } - - return retrievedMsg; + return null; } -} \ No newline at end of file +} diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java index e490e9dd77b7..2a33286a02a0 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java @@ -46,7 +46,7 @@ public ServiceExecutor(MessageQueue msgQueue) { public void run() { try { while (!Thread.currentThread().isInterrupted()) { - Message msg = msgQueue.retrieveMsg(); + var msg = msgQueue.retrieveMsg(); if (null != msg) { LOGGER.info(msg.toString() + " is served."); diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java index 885e51652857..492b5862363a 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java @@ -63,12 +63,11 @@ public void submit(Message msg) { * submission TaskGenerator thread will sleep for 1 second. */ public void run() { - - int count = this.msgCount; + var count = this.msgCount; try { while (count > 0) { - String statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName(); + var statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName(); this.submit(new Message(statusMsg)); LOGGER.info(statusMsg); diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java index b8d772f3929e..55c9528e6d6b 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java @@ -25,15 +25,12 @@ import org.junit.jupiter.api.Test; -import java.io.IOException; - /** * Application Test */ public class AppTest { @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + public void test() { + App.main(new String[]{}); } } \ No newline at end of file diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java index 0333a666df87..b712853f6c8d 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java @@ -23,25 +23,23 @@ package com.iluwatar.queue.load.leveling; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + /** - * * Test case for submitting and retrieving messages from Blocking Queue. - * */ public class MessageQueueTest { @Test public void messageQueueTest() { - - MessageQueue msgQueue = new MessageQueue(); - + + var msgQueue = new MessageQueue(); + // submit message msgQueue.submitMsg(new Message("MessageQueue Test")); - + // retrieve message assertEquals("MessageQueue Test", msgQueue.retrieveMsg().getMsg()); } diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java index 4dad771628c3..15b90078c7fc 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java @@ -23,23 +23,21 @@ package com.iluwatar.queue.load.leveling; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + /** - * * Test case for creating and checking the Message. - * */ public class MessageTest { - + @Test public void messageTest() { - + // Parameterized constructor test. - String testMsg = "Message Test"; - Message msg = new Message(testMsg); + var testMsg = "Message Test"; + var msg = new Message(testMsg); assertEquals(testMsg, msg.getMsg()); } } diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java index a6cd3d36c2eb..1e81c5d118a5 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java @@ -26,25 +26,23 @@ import org.junit.jupiter.api.Test; /** - * - * Test case for submitting Message to Blocking Queue by TaskGenerator - * and retrieve the message by ServiceExecutor. - * + * Test case for submitting Message to Blocking Queue by TaskGenerator and retrieve the message by + * ServiceExecutor. */ public class TaskGenSrvExeTest { @Test public void taskGeneratorTest() { - MessageQueue msgQueue = new MessageQueue(); - + var msgQueue = new MessageQueue(); + // Create a task generator thread with 1 job to submit. - Runnable taskRunnable = new TaskGenerator(msgQueue, 1); - Thread taskGenThr = new Thread(taskRunnable); + var taskRunnable = new TaskGenerator(msgQueue, 1); + var taskGenThr = new Thread(taskRunnable); taskGenThr.start(); - + // Create a service executor thread. - Runnable srvRunnable = new ServiceExecutor(msgQueue); - Thread srvExeThr = new Thread(srvRunnable); + var srvRunnable = new ServiceExecutor(msgQueue); + var srvExeThr = new Thread(srvRunnable); srvExeThr.start(); } diff --git a/reactor/pom.xml b/reactor/pom.xml index 7610804309e5..b95b0b6e2df6 100644 --- a/reactor/pom.xml +++ b/reactor/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.reactor.app.App + + + + + + + + diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/App.java b/reactor/src/main/java/com/iluwatar/reactor/app/App.java index 0804f8862175..3bd8176a6162 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/App.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/App.java @@ -124,15 +124,17 @@ public void start() throws IOException { * This represents application specific business logic that dispatcher will call on appropriate * events. These events are read events in our example. */ - LoggingHandler loggingHandler = new LoggingHandler(); + var loggingHandler = new LoggingHandler(); /* * Our application binds to multiple channels and uses same logging handler to handle incoming * log requests. */ - reactor.registerChannel(tcpChannel(6666, loggingHandler)) + reactor + .registerChannel(tcpChannel(6666, loggingHandler)) .registerChannel(tcpChannel(6667, loggingHandler)) - .registerChannel(udpChannel(6668, loggingHandler)).start(); + .registerChannel(udpChannel(6668, loggingHandler)) + .start(); } /** @@ -144,20 +146,20 @@ public void start() throws IOException { public void stop() throws InterruptedException, IOException { reactor.stop(); dispatcher.stop(); - for (AbstractNioChannel channel : channels) { + for (var channel : channels) { channel.getJavaChannel().close(); } } private AbstractNioChannel tcpChannel(int port, ChannelHandler handler) throws IOException { - NioServerSocketChannel channel = new NioServerSocketChannel(port, handler); + var channel = new NioServerSocketChannel(port, handler); channel.bind(); channels.add(channel); return channel; } private AbstractNioChannel udpChannel(int port, ChannelHandler handler) throws IOException { - NioDatagramChannel channel = new NioDatagramChannel(port, handler); + var channel = new NioDatagramChannel(port, handler); channel.bind(); channels.add(channel); return channel; diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java index a15437396980..ec6022621551 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.io.PrintWriter; import java.net.DatagramPacket; import java.net.DatagramSocket; @@ -55,7 +54,7 @@ public class AppClient { * @throws IOException if any I/O error occurs. */ public static void main(String[] args) throws IOException { - AppClient appClient = new AppClient(); + var appClient = new AppClient(); appClient.start(); } @@ -118,8 +117,8 @@ public TcpLoggingClient(String clientName, int serverPort) { @Override public void run() { try (Socket socket = new Socket(InetAddress.getLocalHost(), serverPort)) { - OutputStream outputStream = socket.getOutputStream(); - PrintWriter writer = new PrintWriter(outputStream); + var outputStream = socket.getOutputStream(); + var writer = new PrintWriter(outputStream); sendLogRequests(writer, socket.getInputStream()); } catch (IOException e) { LOGGER.error("error sending requests", e); @@ -128,12 +127,12 @@ public void run() { } private void sendLogRequests(PrintWriter writer, InputStream inputStream) throws IOException { - for (int i = 0; i < 4; i++) { + for (var i = 0; i < 4; i++) { writer.println(clientName + " - Log request: " + i); writer.flush(); - byte[] data = new byte[1024]; - int read = inputStream.read(data, 0, data.length); + var data = new byte[1024]; + var read = inputStream.read(data, 0, data.length); if (read == 0) { LOGGER.info("Read zero bytes"); } else { @@ -167,17 +166,17 @@ public UdpLoggingClient(String clientName, int port) throws UnknownHostException @Override public void run() { - try (DatagramSocket socket = new DatagramSocket()) { - for (int i = 0; i < 4; i++) { + try (var socket = new DatagramSocket()) { + for (var i = 0; i < 4; i++) { - String message = clientName + " - Log request: " + i; - DatagramPacket request = - new DatagramPacket(message.getBytes(), message.getBytes().length, remoteAddress); + var message = clientName + " - Log request: " + i; + var bytes = message.getBytes(); + var request = new DatagramPacket(bytes, bytes.length, remoteAddress); socket.send(request); - byte[] data = new byte[1024]; - DatagramPacket reply = new DatagramPacket(data, data.length); + var data = new byte[1024]; + var reply = new DatagramPacket(data, data.length); socket.receive(reply); if (reply.getLength() == 0) { LOGGER.info("Read zero bytes"); diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java b/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java index edf7e26fde73..8babaa3a0778 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java @@ -54,7 +54,7 @@ public void handleChannelRead(AbstractNioChannel channel, Object readObject, Sel doLogging((ByteBuffer) readObject); sendReply(channel, key); } else if (readObject instanceof DatagramPacket) { - DatagramPacket datagram = (DatagramPacket) readObject; + var datagram = (DatagramPacket) readObject; doLogging(datagram.getData()); sendReply(channel, datagram, key); } else { @@ -71,14 +71,14 @@ private static void sendReply( * Create a reply acknowledgement datagram packet setting the receiver to the sender of incoming * message. */ - DatagramPacket replyPacket = new DatagramPacket(ByteBuffer.wrap(ACK)); + var replyPacket = new DatagramPacket(ByteBuffer.wrap(ACK)); replyPacket.setReceiver(incomingPacket.getSender()); channel.write(replyPacket, key); } private static void sendReply(AbstractNioChannel channel, SelectionKey key) { - ByteBuffer buffer = ByteBuffer.wrap(ACK); + var buffer = ByteBuffer.wrap(ACK); channel.write(buffer, key); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java index 6b356d02137a..7adf18166ab7 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java @@ -46,8 +46,7 @@ public abstract class AbstractNioChannel { private final SelectableChannel channel; private final ChannelHandler handler; - private final Map> channelToPendingWrites = - new ConcurrentHashMap<>(); + private final Map> channelToPendingWrites; private NioReactor reactor; /** @@ -59,6 +58,7 @@ public abstract class AbstractNioChannel { public AbstractNioChannel(ChannelHandler handler, SelectableChannel channel) { this.handler = handler; this.channel = channel; + this.channelToPendingWrites = new ConcurrentHashMap<>(); } /** @@ -117,18 +117,14 @@ public ChannelHandler getHandler() { * whole pending block of data at once. */ void flush(SelectionKey key) throws IOException { - Queue pendingWrites = channelToPendingWrites.get(key.channel()); - while (true) { - Object pendingWrite = pendingWrites.poll(); - if (pendingWrite == null) { - // We don't have anything more to write so channel is interested in reading more data - reactor.changeOps(key, SelectionKey.OP_READ); - break; - } - + var pendingWrites = channelToPendingWrites.get(key.channel()); + Object pendingWrite; + while ((pendingWrite = pendingWrites.poll()) != null) { // ask the concrete channel to make sense of data and write it to java channel doWrite(pendingWrite, key); } + // We don't have anything more to write so channel is interested in reading more data + reactor.changeOps(key, SelectionKey.OP_READ); } /** @@ -162,7 +158,7 @@ void flush(SelectionKey key) throws IOException { * @param key the key which is writable. */ public void write(Object data, SelectionKey key) { - Queue pendingWrites = this.channelToPendingWrites.get(key.channel()); + var pendingWrites = this.channelToPendingWrites.get(key.channel()); if (pendingWrites == null) { synchronized (this.channelToPendingWrites) { pendingWrites = this.channelToPendingWrites.get(key.channel()); diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java index ba4b68231725..13657cdb27e4 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java @@ -73,15 +73,15 @@ public int getInterestedOps() { */ @Override public DatagramPacket read(SelectionKey key) throws IOException { - ByteBuffer buffer = ByteBuffer.allocate(1024); - SocketAddress sender = ((DatagramChannel) key.channel()).receive(buffer); + var buffer = ByteBuffer.allocate(1024); + var sender = ((DatagramChannel) key.channel()).receive(buffer); /* * It is required to create a DatagramPacket because we need to preserve which socket address * acts as destination for sending reply packets. */ buffer.flip(); - DatagramPacket packet = new DatagramPacket(buffer); + var packet = new DatagramPacket(buffer); packet.setSender(sender); return packet; @@ -115,7 +115,7 @@ public void bind() throws IOException { */ @Override protected void doWrite(Object pendingWrite, SelectionKey key) throws IOException { - DatagramPacket pendingPacket = (DatagramPacket) pendingWrite; + var pendingPacket = (DatagramPacket) pendingWrite; getJavaChannel().send(pendingPacket.getData(), pendingPacket.getReceiver()); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java index becf1fd2d35d..1a0b17386285 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java @@ -27,10 +27,7 @@ import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.Iterator; import java.util.Queue; -import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -119,20 +116,15 @@ public void stop() throws InterruptedException, IOException { * @throws IOException if any I/O error occurs. */ public NioReactor registerChannel(AbstractNioChannel channel) throws IOException { - SelectionKey key = channel.getJavaChannel().register(selector, channel.getInterestedOps()); + var key = channel.getJavaChannel().register(selector, channel.getInterestedOps()); key.attach(channel); channel.setReactor(this); return this; } private void eventLoop() throws IOException { - while (true) { - - // honor interrupt request - if (Thread.interrupted()) { - break; - } - + // honor interrupt request + while (!Thread.interrupted()) { // honor any pending commands first processPendingCommands(); @@ -145,12 +137,11 @@ private void eventLoop() throws IOException { /* * Represents the events that have occurred on registered handles. */ - Set keys = selector.selectedKeys(); - - Iterator iterator = keys.iterator(); + var keys = selector.selectedKeys(); + var iterator = keys.iterator(); while (iterator.hasNext()) { - SelectionKey key = iterator.next(); + var key = iterator.next(); if (!key.isValid()) { iterator.remove(); continue; @@ -162,9 +153,9 @@ private void eventLoop() throws IOException { } private void processPendingCommands() { - Iterator iterator = pendingCommands.iterator(); + var iterator = pendingCommands.iterator(); while (iterator.hasNext()) { - Runnable command = iterator.next(); + var command = iterator.next(); command.run(); iterator.remove(); } @@ -185,15 +176,14 @@ private void processKey(SelectionKey key) throws IOException { } private static void onChannelWritable(SelectionKey key) throws IOException { - AbstractNioChannel channel = (AbstractNioChannel) key.attachment(); + var channel = (AbstractNioChannel) key.attachment(); channel.flush(key); } private void onChannelReadable(SelectionKey key) { try { // reads the incoming data in context of reactor main loop. Can this be improved? - Object readObject = ((AbstractNioChannel) key.attachment()).read(key); - + var readObject = ((AbstractNioChannel) key.attachment()).read(key); dispatchReadEvent(key, readObject); } catch (IOException e) { try { @@ -212,10 +202,10 @@ private void dispatchReadEvent(SelectionKey key, Object readObject) { } private void onChannelAcceptable(SelectionKey key) throws IOException { - ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); - SocketChannel socketChannel = serverSocketChannel.accept(); + var serverSocketChannel = (ServerSocketChannel) key.channel(); + var socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); - SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ); + var readKey = socketChannel.register(selector, SelectionKey.OP_READ); readKey.attach(key.attachment()); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java index 7c52a95c3b46..04673f01d4a2 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java @@ -83,9 +83,9 @@ public ServerSocketChannel getJavaChannel() { */ @Override public ByteBuffer read(SelectionKey key) throws IOException { - SocketChannel socketChannel = (SocketChannel) key.channel(); - ByteBuffer buffer = ByteBuffer.allocate(1024); - int read = socketChannel.read(buffer); + var socketChannel = (SocketChannel) key.channel(); + var buffer = ByteBuffer.allocate(1024); + var read = socketChannel.read(buffer); buffer.flip(); if (read == -1) { throw new IOException("Socket closed"); @@ -100,9 +100,9 @@ public ByteBuffer read(SelectionKey key) throws IOException { */ @Override public void bind() throws IOException { - getJavaChannel().socket().bind( - new InetSocketAddress(InetAddress.getLocalHost(), port)); - getJavaChannel().configureBlocking(false); + var javaChannel = getJavaChannel(); + javaChannel.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), port)); + javaChannel.configureBlocking(false); LOGGER.info("Bound TCP socket at port: {}", port); } @@ -112,7 +112,7 @@ public void bind() throws IOException { */ @Override protected void doWrite(Object pendingWrite, SelectionKey key) throws IOException { - ByteBuffer pendingBuffer = (ByteBuffer) pendingWrite; + var pendingBuffer = (ByteBuffer) pendingWrite; ((SocketChannel) key.channel()).write(pendingBuffer); } } diff --git a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java index 4b2f0348abfe..76ddfbdba15d 100644 --- a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java +++ b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java @@ -25,14 +25,12 @@ import com.iluwatar.reactor.framework.SameThreadDispatcher; import com.iluwatar.reactor.framework.ThreadPoolDispatcher; +import java.io.IOException; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - /** - * * This class tests the Distributed Logging service by starting a Reactor and then sending it * concurrent logging requests using multiple clients. */ @@ -42,17 +40,17 @@ public class ReactorTest { /** * Test the application using pooled thread dispatcher. - * - * @throws IOException if any I/O error occurs. + * + * @throws IOException if any I/O error occurs. * @throws InterruptedException if interrupted while stopping the application. */ @Test public void testAppUsingThreadPoolDispatcher() throws IOException, InterruptedException { LOGGER.info("testAppUsingThreadPoolDispatcher start"); - App app = new App(new ThreadPoolDispatcher(2)); + var app = new App(new ThreadPoolDispatcher(2)); app.start(); - AppClient client = new AppClient(); + var client = new AppClient(); client.start(); // allow clients to send requests. Artificial delay. @@ -70,17 +68,17 @@ public void testAppUsingThreadPoolDispatcher() throws IOException, InterruptedEx /** * Test the application using same thread dispatcher. - * - * @throws IOException if any I/O error occurs. + * + * @throws IOException if any I/O error occurs. * @throws InterruptedException if interrupted while stopping the application. */ @Test public void testAppUsingSameThreadDispatcher() throws IOException, InterruptedException { LOGGER.info("testAppUsingSameThreadDispatcher start"); - App app = new App(new SameThreadDispatcher()); + var app = new App(new SameThreadDispatcher()); app.start(); - AppClient client = new AppClient(); + var client = new AppClient(); client.start(); // allow clients to send requests. Artificial delay. diff --git a/reader-writer-lock/pom.xml b/reader-writer-lock/pom.xml index 3892e5c62fee..92f53df66dad 100644 --- a/reader-writer-lock/pom.xml +++ b/reader-writer-lock/pom.xml @@ -43,6 +43,24 @@ mockito-core test - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.reader.writer.lock.App + + + + + + + + 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 f59ba10cc0bb..c482ab7e7670 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 @@ -23,11 +23,9 @@ package com.iluwatar.reader.writer.lock; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; -import java.util.stream.IntStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,19 +56,21 @@ public class App { */ public static void main(String[] args) { - ExecutorService executeService = Executors.newFixedThreadPool(10); - ReaderWriterLock lock = new ReaderWriterLock(); + var executeService = Executors.newFixedThreadPool(10); + var lock = new ReaderWriterLock(); // Start writers - IntStream.range(0, 5) - .forEach(i -> executeService.submit(new Writer("Writer " + i, lock.writeLock(), - ThreadLocalRandom.current().nextLong(5000)))); + for (var i = 0; i < 5; i++) { + var writingTime = ThreadLocalRandom.current().nextLong(5000); + executeService.submit(new Writer("Writer " + i, lock.writeLock(), writingTime)); + } LOGGER.info("Writers added..."); // Start readers - IntStream.range(0, 5) - .forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock(), - ThreadLocalRandom.current().nextLong(10)))); + for (var i = 0; i < 5; i++) { + var readingTime = ThreadLocalRandom.current().nextLong(10); + executeService.submit(new Reader("Reader " + i, lock.readLock(), readingTime)); + } LOGGER.info("Readers added..."); try { @@ -81,9 +81,10 @@ public static void main(String[] args) { } // Start readers - IntStream.range(6, 10) - .forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock(), - ThreadLocalRandom.current().nextLong(10)))); + for (var i = 6; i < 10; i++) { + var readingTime = ThreadLocalRandom.current().nextLong(10); + executeService.submit(new Reader("Reader " + i, lock.readLock(), readingTime)); + } LOGGER.info("More readers added..."); 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 d578b0f21435..99c9b056b0d4 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 @@ -43,7 +43,7 @@ public class ReaderWriterLock implements ReadWriteLock { private static final Logger LOGGER = LoggerFactory.getLogger(ReaderWriterLock.class); - private Object readerMutex = new Object(); + private final Object readerMutex = new Object(); private int currentReaderCount; @@ -57,7 +57,7 @@ public class ReaderWriterLock implements ReadWriteLock { * *

This is the most important field in this class to control the access for reader/writer. */ - private Set globalMutex = new HashSet<>(); + private final Set globalMutex = new HashSet<>(); private ReadLock readerLock = new ReadLock(); private WriteLock writerLock = new WriteLock(); @@ -114,8 +114,8 @@ private void acquireForReaders() { try { globalMutex.wait(); } catch (InterruptedException e) { - LOGGER - .info("InterruptedException while waiting for globalMutex in acquireForReaders", e); + var message = "InterruptedException while waiting for globalMutex in acquireForReaders"; + LOGGER.info(message, e); Thread.currentThread().interrupt(); } } @@ -125,7 +125,6 @@ private void acquireForReaders() { @Override public void unlock() { - synchronized (readerMutex) { currentReaderCount--; // Release the lock only when it is the last reader, it is ensure that the lock is released @@ -142,7 +141,7 @@ public void unlock() { } @Override - public void lockInterruptibly() throws InterruptedException { + public void lockInterruptibly() { throw new UnsupportedOperationException(); } @@ -152,7 +151,7 @@ public boolean tryLock() { } @Override - public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { + public boolean tryLock(long time, TimeUnit unit) { throw new UnsupportedOperationException(); } @@ -170,7 +169,6 @@ private class WriteLock implements Lock { @Override public void lock() { - synchronized (globalMutex) { // Wait until the lock is free. @@ -189,7 +187,6 @@ public void lock() { @Override public void unlock() { - synchronized (globalMutex) { globalMutex.remove(this); // Notify the waiter, other writer or reader @@ -198,7 +195,7 @@ public void unlock() { } @Override - public void lockInterruptibly() throws InterruptedException { + public void lockInterruptibly() { throw new UnsupportedOperationException(); } @@ -208,7 +205,7 @@ public boolean tryLock() { } @Override - public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { + public boolean tryLock(long time, TimeUnit unit) { throw new UnsupportedOperationException(); } 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 0c323724e471..a0175e25950a 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 @@ -31,9 +31,8 @@ public class AppTest { @Test - public void test() throws Exception { - String[] args = {}; - App.main(args); + public void test() { + App.main(new String[]{}); } } 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 1f6edfa3cf3f..ffd1dd4a4c8a 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 @@ -23,19 +23,17 @@ package com.iluwatar.reader.writer.lock; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * @author hongshuwei@gmail.com */ @@ -61,12 +59,12 @@ public void tearDown() { @Test public void testReadAndWrite() throws Exception { - ReaderWriterLock lock = new ReaderWriterLock(); + var lock = new ReaderWriterLock(); - Reader reader1 = new Reader("Reader 1", lock.readLock()); - Writer writer1 = new Writer("Writer 1", lock.writeLock()); + var reader1 = new Reader("Reader 1", lock.readLock()); + var writer1 = new Writer("Writer 1", lock.writeLock()); - ExecutorService executeService = Executors.newFixedThreadPool(2); + var executeService = Executors.newFixedThreadPool(2); executeService.submit(reader1); // Let reader1 execute first Thread.sleep(150); @@ -91,11 +89,11 @@ public void testReadAndWrite() throws Exception { @Test public void testWriteAndRead() throws Exception { - ExecutorService executeService = Executors.newFixedThreadPool(2); - ReaderWriterLock lock = new ReaderWriterLock(); + var executeService = Executors.newFixedThreadPool(2); + var lock = new ReaderWriterLock(); - Reader reader1 = new Reader("Reader 1", lock.readLock()); - Writer writer1 = new Writer("Writer 1", lock.writeLock()); + var reader1 = new Reader("Reader 1", lock.readLock()); + var writer1 = new Writer("Writer 1", lock.writeLock()); executeService.submit(writer1); // Let writer1 execute first 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 849cf32ba802..284a1bc3b599 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 @@ -23,20 +23,18 @@ package com.iluwatar.reader.writer.lock; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.spy; + import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.spy; - /** * @author hongshuwei@gmail.com */ @@ -62,11 +60,11 @@ public void tearDown() { @Test public void testRead() throws Exception { - ExecutorService executeService = Executors.newFixedThreadPool(2); - ReaderWriterLock lock = new ReaderWriterLock(); + var executeService = Executors.newFixedThreadPool(2); + var lock = new ReaderWriterLock(); - Reader reader1 = spy(new Reader("Reader 1", lock.readLock())); - Reader reader2 = spy(new Reader("Reader 2", lock.readLock())); + var reader1 = spy(new Reader("Reader 1", lock.readLock())); + var reader2 = spy(new Reader("Reader 2", lock.readLock())); executeService.submit(reader1); Thread.sleep(150); 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 60c78e57313a..00edf8b54645 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 @@ -23,20 +23,18 @@ package com.iluwatar.reader.writer.lock; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.spy; + import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.spy; - /** * @author hongshuwei@gmail.com */ @@ -62,11 +60,11 @@ public void tearDown() { @Test public void testWrite() throws Exception { - ExecutorService executeService = Executors.newFixedThreadPool(2); - ReaderWriterLock lock = new ReaderWriterLock(); + var executeService = Executors.newFixedThreadPool(2); + var lock = new ReaderWriterLock(); - Writer writer1 = spy(new Writer("Writer 1", lock.writeLock())); - Writer writer2 = spy(new Writer("Writer 2", lock.writeLock())); + var writer1 = spy(new Writer("Writer 1", lock.writeLock())); + var writer2 = spy(new Writer("Writer 2", lock.writeLock())); executeService.submit(writer1); // Let write1 execute first 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 98f14a82bcc0..c7e8bc02a80c 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 @@ -26,10 +26,9 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.slf4j.LoggerFactory; - import java.util.LinkedList; import java.util.List; +import org.slf4j.LoggerFactory; /** * InMemory Log Appender Util. diff --git a/repository/pom.xml b/repository/pom.xml index 3bae29a70ba9..0b98cdb41dbe 100644 --- a/repository/pom.xml +++ b/repository/pom.xml @@ -76,4 +76,23 @@ spring-boot-starter-test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.repository.App + + + + + + + + diff --git a/repository/src/main/java/com/iluwatar/repository/App.java b/repository/src/main/java/com/iluwatar/repository/App.java index ac932b81550d..0308db473809 100644 --- a/repository/src/main/java/com/iluwatar/repository/App.java +++ b/repository/src/main/java/com/iluwatar/repository/App.java @@ -24,7 +24,6 @@ package com.iluwatar.repository; import java.util.List; -import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -55,14 +54,13 @@ public class App { */ public static void main(String[] args) { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - "applicationContext.xml"); - PersonRepository repository = context.getBean(PersonRepository.class); + var context = new ClassPathXmlApplicationContext("applicationContext.xml"); + var repository = context.getBean(PersonRepository.class); - Person peter = new Person("Peter", "Sagan", 17); - Person nasta = new Person("Nasta", "Kuzminova", 25); - Person john = new Person("John", "lawrence", 35); - Person terry = new Person("Terry", "Law", 36); + var peter = new Person("Peter", "Sagan", 17); + var nasta = new Person("Nasta", "Kuzminova", 25); + var john = new Person("John", "lawrence", 35); + var terry = new Person("Terry", "Law", 36); // Add new Person records repository.save(peter); @@ -74,17 +72,15 @@ public static void main(String[] args) { LOGGER.info("Count Person records: {}", repository.count()); // Print all records - List persons = (List) repository.findAll(); - for (Person person : persons) { - LOGGER.info(person.toString()); - } + var persons = (List) repository.findAll(); + persons.stream().map(Person::toString).forEach(LOGGER::info); // Update Person nasta.setName("Barbora"); nasta.setSurname("Spotakova"); repository.save(nasta); - LOGGER.info("Find by id 2: {}", repository.findById(2L).get()); + repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p)); // Remove record from Person repository.deleteById(2L); @@ -93,16 +89,15 @@ public static void main(String[] args) { LOGGER.info("Count Person records: {}", repository.count()); // find by name - Optional p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); - LOGGER.info("Find by John is {}", p.get()); + repository + .findOne(new PersonSpecifications.NameEqualSpec("John")) + .ifPresent(p -> LOGGER.info("Find by John is {}", p)); // find by age persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); LOGGER.info("Find Person with age between 20,40: "); - for (Person person : persons) { - LOGGER.info(person.toString()); - } + persons.stream().map(Person::toString).forEach(LOGGER::info); repository.deleteAll(); diff --git a/repository/src/main/java/com/iluwatar/repository/AppConfig.java b/repository/src/main/java/com/iluwatar/repository/AppConfig.java index 197205773f26..50a23026f489 100644 --- a/repository/src/main/java/com/iluwatar/repository/AppConfig.java +++ b/repository/src/main/java/com/iluwatar/repository/AppConfig.java @@ -25,7 +25,6 @@ import java.sql.SQLException; import java.util.List; -import java.util.Optional; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; @@ -55,7 +54,7 @@ public class AppConfig { */ @Bean(destroyMethod = "close") public DataSource dataSource() { - BasicDataSource basicDataSource = new BasicDataSource(); + var basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName("org.h2.Driver"); basicDataSource.setUrl("jdbc:h2:~/databases/person"); basicDataSource.setUsername("sa"); @@ -68,13 +67,11 @@ public DataSource dataSource() { */ @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - LocalContainerEntityManagerFactoryBean entityManager = - new LocalContainerEntityManagerFactoryBean(); + var entityManager = new LocalContainerEntityManagerFactoryBean(); entityManager.setDataSource(dataSource()); entityManager.setPackagesToScan("com.iluwatar"); entityManager.setPersistenceProvider(new HibernatePersistenceProvider()); entityManager.setJpaProperties(jpaProperties()); - return entityManager; } @@ -82,7 +79,7 @@ public LocalContainerEntityManagerFactoryBean entityManagerFactory() { * Properties for Jpa. */ private static Properties jpaProperties() { - Properties properties = new Properties(); + var properties = new Properties(); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); return properties; @@ -93,7 +90,7 @@ private static Properties jpaProperties() { */ @Bean public JpaTransactionManager transactionManager() throws SQLException { - JpaTransactionManager transactionManager = new JpaTransactionManager(); + var transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } @@ -104,15 +101,13 @@ public JpaTransactionManager transactionManager() throws SQLException { * @param args command line args */ public static void main(String[] args) { + var context = new AnnotationConfigApplicationContext(AppConfig.class); + var repository = context.getBean(PersonRepository.class); - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - AppConfig.class); - PersonRepository repository = context.getBean(PersonRepository.class); - - Person peter = new Person("Peter", "Sagan", 17); - Person nasta = new Person("Nasta", "Kuzminova", 25); - Person john = new Person("John", "lawrence", 35); - Person terry = new Person("Terry", "Law", 36); + var peter = new Person("Peter", "Sagan", 17); + var nasta = new Person("Nasta", "Kuzminova", 25); + var john = new Person("John", "lawrence", 35); + var terry = new Person("Terry", "Law", 36); // Add new Person records repository.save(peter); @@ -124,17 +119,15 @@ public static void main(String[] args) { LOGGER.info("Count Person records: {}", repository.count()); // Print all records - List persons = (List) repository.findAll(); - for (Person person : persons) { - LOGGER.info(person.toString()); - } + var persons = (List) repository.findAll(); + persons.stream().map(Person::toString).forEach(LOGGER::info); // Update Person nasta.setName("Barbora"); nasta.setSurname("Spotakova"); repository.save(nasta); - LOGGER.info("Find by id 2: {}", repository.findById(2L).get()); + repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p)); // Remove record from Person repository.deleteById(2L); @@ -143,16 +136,15 @@ public static void main(String[] args) { LOGGER.info("Count Person records: {}", repository.count()); // find by name - Optional p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); - LOGGER.info("Find by John is {}", p.get()); + repository + .findOne(new PersonSpecifications.NameEqualSpec("John")) + .ifPresent(p -> LOGGER.info("Find by John is {}", p)); // find by age persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); LOGGER.info("Find Person with age between 20,40: "); - for (Person person : persons) { - LOGGER.info(person.toString()); - } + persons.stream().map(Person::toString).forEach(LOGGER::info); context.close(); diff --git a/repository/src/main/java/com/iluwatar/repository/Person.java b/repository/src/main/java/com/iluwatar/repository/Person.java index e83f0ce466cf..ee1602ace19b 100644 --- a/repository/src/main/java/com/iluwatar/repository/Person.java +++ b/repository/src/main/java/com/iluwatar/repository/Person.java @@ -92,9 +92,8 @@ public String toString() { @Override public int hashCode() { - - final int prime = 31; - int result = 1; + final var prime = 31; + var result = 1; result = prime * result + age; result = prime * result + (id == null ? 0 : id.hashCode()); result = prime * result + (name == null ? 0 : name.hashCode()); @@ -113,7 +112,7 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - Person other = (Person) obj; + var other = (Person) obj; if (age != other.age) { return false; } @@ -132,13 +131,9 @@ public boolean equals(Object obj) { return false; } if (surname == null) { - if (other.surname != null) { - return false; - } - } else if (!surname.equals(other.surname)) { - return false; + return other.surname == null; } - return true; + return surname.equals(other.surname); } } diff --git a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java index 149c2488ee1a..f91c0a6e1cc6 100644 --- a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java +++ b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java @@ -50,9 +50,7 @@ public AgeBetweenSpec(int from, int to) { @Override public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { - return cb.between(root.get("age"), from, to); - } } @@ -72,9 +70,7 @@ public NameEqualSpec(String name) { * Get predicate. */ public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { - return cb.equal(root.get("name"), this.name); - } } diff --git a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java index 3b0bff608327..6b47cbe9af5e 100644 --- a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java @@ -23,7 +23,13 @@ package com.iluwatar.repository; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.google.common.collect.Lists; +import java.util.List; +import javax.annotation.Resource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,51 +37,41 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; -import javax.annotation.Resource; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; - /** * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query * by {@link org.springframework.data.jpa.domain.Specification} are also test. - * */ @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = { AppConfig.class }) +@SpringBootTest(classes = {AppConfig.class}) public class AnnotationBasedRepositoryTest { @Resource private PersonRepository repository; - Person peter = new Person("Peter", "Sagan", 17); - Person nasta = new Person("Nasta", "Kuzminova", 25); - Person john = new Person("John", "lawrence", 35); - Person terry = new Person("Terry", "Law", 36); + private Person peter = new Person("Peter", "Sagan", 17); + private Person nasta = new Person("Nasta", "Kuzminova", 25); + private Person john = new Person("John", "lawrence", 35); + private Person terry = new Person("Terry", "Law", 36); - List persons = List.of(peter, nasta, john, terry); + private List persons = List.of(peter, nasta, john, terry); /** * Prepare data for test */ @BeforeEach public void setup() { - repository.saveAll(persons); } @Test public void testFindAll() { - - List actuals = Lists.newArrayList(repository.findAll()); + var actuals = Lists.newArrayList(repository.findAll()); assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals)); } @Test public void testSave() { - - Person terry = repository.findByName("Terry"); + var terry = repository.findByName("Terry"); terry.setSurname("Lee"); terry.setAge(47); repository.save(terry); @@ -87,8 +83,7 @@ public void testSave() { @Test public void testDelete() { - - Person terry = repository.findByName("Terry"); + var terry = repository.findByName("Terry"); repository.delete(terry); assertEquals(3, repository.count()); @@ -97,31 +92,26 @@ public void testDelete() { @Test public void testCount() { - assertEquals(4, repository.count()); } @Test public void testFindAllByAgeBetweenSpec() { - - List persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); + var persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); assertEquals(3, persons.size()); - assertTrue(persons.stream().allMatch((item) -> { - return item.getAge() > 20 && item.getAge() < 40; - })); + assertTrue(persons.stream().allMatch((item) -> item.getAge() > 20 && item.getAge() < 40)); } @Test public void testFindOneByNameEqualSpec() { - - Optional actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + var actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + assertTrue(actual.isPresent()); assertEquals(terry, actual.get()); } @AfterEach public void cleanup() { - repository.deleteAll(); } diff --git a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java index c9f292029b63..403f793af1b1 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java @@ -23,6 +23,12 @@ package com.iluwatar.repository; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.sql.ResultSet; +import java.sql.SQLException; +import javax.sql.DataSource; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -30,19 +36,11 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; -import javax.sql.DataSource; -import java.sql.ResultSet; -import java.sql.SQLException; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - /** * This case is Just for test the Annotation Based configuration - * */ @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = { AppConfig.class }) +@SpringBootTest(classes = {AppConfig.class}) public class AppConfigTest { @Autowired @@ -62,12 +60,11 @@ public void testDataSource() { @Test @Transactional public void testQuery() throws SQLException { - ResultSet resultSet = dataSource.getConnection().createStatement().executeQuery("SELECT 1"); + var resultSet = dataSource.getConnection().createStatement().executeQuery("SELECT 1"); + var expected = "1"; String result = null; - String expected = "1"; while (resultSet.next()) { result = resultSet.getString(1); - } assertEquals(expected, result); } diff --git a/repository/src/test/java/com/iluwatar/repository/AppTest.java b/repository/src/test/java/com/iluwatar/repository/AppTest.java index 8889833f6bfa..b12f03d8cc63 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppTest.java @@ -25,15 +25,12 @@ import org.junit.jupiter.api.Test; -import java.io.IOException; - /** * Tests that Repository example runs without errors. */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java index 614f18dba1af..ad9587acad34 100644 --- a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java @@ -23,7 +23,13 @@ package com.iluwatar.repository; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.google.common.collect.Lists; +import java.util.List; +import javax.annotation.Resource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,50 +37,41 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; -import javax.annotation.Resource; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; - /** * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query * by {@link org.springframework.data.jpa.domain.Specification} are also test. */ @ExtendWith(SpringExtension.class) -@SpringBootTest(properties = { "locations=classpath:applicationContext.xml" }) +@SpringBootTest(properties = {"locations=classpath:applicationContext.xml"}) public class RepositoryTest { @Resource private PersonRepository repository; - Person peter = new Person("Peter", "Sagan", 17); - Person nasta = new Person("Nasta", "Kuzminova", 25); - Person john = new Person("John", "lawrence", 35); - Person terry = new Person("Terry", "Law", 36); + private Person peter = new Person("Peter", "Sagan", 17); + private Person nasta = new Person("Nasta", "Kuzminova", 25); + private Person john = new Person("John", "lawrence", 35); + private Person terry = new Person("Terry", "Law", 36); - List persons = List.of(peter, nasta, john, terry); + private List persons = List.of(peter, nasta, john, terry); /** * Prepare data for test */ @BeforeEach public void setup() { - repository.saveAll(persons); } @Test public void testFindAll() { - - List actuals = Lists.newArrayList(repository.findAll()); + var actuals = Lists.newArrayList(repository.findAll()); assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals)); } @Test public void testSave() { - - Person terry = repository.findByName("Terry"); + var terry = repository.findByName("Terry"); terry.setSurname("Lee"); terry.setAge(47); repository.save(terry); @@ -86,8 +83,7 @@ public void testSave() { @Test public void testDelete() { - - Person terry = repository.findByName("Terry"); + var terry = repository.findByName("Terry"); repository.delete(terry); assertEquals(3, repository.count()); @@ -96,14 +92,12 @@ public void testDelete() { @Test public void testCount() { - assertEquals(4, repository.count()); } @Test public void testFindAllByAgeBetweenSpec() { - - List persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); + var persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); assertEquals(3, persons.size()); assertTrue(persons.stream().allMatch(item -> item.getAge() > 20 && item.getAge() < 40)); @@ -111,14 +105,13 @@ public void testFindAllByAgeBetweenSpec() { @Test public void testFindOneByNameEqualSpec() { - - Optional actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + var actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + assertTrue(actual.isPresent()); assertEquals(terry, actual.get()); } @AfterEach public void cleanup() { - repository.deleteAll(); } diff --git a/resource-acquisition-is-initialization/pom.xml b/resource-acquisition-is-initialization/pom.xml index c368d1b531cc..ef8e19f48b7b 100644 --- a/resource-acquisition-is-initialization/pom.xml +++ b/resource-acquisition-is-initialization/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.resource.acquisition.is.initialization.App + + + + + + + + diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java index 293675e997b9..08b62ee8bbfa 100644 --- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java +++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java @@ -54,11 +54,11 @@ public class App { */ public static void main(String[] args) throws Exception { - try (SlidingDoor slidingDoor = new SlidingDoor()) { + try (var ignored = new SlidingDoor()) { LOGGER.info("Walking in."); } - try (TreasureChest treasureChest = new TreasureChest()) { + try (var ignored = new TreasureChest()) { LOGGER.info("Looting contents."); } } diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java index d890eb4c3bff..c311f939aa9d 100644 --- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java +++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java @@ -38,7 +38,7 @@ public SlidingDoor() { } @Override - public void close() throws Exception { + public void close() { LOGGER.info("Sliding door closes."); } } diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java index 26eab1405102..2e8595b14d53 100644 --- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java +++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java @@ -24,7 +24,6 @@ package com.iluwatar.resource.acquisition.is.initialization; import java.io.Closeable; -import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,7 +39,7 @@ public TreasureChest() { } @Override - public void close() throws IOException { + public void close() { LOGGER.info("Treasure chest closes."); } } diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java index 0e58779aff08..dedeee7e0c7a 100644 --- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java +++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() throws Exception { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java index 10a85c6efdbc..7bba17553a8b 100644 --- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java +++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java @@ -23,19 +23,18 @@ package com.iluwatar.resource.acquisition.is.initialization; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Date: 12/28/15 - 9:31 PM * @@ -56,8 +55,8 @@ public void tearDown() { } @Test - public void testOpenClose() throws Exception { - try (final SlidingDoor door = new SlidingDoor(); final TreasureChest chest = new TreasureChest()) { + public void testOpenClose() { + try (final var ignored = new SlidingDoor(); final var ignored1 = new TreasureChest()) { assertTrue(appender.logContains("Sliding door opens.")); assertTrue(appender.logContains("Treasure chest opens.")); } diff --git a/retry/README.md b/retry/README.md index 27325331de08..0f8345412ac2 100644 --- a/retry/README.md +++ b/retry/README.md @@ -78,7 +78,7 @@ to recover from this error. We can model a 'recoverable' scenario by instantiating `FindCustomer` like this: ```java -final BusinessOperation op = new FindCustomer( +final var op = new FindCustomer( "12345", new CustomerNotFoundException("not found"), new CustomerNotFoundException("still not found"), @@ -97,7 +97,7 @@ worker thread in the database subsystem typically needs 50ms to this: ```java -final BusinessOperation op = new Retry<>( +final var op = new Retry<>( new FindCustomer( "1235", new CustomerNotFoundException("not found"), diff --git a/retry/pom.xml b/retry/pom.xml index d1dc9531f71b..e6c2701e05e2 100644 --- a/retry/pom.xml +++ b/retry/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.retry.App + + + + + + + + diff --git a/retry/src/main/java/com/iluwatar/retry/App.java b/retry/src/main/java/com/iluwatar/retry/App.java index 594c482953b3..06f43c29f98c 100644 --- a/retry/src/main/java/com/iluwatar/retry/App.java +++ b/retry/src/main/java/com/iluwatar/retry/App.java @@ -90,14 +90,14 @@ private static void errorNoRetry() throws Exception { } private static void errorWithRetry() throws Exception { - final Retry retry = new Retry<>( + final var retry = new Retry<>( new FindCustomer("123", new CustomerNotFoundException("not found")), 3, //3 attempts 100, //100 ms delay between attempts e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; - final String customerId = op.perform(); + final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() @@ -105,14 +105,14 @@ private static void errorWithRetry() throws Exception { } private static void errorWithRetryExponentialBackoff() throws Exception { - final RetryExponentialBackoff retry = new RetryExponentialBackoff<>( + final var retry = new RetryExponentialBackoff<>( new FindCustomer("123", new CustomerNotFoundException("not found")), 6, //6 attempts 30000, //30 s max delay between attempts e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; - final String customerId = op.perform(); + final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() diff --git a/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java index c074f9cd49ff..54faf4306c7d 100644 --- a/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java +++ b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java @@ -100,8 +100,8 @@ public T perform() throws BusinessException { } try { - long testDelay = (long) Math.pow(2, this.attempts()) * 1000 + RANDOM.nextInt(1000); - long delay = testDelay < this.maxDelay ? testDelay : maxDelay; + var testDelay = (long) Math.pow(2, this.attempts()) * 1000 + RANDOM.nextInt(1000); + var delay = Math.min(testDelay, this.maxDelay); Thread.sleep(delay); } catch (InterruptedException f) { //ignore diff --git a/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java index b52763099bd4..295d8d76353d 100644 --- a/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java +++ b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java @@ -23,12 +23,12 @@ package com.iluwatar.retry; -import org.junit.jupiter.api.Test; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + /** * Unit tests for {@link FindCustomer}. * @@ -40,33 +40,29 @@ public class FindCustomerTest { */ @Test public void noExceptions() throws Exception { - assertThat( - new FindCustomer("123").perform(), - is("123") - ); + assertThat(new FindCustomer("123").perform(), is("123")); } /** * Throws the given exception. - * + * * @throws Exception the expected exception */ @Test public void oneException() { - assertThrows(BusinessException.class, () -> { - new FindCustomer("123", new BusinessException("test")).perform(); - }); + var findCustomer = new FindCustomer("123", new BusinessException("test")); + assertThrows(BusinessException.class, findCustomer::perform); } /** * Should first throw the given exceptions, then return the given result. - * + * * @throws Exception not an expected exception */ @Test public void resultAfterExceptions() throws Exception { - final BusinessOperation op = new FindCustomer( - "123", + final var op = new FindCustomer( + "123", new CustomerNotFoundException("not found"), new DatabaseNotAvailableException("not available") ); @@ -81,9 +77,6 @@ public void resultAfterExceptions() throws Exception { //ignore } - assertThat( - op.perform(), - is("123") - ); + assertThat(op.perform(), is("123")); } } diff --git a/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java index f07d665af6a3..3ca739fbf0fd 100644 --- a/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java +++ b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java @@ -23,26 +23,27 @@ package com.iluwatar.retry; -import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import org.junit.jupiter.api.Test; + /** * Unit tests for {@link Retry}. * * @author George Aristy (george.aristy@gmail.com) */ public class RetryExponentialBackoffTest { - /** - * Should contain all errors thrown. - */ + /** + * Should contain all errors thrown. + */ @Test - public void errors() throws Exception { - final BusinessException e = new BusinessException("unhandled"); - final RetryExponentialBackoff retry = new RetryExponentialBackoff<>( - () -> { - throw e; + public void errors() { + final var e = new BusinessException("unhandled"); + final var retry = new RetryExponentialBackoff( + () -> { + throw e; }, 2, 0 @@ -53,22 +54,19 @@ public void errors() throws Exception { //ignore } - assertThat( - retry.errors(), - hasItem(e) - ); + assertThat(retry.errors(), hasItem(e)); } - /** - * No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking - * it to attempt twice. - */ + /** + * No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking + * it to attempt twice. + */ @Test public void attempts() { - final BusinessException e = new BusinessException("unhandled"); - final RetryExponentialBackoff retry = new RetryExponentialBackoff<>( - () -> { - throw e; + final var e = new BusinessException("unhandled"); + final var retry = new RetryExponentialBackoff( + () -> { + throw e; }, 2, 0 @@ -79,22 +77,19 @@ public void attempts() { //ignore } - assertThat( - retry.attempts(), - is(1) - ); + assertThat(retry.attempts(), is(1)); } - /** - * Final number of attempts should be equal to the number of attempts asked because we are - * asking it to ignore the exception that will be thrown. - */ + /** + * Final number of attempts should be equal to the number of attempts asked because we are asking + * it to ignore the exception that will be thrown. + */ @Test - public void ignore() throws Exception { - final BusinessException e = new CustomerNotFoundException("customer not found"); - final RetryExponentialBackoff retry = new RetryExponentialBackoff<>( - () -> { - throw e; + public void ignore() { + final var e = new CustomerNotFoundException("customer not found"); + final var retry = new RetryExponentialBackoff( + () -> { + throw e; }, 2, 0, @@ -106,9 +101,6 @@ public void ignore() throws Exception { //ignore } - assertThat( - retry.attempts(), - is(2) - ); + assertThat(retry.attempts(), is(2)); } } diff --git a/retry/src/test/java/com/iluwatar/retry/RetryTest.java b/retry/src/test/java/com/iluwatar/retry/RetryTest.java index 64df9d14d8f9..b36b6a5615fd 100644 --- a/retry/src/test/java/com/iluwatar/retry/RetryTest.java +++ b/retry/src/test/java/com/iluwatar/retry/RetryTest.java @@ -23,12 +23,12 @@ package com.iluwatar.retry; -import org.junit.jupiter.api.Test; - import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import org.junit.jupiter.api.Test; + /** * Unit tests for {@link Retry}. * @@ -40,10 +40,11 @@ public class RetryTest { */ @Test public void errors() { - final BusinessException e = new BusinessException("unhandled"); - final Retry retry = new Retry<>( + final var e = new BusinessException("unhandled"); + final var retry = new Retry( () -> { - throw e; }, + throw e; + }, 2, 0 ); @@ -53,10 +54,7 @@ public void errors() { //ignore } - assertThat( - retry.errors(), - hasItem(e) - ); + assertThat(retry.errors(), hasItem(e)); } /** @@ -65,10 +63,11 @@ public void errors() { */ @Test public void attempts() { - final BusinessException e = new BusinessException("unhandled"); - final Retry retry = new Retry<>( + final var e = new BusinessException("unhandled"); + final var retry = new Retry( () -> { - throw e; }, + throw e; + }, 2, 0 ); @@ -78,22 +77,20 @@ public void attempts() { //ignore } - assertThat( - retry.attempts(), - is(1) - ); + assertThat(retry.attempts(), is(1)); } /** - * Final number of attempts should be equal to the number of attempts asked because we are - * asking it to ignore the exception that will be thrown. + * Final number of attempts should be equal to the number of attempts asked because we are asking + * it to ignore the exception that will be thrown. */ @Test - public void ignore() throws Exception { - final BusinessException e = new CustomerNotFoundException("customer not found"); - final Retry retry = new Retry<>( + public void ignore() { + final var e = new CustomerNotFoundException("customer not found"); + final var retry = new Retry( () -> { - throw e; }, + throw e; + }, 2, 0, ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass()) @@ -104,10 +101,7 @@ public void ignore() throws Exception { //ignore } - assertThat( - retry.attempts(), - is(2) - ); + assertThat(retry.attempts(), is(2)); } } \ No newline at end of file diff --git a/role-object/pom.xml b/role-object/pom.xml index 322122897394..ccb8219ebae8 100644 --- a/role-object/pom.xml +++ b/role-object/pom.xml @@ -41,4 +41,23 @@ + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.roleobject.ApplicationRoleObject + + + + + + + + diff --git a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java index eb76ef34a522..0fc028893b1a 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java @@ -30,37 +30,31 @@ import org.slf4j.LoggerFactory; /** - * 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 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. + * 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 { @@ -72,13 +66,13 @@ public class ApplicationRoleObject { * @param args program arguments */ public static void main(String[] args) { - Customer customer = Customer.newCustomer(Borrower, Investor); + var customer = Customer.newCustomer(Borrower, Investor); logger.info(" the new customer created : {}", customer); - boolean hasBorrowerRole = customer.hasRole(Borrower); + var hasBorrowerRole = customer.hasRole(Borrower); logger.info(" customer has a borrowed role - {}", hasBorrowerRole); - boolean hasInvestorRole = customer.hasRole(Investor); + var hasInvestorRole = customer.hasRole(Investor); logger.info(" customer has an investor role - {}", hasInvestorRole); customer.getRole(Investor, InvestorRole.class) diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java index 1d21c5cc80a9..bca450a382b0 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java @@ -23,6 +23,7 @@ package com.iluwatar.roleobject; +import java.util.Arrays; import java.util.Optional; /** @@ -32,6 +33,7 @@ public abstract class Customer { /** * Add specific role @see {@link Role}. + * * @param role to add * @return true if the operation has been successful otherwise false */ @@ -39,6 +41,7 @@ public abstract class Customer { /** * Check specific role @see {@link Role}. + * * @param role to check * @return true if the role exists otherwise false */ @@ -47,6 +50,7 @@ public abstract class Customer { /** * Remove specific role @see {@link Role}. + * * @param role to remove * @return true if the operation has been successful otherwise false */ @@ -54,6 +58,7 @@ public abstract class Customer { /** * 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 @@ -67,14 +72,13 @@ public static Customer newCustomer() { /** * Create {@link Customer} with given roles. + * * @param role roles * @return Customer */ public static Customer newCustomer(Role... role) { - Customer customer = newCustomer(); - for (Role r : role) { - customer.addRole(r); - } + var customer = newCustomer(); + Arrays.stream(role).forEach(customer::addRole); 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 index 670a53904ef7..966d0e3f0451 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java @@ -73,7 +73,7 @@ public Optional getRole(Role role, Class expectedRole @Override public String toString() { - String roles = Arrays.toString(this.roles.keySet().toArray()); + var 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 index 7f1805924fdc..b961c210ef84 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java @@ -26,5 +26,5 @@ /** * Key abstraction for segregated roles. */ -public abstract class CustomerRole extends CustomerCore{ +public abstract class CustomerRole extends CustomerCore { } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Role.java b/role-object/src/main/java/com/iluwatar/roleobject/Role.java index 74863ad84051..cbc6cc79b062 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/Role.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/Role.java @@ -24,7 +24,6 @@ package com.iluwatar.roleobject; import java.util.Optional; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,7 +47,7 @@ public enum Role { */ @SuppressWarnings("unchecked") public Optional instance() { - Class typeCst = this.typeCst; + var typeCst = this.typeCst; try { return (Optional) Optional.of(typeCst.newInstance()); } catch (InstantiationException | IllegalAccessException e) { diff --git a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java index 831781d7103b..eb8d57f4fa42 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java @@ -26,8 +26,8 @@ public class ApplicationRoleObjectTest { - @Test - public void mainTest() { - ApplicationRoleObject.main(new String[]{}); - } + @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 index 0c0f92fc2322..e04f91acc8f3 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java @@ -25,16 +25,12 @@ 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); - } + @Test + public void borrowTest() { + var borrowerRole = new BorrowerRole(); + borrowerRole.setName("test"); + Assert.assertEquals(borrowerRole.borrow(), "Borrower test wants to get some money."); + } } \ 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 index 1b2987400d05..50c96986af8f 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java @@ -22,82 +22,72 @@ */ package com.iluwatar.roleobject; -import org.junit.Test; - -import java.util.Optional; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import static org.junit.Assert.*; +import org.junit.Test; 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()); + @Test + public void addRole() { + var core = new CustomerCore(); + assertTrue(core.addRole(Role.Borrower)); + } - boolean res = core.remRole(Role.Borrower); - assertTrue(res); + @Test + public void hasRole() { + var core = new CustomerCore(); + core.addRole(Role.Borrower); + assertTrue(core.hasRole(Role.Borrower)); + assertFalse(core.hasRole(Role.Investor)); + } - Optional empt = core.getRole(Role.Borrower, BorrowerRole.class); - assertFalse(empt.isPresent()); + @Test + public void remRole() { + var core = new CustomerCore(); + core.addRole(Role.Borrower); - } + var bRole = core.getRole(Role.Borrower, BorrowerRole.class); + assertTrue(bRole.isPresent()); - @Test - public void getRole() { - CustomerCore core = new CustomerCore(); - core.addRole(Role.Borrower); + assertTrue(core.remRole(Role.Borrower)); - Optional bRole = core.getRole(Role.Borrower, BorrowerRole.class); - assertTrue(bRole.isPresent()); + var empt = core.getRole(Role.Borrower, BorrowerRole.class); + assertFalse(empt.isPresent()); + } - Optional nonRole = core.getRole(Role.Borrower, InvestorRole.class); - assertFalse(nonRole.isPresent()); + @Test + public void getRole() { + var core = new CustomerCore(); + core.addRole(Role.Borrower); - Optional invRole = core.getRole(Role.Investor, InvestorRole.class); - assertFalse(invRole.isPresent()); + var bRole = core.getRole(Role.Borrower, BorrowerRole.class); + assertTrue(bRole.isPresent()); + var nonRole = core.getRole(Role.Borrower, InvestorRole.class); + assertFalse(nonRole.isPresent()); - } + var 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]}"); + @Test + public void toStringTest() { + var 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(); + core.addRole(Role.Investor); + assertEquals(core.toString(), "Customer{roles=[Investor]}"); - core = new CustomerCore(); - assertEquals(core.toString(), "Customer{roles=[]}"); + 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 index 06afa1016275..7f8410ccabb9 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java @@ -27,12 +27,11 @@ 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); - } + @Test + public void investTest() { + var investorRole = new InvestorRole(); + investorRole.setName("test"); + investorRole.setAmountToInvest(10); + Assert.assertEquals(investorRole.invest(), "Investor test has invested 10 dollars"); + } } \ 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 index 6ae5b0cd8857..29161de3fa35 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java @@ -25,16 +25,12 @@ 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); - } + @Test + public void instanceTest() { + var instance = Role.Borrower.instance(); + Assert.assertTrue(instance.isPresent()); + Assert.assertEquals(instance.get().getClass(), BorrowerRole.class); + } } \ No newline at end of file diff --git a/saga/pom.xml b/saga/pom.xml index a22ec9797f61..08a5cdc77599 100644 --- a/saga/pom.xml +++ b/saga/pom.xml @@ -41,5 +41,34 @@ test - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + Choreography + + + + com.iluwatar.saga.choreography.SagaApplication + + + + + + Orchestration + + + + com.iluwatar.saga.orchestration.SagaApplication + + + + + + + + diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/ChoreographyChapter.java b/saga/src/main/java/com/iluwatar/saga/choreography/ChoreographyChapter.java index c79a77a9ac46..cfb22441d1b3 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/ChoreographyChapter.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/ChoreographyChapter.java @@ -25,9 +25,9 @@ /** - * ChoreographyChapter is an interface representing a contract for an external service. - * In that case, a service needs to make a decision what to do further - * hence the server needs to get all context representing {@link Saga} + * ChoreographyChapter is an interface representing a contract for an external service. In that + * case, a service needs to make a decision what to do further hence the server needs to get all + * context representing {@link Saga} */ public interface ChoreographyChapter { @@ -41,6 +41,7 @@ public interface ChoreographyChapter { /** * get name method. + * * @return service name. */ String getName(); diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java b/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java index b591adaf278a..818b59a1448c 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java @@ -28,9 +28,8 @@ import java.util.List; /** - * Saga representation. - * Saga consists of chapters. - * Every ChoreographyChapter is executed a certain service. + * Saga representation. Saga consists of chapters. Every ChoreographyChapter is executed a certain + * service. */ public class Saga { @@ -61,6 +60,7 @@ public SagaResult getResult() { /** * add chapter to saga. + * * @param name chapter name * @return this */ @@ -71,6 +71,7 @@ public Saga chapter(String name) { /** * set value to last chapter. + * * @param value invalue * @return this */ @@ -84,6 +85,7 @@ public Saga setInValue(Object value) { /** * get value from current chapter. + * * @return value */ public Object getCurrentValue() { @@ -92,6 +94,7 @@ public Object getCurrentValue() { /** * set value to current chapter. + * * @param value to set */ public void setCurrentValue(Object value) { @@ -100,6 +103,7 @@ public void setCurrentValue(Object value) { /** * set status for current chapter. + * * @param result to set */ public void setCurrentStatus(ChapterResult result) { @@ -145,8 +149,8 @@ boolean isCurrentSuccess() { } /** - * Class presents a chapter status and incoming - * parameters(incoming parameter transforms to outcoming parameter). + * Class presents a chapter status and incoming parameters(incoming parameter transforms to + * outcoming parameter). */ public static class Chapter { private String name; @@ -173,6 +177,7 @@ public String getName() { /** * set result. + * * @param result {@link ChapterResult} */ public void setResult(ChapterResult result) { @@ -181,6 +186,7 @@ public void setResult(ChapterResult result) { /** * the result for chapter is good. + * * @return true if is good otherwise bad */ public boolean isSuccess() { diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java b/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java index d8844c864ae4..858aa76d79a6 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java @@ -27,22 +27,19 @@ import org.slf4j.LoggerFactory; /** - * This pattern is used in distributed services to perform a group of operations atomically. - * This is an analog of transaction in a database but in terms - * of microservices architecture this is executed - * in a distributed environment + * This pattern is used in distributed services to perform a group of operations atomically. This is + * an analog of transaction in a database but in terms of microservices architecture this is + * executed in a distributed environment * *

A saga is a sequence of local transactions in a certain context. - * If one transaction fails for some reason, - * the saga executes compensating transactions(rollbacks) + * If one transaction fails for some reason, the saga executes compensating transactions(rollbacks) * to undo the impact of the preceding transactions. * *

In this approach, there are no mediators or orchestrators services. * All chapters are handled and moved by services manually. * *

The major difference with choreography saga is an ability to handle crashed services - * (otherwise in choreography services very hard to prevent a saga - * if one of them has been crashed) + * (otherwise in choreography services very hard to prevent a saga if one of them has been crashed) * * @see com.iluwatar.saga.choreography.Saga * @see Service @@ -54,10 +51,10 @@ public class SagaApplication { * main method. */ public static void main(String[] args) { - ServiceDiscoveryService sd = serviceDiscovery(); - ChoreographyChapter service = sd.findAny(); - Saga goodOrderSaga = service.execute(newSaga("good_order")); - Saga badOrderSaga = service.execute(newSaga("bad_order")); + var sd = serviceDiscovery(); + var service = sd.findAny(); + var goodOrderSaga = service.execute(newSaga("good_order")); + var badOrderSaga = service.execute(newSaga("bad_order")); LOGGER.info("orders: goodOrder is {}, badOrder is {}", goodOrderSaga.getResult(), badOrderSaga.getResult()); @@ -74,7 +71,7 @@ private static Saga newSaga(Object value) { } private static ServiceDiscoveryService serviceDiscovery() { - ServiceDiscoveryService sd = new ServiceDiscoveryService(); + var sd = new ServiceDiscoveryService(); return sd .discover(new OrderService(sd)) .discover(new FlyBookingService(sd)) diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/Service.java b/saga/src/main/java/com/iluwatar/saga/choreography/Service.java index 2e932b5288c0..da447c528a31 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/Service.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/Service.java @@ -29,8 +29,8 @@ /** - * Common abstraction class representing services. - * implementing a general contract @see {@link ChoreographyChapter} + * Common abstraction class representing services. implementing a general contract @see {@link + * ChoreographyChapter} */ public abstract class Service implements ChoreographyChapter { protected static final Logger LOGGER = LoggerFactory.getLogger(Service.class); @@ -43,9 +43,9 @@ public Service(ServiceDiscoveryService service) { @Override public Saga execute(Saga saga) { - Saga nextSaga = saga; + var nextSaga = saga; Object nextVal; - String chapterName = saga.getCurrent().getName(); + var chapterName = saga.getCurrent().getName(); if (chapterName.equals(getName())) { if (saga.isForward()) { nextSaga = process(saga); @@ -67,7 +67,7 @@ public Saga execute(Saga saga) { nextSaga.setCurrentValue(nextVal); } - Saga finalNextSaga = nextSaga; + var finalNextSaga = nextSaga; return sd.find(chapterName).map(ch -> ch.execute(finalNextSaga)) .orElseThrow(serviceNotFoundException(chapterName)); @@ -80,7 +80,7 @@ private Supplier serviceNotFoundException(String chServiceName @Override public Saga process(Saga saga) { - Object inValue = saga.getCurrentValue(); + var inValue = saga.getCurrentValue(); LOGGER.info("The chapter '{}' has been started. " + "The data {} has been stored or calculated successfully", getName(), inValue); @@ -91,7 +91,7 @@ public Saga process(Saga saga) { @Override public Saga rollback(Saga saga) { - Object inValue = saga.getCurrentValue(); + var inValue = saga.getCurrentValue(); LOGGER.info("The Rollback for a chapter '{}' has been started. " + "The data {} has been rollbacked successfully", getName(), inValue); diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java b/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java index 637e8ac1bbf4..d0fd02390d60 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java @@ -39,7 +39,7 @@ public String getName() { @Override public Saga process(Saga saga) { - Object inValue = saga.getCurrentValue(); + var inValue = saga.getCurrentValue(); if (inValue.equals("bad_order")) { LOGGER.info("The chapter '{}' has been started. But the exception has been raised." diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/OrchestrationChapter.java b/saga/src/main/java/com/iluwatar/saga/orchestration/OrchestrationChapter.java index 7e9e3581f54d..667dea904964 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/OrchestrationChapter.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/OrchestrationChapter.java @@ -32,6 +32,7 @@ public interface OrchestrationChapter { /** * method get name. + * * @return service name. */ String getName(); diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java b/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java index 0d53362aa8e2..aff3593f17e4 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java @@ -27,9 +27,8 @@ import java.util.List; /** - * Saga representation. - * Saga consists of chapters. - * Every ChoreographyChapter is executed by a certain service. + * Saga representation. Saga consists of chapters. Every ChoreographyChapter is executed by a + * certain service. */ public class Saga { diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java b/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java index 830f5e653cce..201a526f9f55 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java @@ -27,23 +27,19 @@ import org.slf4j.LoggerFactory; /** - * This pattern is used in distributed services to perform - * a group of operations atomically. - * This is an analog of transaction in a database but in terms - * of microservices architecture this is executed - * in a distributed environment + * This pattern is used in distributed services to perform a group of operations atomically. This is + * an analog of transaction in a database but in terms of microservices architecture this is + * executed in a distributed environment * *

A saga is a sequence of local transactions in a certain context. - * If one transaction fails for some reason, - * the saga executes compensating transactions(rollbacks) + * If one transaction fails for some reason, the saga executes compensating transactions(rollbacks) * to undo the impact of the preceding transactions. * *

In this approach, there is an orchestrator @see {@link SagaOrchestrator} - * that manages all the transactions and directs - * the participant services to execute local transactions based on events. - * The major difference with choreography saga is an ability to handle crashed services - * (otherwise in choreography services very hard to prevent a saga - * if one of them has been crashed) + * that manages all the transactions and directs the participant services to execute local + * transactions based on events. The major difference with choreography saga is an ability to handle + * crashed services (otherwise in choreography services very hard to prevent a saga if one of them + * has been crashed) * * @see Saga * @see SagaOrchestrator @@ -56,7 +52,7 @@ public class SagaApplication { * method to show common saga logic. */ public static void main(String[] args) { - SagaOrchestrator sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); + var sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); Saga.Result goodOrder = sagaOrchestrator.execute("good_order"); Saga.Result badOrder = sagaOrchestrator.execute("bad_order"); @@ -77,11 +73,10 @@ private static Saga newSaga() { } private static ServiceDiscoveryService serviceDiscovery() { - return - new ServiceDiscoveryService() - .discover(new OrderService()) - .discover(new FlyBookingService()) - .discover(new HotelBookingService()) - .discover(new WithdrawMoneyService()); + return new ServiceDiscoveryService() + .discover(new OrderService()) + .discover(new FlyBookingService()) + .discover(new HotelBookingService()) + .discover(new WithdrawMoneyService()); } } diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java b/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java index beec37655534..d4df6fa07c7a 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java @@ -23,18 +23,18 @@ package com.iluwatar.saga.orchestration; +import static com.iluwatar.saga.orchestration.Saga.Result; import static com.iluwatar.saga.orchestration.Saga.Result.CRASHED; import static com.iluwatar.saga.orchestration.Saga.Result.FINISHED; import static com.iluwatar.saga.orchestration.Saga.Result.ROLLBACK; -import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * The orchestrator that manages all the transactions and directs - * the participant services to execute local transactions based on events. + * The orchestrator that manages all the transactions and directs the participant services to + * execute local transactions based on events. */ public class SagaOrchestrator { private static final Logger LOGGER = LoggerFactory.getLogger(SagaOrchestrator.class); @@ -45,8 +45,9 @@ public class SagaOrchestrator { /** * Create a new service to orchetrate sagas. + * * @param saga saga to process - * @param sd service discovery @see {@link ServiceDiscoveryService} + * @param sd service discovery @see {@link ServiceDiscoveryService} */ public SagaOrchestrator(Saga saga, ServiceDiscoveryService sd) { this.saga = saga; @@ -59,30 +60,30 @@ public SagaOrchestrator(Saga saga, ServiceDiscoveryService sd) { * * @param value incoming value * @param type for incoming value - * @return result @see {@link Saga.Result} + * @return result @see {@link Result} */ @SuppressWarnings("unchecked") - public Saga.Result execute(K value) { + public Result execute(K value) { state.cleanUp(); LOGGER.info(" The new saga is about to start"); - Saga.Result result = FINISHED; + var result = FINISHED; K tempVal = value; while (true) { - int next = state.current(); - Saga.Chapter ch = saga.get(next); - Optional srvOpt = sd.find(ch.name); + var next = state.current(); + var ch = saga.get(next); + var srvOpt = sd.find(ch.name); - if (!srvOpt.isPresent()) { + if (srvOpt.isEmpty()) { state.directionToBack(); state.back(); continue; } - OrchestrationChapter srv = srvOpt.get(); + var srv = srvOpt.get(); if (state.isForward()) { - ChapterResult processRes = srv.process(tempVal); + var processRes = srv.process(tempVal); if (processRes.isSuccess()) { next = state.forward(); tempVal = (K) processRes.getValue(); @@ -90,7 +91,7 @@ public Saga.Result execute(K value) { state.directionToBack(); } } else { - ChapterResult rlRes = srv.rollback(tempVal); + var rlRes = srv.rollback(tempVal); if (rlRes.isSuccess()) { next = state.back(); tempVal = (K) rlRes.getValue(); diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java b/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java index d2b0652015c1..eb2fc04823bc 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java @@ -27,8 +27,8 @@ import org.slf4j.LoggerFactory; /** - * Common abstraction class representing services. - * implementing a general contract @see {@link OrchestrationChapter} + * Common abstraction class representing services. implementing a general contract @see {@link + * OrchestrationChapter} * * @param type of incoming param */ diff --git a/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java b/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java index 4300d4057780..5ae9df19ddd5 100644 --- a/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java +++ b/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java @@ -33,10 +33,10 @@ public class SagaChoreographyTest { @Test public void executeTest() { - ServiceDiscoveryService sd = serviceDiscovery(); - ChoreographyChapter service = sd.findAny(); - Saga badOrderSaga = service.execute(newSaga("bad_order")); - Saga goodOrderSaga = service.execute(newSaga("good_order")); + var sd = serviceDiscovery(); + var service = sd.findAny(); + var badOrderSaga = service.execute(newSaga("bad_order")); + var goodOrderSaga = service.execute(newSaga("good_order")); Assert.assertEquals(badOrderSaga.getResult(), Saga.SagaResult.ROLLBACKED); Assert.assertEquals(goodOrderSaga.getResult(), Saga.SagaResult.FINISHED); @@ -52,7 +52,7 @@ private static Saga newSaga(Object value) { } private static ServiceDiscoveryService serviceDiscovery() { - ServiceDiscoveryService sd = new ServiceDiscoveryService(); + var sd = new ServiceDiscoveryService(); return sd .discover(new OrderService(sd)) .discover(new FlyBookingService(sd)) diff --git a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java index aa3c8773f46a..aa4f4ff7dcae 100644 --- a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java +++ b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java @@ -24,8 +24,6 @@ import org.junit.Test; -import static org.junit.Assert.*; - /** * empty test */ diff --git a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java index a93bf5280cb6..423b8e12ee0f 100644 --- a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java +++ b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java @@ -22,11 +22,12 @@ */ package com.iluwatar.saga.orchestration; -import org.junit.Assert; -import org.junit.Test; +import static com.iluwatar.saga.orchestration.Saga.Result; import java.util.ArrayList; import java.util.List; +import org.junit.Assert; +import org.junit.Test; /** * test to test orchestration logic @@ -37,17 +38,16 @@ public class SagaOrchestratorInternallyTest { @Test public void executeTest() { - SagaOrchestrator sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); - Saga.Result result = sagaOrchestrator.execute(1); - Assert.assertEquals(result, Saga.Result.ROLLBACK); + var sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); + var result = sagaOrchestrator.execute(1); + Assert.assertEquals(result, Result.ROLLBACK); Assert.assertArrayEquals( records.toArray(new String[]{}), new String[]{"+1", "+2", "+3", "+4", "-4", "-3", "-2", "-1"}); } private static Saga newSaga() { - return Saga - .create() + return Saga.create() .chapter("1") .chapter("2") .chapter("3") @@ -55,12 +55,11 @@ private static Saga newSaga() { } private ServiceDiscoveryService serviceDiscovery() { - return - new ServiceDiscoveryService() - .discover(new Service1()) - .discover(new Service2()) - .discover(new Service3()) - .discover(new Service4()); + return new ServiceDiscoveryService() + .discover(new Service1()) + .discover(new Service2()) + .discover(new Service3()) + .discover(new Service4()); } class Service1 extends Service { diff --git a/semaphore/pom.xml b/semaphore/pom.xml index 2684289981fa..b6375366b153 100644 --- a/semaphore/pom.xml +++ b/semaphore/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.semaphore.App + + + + + + + + diff --git a/semaphore/src/main/java/com/iluwatar/semaphore/App.java b/semaphore/src/main/java/com/iluwatar/semaphore/App.java index ccf3dc4ab122..ebb35037f49f 100644 --- a/semaphore/src/main/java/com/iluwatar/semaphore/App.java +++ b/semaphore/src/main/java/com/iluwatar/semaphore/App.java @@ -38,7 +38,7 @@ public class App { * main method. */ public static void main(String[] args) { - FruitShop shop = new FruitShop(); + var shop = new FruitShop(); new Customer("Peter", shop).start(); new Customer("Paul", shop).start(); new Customer("Mary", shop).start(); diff --git a/semaphore/src/main/java/com/iluwatar/semaphore/Customer.java b/semaphore/src/main/java/com/iluwatar/semaphore/Customer.java index 97c9cf0e05bd..47f503a06982 100644 --- a/semaphore/src/main/java/com/iluwatar/semaphore/Customer.java +++ b/semaphore/src/main/java/com/iluwatar/semaphore/Customer.java @@ -64,13 +64,14 @@ public Customer(String name, FruitShop fruitShop) { public void run() { while (fruitShop.countFruit() > 0) { - FruitBowl bowl = fruitShop.takeBowl(); - Fruit fruit; - - if (bowl != null && (fruit = bowl.take()) != null) { - LOGGER.info("{} took an {}", name, fruit); - fruitBowl.put(fruit); - fruitShop.returnBowl(bowl); + var bowl = fruitShop.takeBowl(); + if (bowl != null) { + var fruit = bowl.take(); + if (fruit != null) { + LOGGER.info("{} took an {}", name, fruit); + fruitBowl.put(fruit); + fruitShop.returnBowl(bowl); + } } } diff --git a/semaphore/src/main/java/com/iluwatar/semaphore/FruitBowl.java b/semaphore/src/main/java/com/iluwatar/semaphore/FruitBowl.java index 9089f9c73991..6b43c8100012 100644 --- a/semaphore/src/main/java/com/iluwatar/semaphore/FruitBowl.java +++ b/semaphore/src/main/java/com/iluwatar/semaphore/FruitBowl.java @@ -68,11 +68,11 @@ public Fruit take() { * toString method. */ public String toString() { - int apples = 0; - int oranges = 0; - int lemons = 0; + var apples = 0; + var oranges = 0; + var lemons = 0; - for (Fruit f : fruit) { + for (var f : fruit) { switch (f.getType()) { case APPLE: apples++; diff --git a/semaphore/src/main/java/com/iluwatar/semaphore/FruitShop.java b/semaphore/src/main/java/com/iluwatar/semaphore/FruitShop.java index ba826fb0970d..a360f955c0fd 100644 --- a/semaphore/src/main/java/com/iluwatar/semaphore/FruitShop.java +++ b/semaphore/src/main/java/com/iluwatar/semaphore/FruitShop.java @@ -55,7 +55,7 @@ public class FruitShop { * FruitShop constructor. */ public FruitShop() { - for (int i = 0; i < 100; i++) { + for (var i = 0; i < 100; i++) { bowls[0].put(new Fruit(Fruit.FruitType.APPLE)); bowls[1].put(new Fruit(Fruit.FruitType.ORANGE)); bowls[2].put(new Fruit(Fruit.FruitType.LEMON)); diff --git a/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java b/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java index 087ab78758b2..f450c0593035 100644 --- a/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java +++ b/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java @@ -25,15 +25,12 @@ import org.junit.jupiter.api.Test; -import java.io.IOException; - /** * Application Test Entrypoint */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java b/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java index 5cab7d64d9a1..bc21f91960dc 100644 --- a/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java +++ b/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java @@ -23,12 +23,12 @@ package com.iluwatar.semaphore; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import org.junit.jupiter.api.Test; + /** * Test taking from and putting Fruit into a FruitBowl */ @@ -36,16 +36,16 @@ public class FruitBowlTest { @Test public void fruitBowlTest() { - FruitBowl fbowl = new FruitBowl(); - + var fbowl = new FruitBowl(); + assertEquals(0, fbowl.countFruit()); - - for (int i = 1; i <= 10; i++) { + + for (var i = 1; i <= 10; i++) { fbowl.put(new Fruit(Fruit.FruitType.LEMON)); assertEquals(i, fbowl.countFruit()); } - for (int i = 9; i >= 0; i--) { + for (var i = 9; i >= 0; i--) { assertNotNull(fbowl.take()); assertEquals(i, fbowl.countFruit()); } diff --git a/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java b/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java index 76f68af1537e..6d64066fb5f7 100644 --- a/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java +++ b/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java @@ -23,11 +23,11 @@ package com.iluwatar.semaphore; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; + /** * Test case for acquiring and releasing a Semaphore */ @@ -35,11 +35,11 @@ public class SemaphoreTest { @Test public void acquireReleaseTest() { - Semaphore sphore = new Semaphore(3); + var sphore = new Semaphore(3); assertEquals(3, sphore.getAvailableLicenses()); - for (int i = 2; i >= 0; i--) { + for (var i = 2; i >= 0; i--) { try { sphore.acquire(); assertEquals(i, sphore.getAvailableLicenses()); @@ -47,8 +47,8 @@ public void acquireReleaseTest() { fail(e.toString()); } } - - for (int i = 1; i <= 3; i++) { + + for (var i = 1; i <= 3; i++) { sphore.release(); assertEquals(i, sphore.getAvailableLicenses()); } diff --git a/servant/pom.xml b/servant/pom.xml index db5abe580025..395060d502fb 100644 --- a/servant/pom.xml +++ b/servant/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.servant.App + + + + + + + + diff --git a/servant/src/main/java/com/iluwatar/servant/App.java b/servant/src/main/java/com/iluwatar/servant/App.java index fcebec5bf532..b68cb9aee38d 100644 --- a/servant/src/main/java/com/iluwatar/servant/App.java +++ b/servant/src/main/java/com/iluwatar/servant/App.java @@ -54,10 +54,10 @@ public static void main(String[] args) { * Can add a List with enum Actions for variable scenarios. */ public static void scenario(Servant servant, int compliment) { - King k = new King(); - Queen q = new Queen(); + var k = new King(); + var q = new Queen(); - List guests = List.of(k, q); + var guests = List.of(k, q); // feed servant.feed(k); @@ -69,9 +69,7 @@ public static void scenario(Servant servant, int compliment) { servant.giveCompliments(guests.get(compliment)); // outcome of the night - for (Royalty r : guests) { - r.changeMood(); - } + guests.forEach(Royalty::changeMood); // check your luck if (servant.checkIfYouWillBeHanged(guests)) { diff --git a/servant/src/main/java/com/iluwatar/servant/Servant.java b/servant/src/main/java/com/iluwatar/servant/Servant.java index 856f7806be63..57b6bc541ffa 100644 --- a/servant/src/main/java/com/iluwatar/servant/Servant.java +++ b/servant/src/main/java/com/iluwatar/servant/Servant.java @@ -55,13 +55,6 @@ public void giveCompliments(Royalty r) { * Check if we will be hanged. */ public boolean checkIfYouWillBeHanged(List tableGuests) { - boolean anotherDay = true; - for (Royalty r : tableGuests) { - if (!r.getMood()) { - anotherDay = false; - } - } - - return anotherDay; + return tableGuests.stream().allMatch(Royalty::getMood); } } diff --git a/servant/src/test/java/com/iluwatar/servant/AppTest.java b/servant/src/test/java/com/iluwatar/servant/AppTest.java index ef37ff010477..ab1e99e5560b 100644 --- a/servant/src/test/java/com/iluwatar/servant/AppTest.java +++ b/servant/src/test/java/com/iluwatar/servant/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/servant/src/test/java/com/iluwatar/servant/KingTest.java b/servant/src/test/java/com/iluwatar/servant/KingTest.java index ed97ae7cfa00..6c4c76ccdaf3 100644 --- a/servant/src/test/java/com/iluwatar/servant/KingTest.java +++ b/servant/src/test/java/com/iluwatar/servant/KingTest.java @@ -23,11 +23,11 @@ package com.iluwatar.servant; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * Date: 12/28/15 - 9:40 PM * @@ -37,14 +37,14 @@ public class KingTest { @Test public void testHungrySoberUncomplimentedKing() { - final King king = new King(); + final var king = new King(); king.changeMood(); assertFalse(king.getMood()); } @Test public void testFedSoberUncomplimentedKing() { - final King king = new King(); + final var king = new King(); king.getFed(); king.changeMood(); assertFalse(king.getMood()); @@ -52,7 +52,7 @@ public void testFedSoberUncomplimentedKing() { @Test public void testHungryDrunkUncomplimentedKing() { - final King king = new King(); + final var king = new King(); king.getDrink(); king.changeMood(); assertFalse(king.getMood()); @@ -60,7 +60,7 @@ public void testHungryDrunkUncomplimentedKing() { @Test public void testHungrySoberComplimentedKing() { - final King king = new King(); + final var king = new King(); king.receiveCompliments(); king.changeMood(); assertFalse(king.getMood()); @@ -68,7 +68,7 @@ public void testHungrySoberComplimentedKing() { @Test public void testFedDrunkUncomplimentedKing() { - final King king = new King(); + final var king = new King(); king.getFed(); king.getDrink(); king.changeMood(); @@ -77,7 +77,7 @@ public void testFedDrunkUncomplimentedKing() { @Test public void testFedSoberComplimentedKing() { - final King king = new King(); + final var king = new King(); king.getFed(); king.receiveCompliments(); king.changeMood(); @@ -86,7 +86,7 @@ public void testFedSoberComplimentedKing() { @Test public void testFedDrunkComplimentedKing() { - final King king = new King(); + final var king = new King(); king.getFed(); king.getDrink(); king.receiveCompliments(); diff --git a/servant/src/test/java/com/iluwatar/servant/QueenTest.java b/servant/src/test/java/com/iluwatar/servant/QueenTest.java index a82eec7767f4..7af35185594b 100644 --- a/servant/src/test/java/com/iluwatar/servant/QueenTest.java +++ b/servant/src/test/java/com/iluwatar/servant/QueenTest.java @@ -24,11 +24,11 @@ package com.iluwatar.servant; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * Date: 12/28/15 - 9:52 PM * @@ -38,34 +38,34 @@ public class QueenTest { @Test public void testNotFlirtyUncomplemented() { - final Queen queen = new Queen(); + final var queen = new Queen(); queen.setFlirtiness(false); queen.changeMood(); assertFalse(queen.getMood()); } - + @Test public void testNotFlirtyComplemented() { - final Queen queen = new Queen(); + final var queen = new Queen(); queen.setFlirtiness(false); queen.receiveCompliments(); queen.changeMood(); assertFalse(queen.getMood()); } - + @Test public void testFlirtyUncomplemented() { - final Queen queen = new Queen(); + final var queen = new Queen(); queen.changeMood(); assertFalse(queen.getMood()); } - + @Test public void testFlirtyComplemented() { - final Queen queen = new Queen(); + final var queen = new Queen(); queen.receiveCompliments(); queen.changeMood(); assertTrue(queen.getMood()); } - + } \ No newline at end of file diff --git a/servant/src/test/java/com/iluwatar/servant/ServantTest.java b/servant/src/test/java/com/iluwatar/servant/ServantTest.java index 02b69559e624..5d8d5d9977b5 100644 --- a/servant/src/test/java/com/iluwatar/servant/ServantTest.java +++ b/servant/src/test/java/com/iluwatar/servant/ServantTest.java @@ -23,16 +23,15 @@ package com.iluwatar.servant; -import org.junit.jupiter.api.Test; - -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import java.util.List; +import org.junit.jupiter.api.Test; + /** * Date: 12/28/15 - 10:02 PM * @@ -42,8 +41,8 @@ public class ServantTest { @Test public void testFeed() { - final Royalty royalty = mock(Royalty.class); - final Servant servant = new Servant("test"); + final var royalty = mock(Royalty.class); + final var servant = new Servant("test"); servant.feed(royalty); verify(royalty).getFed(); verifyNoMoreInteractions(royalty); @@ -51,8 +50,8 @@ public void testFeed() { @Test public void testGiveWine() { - final Royalty royalty = mock(Royalty.class); - final Servant servant = new Servant("test"); + final var royalty = mock(Royalty.class); + final var servant = new Servant("test"); servant.giveWine(royalty); verify(royalty).getDrink(); verifyNoMoreInteractions(royalty); @@ -60,8 +59,8 @@ public void testGiveWine() { @Test public void testGiveCompliments() { - final Royalty royalty = mock(Royalty.class); - final Servant servant = new Servant("test"); + final var royalty = mock(Royalty.class); + final var servant = new Servant("test"); servant.giveCompliments(royalty); verify(royalty).receiveCompliments(); verifyNoMoreInteractions(royalty); @@ -69,15 +68,15 @@ public void testGiveCompliments() { @Test public void testCheckIfYouWillBeHanged() { - final Royalty goodMoodRoyalty = mock(Royalty.class); + final var goodMoodRoyalty = mock(Royalty.class); when(goodMoodRoyalty.getMood()).thenReturn(true); - final Royalty badMoodRoyalty = mock(Royalty.class); + final var badMoodRoyalty = mock(Royalty.class); when(badMoodRoyalty.getMood()).thenReturn(true); - final List goodCompany = List.of(goodMoodRoyalty, goodMoodRoyalty, goodMoodRoyalty); + final var goodCompany = List.of(goodMoodRoyalty, goodMoodRoyalty, goodMoodRoyalty); - final List badCompany = List.of(goodMoodRoyalty, goodMoodRoyalty, badMoodRoyalty); + final var badCompany = List.of(goodMoodRoyalty, goodMoodRoyalty, badMoodRoyalty); assertTrue(new Servant("test").checkIfYouWillBeHanged(goodCompany)); assertTrue(new Servant("test").checkIfYouWillBeHanged(badCompany)); 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 43465f529dd9..a13893f70cb1 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 @@ -24,14 +24,12 @@ package com.iluwatar.serverless.baas.api; import com.amazonaws.regions.Regions; -import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.Serializable; -import java.util.HashMap; import java.util.Map; /** @@ -50,7 +48,7 @@ public AbstractDynamoDbHandler() { } private void initAmazonDynamoDb() { - AmazonDynamoDB amazonDynamoDb = AmazonDynamoDBClientBuilder + var amazonDynamoDb = AmazonDynamoDBClientBuilder .standard() .withRegion(Regions.US_EAST_1) .build(); @@ -71,10 +69,7 @@ public void setDynamoDbMapper(DynamoDBMapper dynamoDbMapper) { } protected Map headers() { - Map headers = new HashMap<>(); - headers.put("Content-Type", "application/json"); - - return headers; + return Map.of("Content-Type", "application/json"); } /** @@ -85,14 +80,11 @@ protected Map headers() { * @return - api gateway proxy response */ protected APIGatewayProxyResponseEvent apiGatewayProxyResponseEvent(Integer statusCode, T body) { - APIGatewayProxyResponseEvent apiGatewayProxyResponseEvent = - new APIGatewayProxyResponseEvent().withHeaders(headers()); + var apiGatewayProxyResponseEvent = new APIGatewayProxyResponseEvent().withHeaders(headers()); try { apiGatewayProxyResponseEvent .withStatusCode(statusCode) - .withBody(getObjectMapper() - .writeValueAsString(body)); - + .withBody(getObjectMapper().writeValueAsString(body)); } catch (JsonProcessingException jsonProcessingException) { throw new RuntimeException(jsonProcessingException); } 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 11066c744521..7190b04fe85a 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 @@ -28,7 +28,6 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.iluwatar.serverless.baas.model.Person; -import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,15 +41,15 @@ public class FindPersonApiHandler extends AbstractDynamoDbHandler private static final Integer SUCCESS_STATUS_CODE = 200; @Override - public APIGatewayProxyResponseEvent handleRequest( - APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent, Context context) { - 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")); - + public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent req, Context ctx) { + req.getPathParameters().forEach(FindPersonApiHandler::logKeyValue); + var id = req.getPathParameters().get("id"); + var person = this.getDynamoDbMapper().load(Person.class, id); return apiGatewayProxyResponseEvent(SUCCESS_STATUS_CODE, person); } + + private static void logKeyValue(String key, String value) { + LOG.info(key + "=" + value); + } + } 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 0bc121853373..51c2df79143a 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 @@ -43,19 +43,15 @@ public class SavePersonApiHandler extends AbstractDynamoDbHandler private static final Integer BAD_REQUEST_STATUS_CODE = 400; @Override - public APIGatewayProxyResponseEvent handleRequest( - APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent, Context context) { - APIGatewayProxyResponseEvent apiGatewayProxyResponseEvent; - Person person; + public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent req, Context ctx) { try { - person = getObjectMapper().readValue(apiGatewayProxyRequestEvent.getBody(), Person.class); + var objectMapper = getObjectMapper(); + var person = objectMapper.readValue(req.getBody(), Person.class); getDynamoDbMapper().save(person); - apiGatewayProxyResponseEvent = apiGatewayProxyResponseEvent(CREATED_STATUS_CODE, person); + return apiGatewayProxyResponseEvent(CREATED_STATUS_CODE, person); } catch (IOException ioException) { LOG.error("unable to parse body", ioException); - apiGatewayProxyResponseEvent = apiGatewayProxyResponseEvent(BAD_REQUEST_STATUS_CODE, null); + return apiGatewayProxyResponseEvent(BAD_REQUEST_STATUS_CODE, null); } - - return apiGatewayProxyResponseEvent; } } 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 710cde531d76..512f436fbc54 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 @@ -26,6 +26,7 @@ import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBDocument; import java.io.Serializable; +import java.util.Objects; /** * Address class Created by dheeraj.mummarareddy on 3/4/18. @@ -96,30 +97,30 @@ public boolean equals(Object o) { return false; } - Address address = (Address) o; + var address = (Address) o; - if (addressLineOne != null ? !addressLineOne.equals(address.addressLineOne) : - address.addressLineOne != null) { + if (!Objects.equals(addressLineOne, address.addressLineOne)) { return false; } - if (addressLineTwo != null ? !addressLineTwo.equals(address.addressLineTwo) : - address.addressLineTwo != null) { + if (!Objects.equals(addressLineTwo, address.addressLineTwo)) { return false; } - if (city != null ? !city.equals(address.city) : address.city != null) { + if (!Objects.equals(city, address.city)) { return false; } - if (state != null ? !state.equals(address.state) : address.state != null) { + + if (!Objects.equals(state, address.state)) { return false; } - return zipCode != null ? zipCode.equals(address.zipCode) : address.zipCode == null; + + return Objects.equals(zipCode, address.zipCode); } @Override public int hashCode() { - int result = addressLineOne != null ? addressLineOne.hashCode() : 0; + var result = addressLineOne != null ? addressLineOne.hashCode() : 0; result = 31 * result + (addressLineTwo != null ? addressLineTwo.hashCode() : 0); result = 31 * result + (city != null ? city.hashCode() : 0); result = 31 * result + (state != null ? state.hashCode() : 0); 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 3c97aae11429..0fd9f158899d 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 @@ -29,6 +29,7 @@ import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; +import java.util.Objects; /** * Person class Created by dheeraj.mummarareddy on 3/4/18. @@ -92,15 +93,15 @@ public boolean equals(Object o) { Person person = (Person) o; - if (firstName != null ? !firstName.equals(person.firstName) : person.firstName != null) { + if (!Objects.equals(firstName, person.firstName)) { return false; } - if (lastName != null ? !lastName.equals(person.lastName) : person.lastName != null) { + if (!Objects.equals(lastName, person.lastName)) { return false; } - return address != null ? address.equals(person.address) : person.address == null; + return Objects.equals(address, person.address); } @Override 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 94fe7b4f9a51..6f57d2e27980 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/faas/ApiGatewayResponse.java +++ b/serverless/src/main/java/com/iluwatar/serverless/faas/ApiGatewayResponse.java @@ -30,10 +30,8 @@ /** * Api gateway response. - * - * @param serializable object */ -public class ApiGatewayResponse implements Serializable { +public class ApiGatewayResponse implements Serializable { private static final long serialVersionUID = 1181159426782844892L; @@ -50,8 +48,12 @@ public class ApiGatewayResponse implements Serializable * @param headers - response headers * @param isBase64Encoded - base64Encoded flag */ - public ApiGatewayResponse(Integer statusCode, String body, Map headers, - Boolean isBase64Encoded) { + public ApiGatewayResponse( + Integer statusCode, + String body, + Map headers, + Boolean isBase64Encoded + ) { this.statusCode = statusCode; this.body = body; this.headers = headers; 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 7cb93ebf4a6b..aa2a86667bb6 100644 --- a/serverless/src/main/java/com/iluwatar/serverless/faas/LambdaInfo.java +++ b/serverless/src/main/java/com/iluwatar/serverless/faas/LambdaInfo.java @@ -24,6 +24,7 @@ package com.iluwatar.serverless.faas; import java.io.Serializable; +import java.util.Objects; /** * Lambda context information. @@ -110,28 +111,22 @@ public boolean equals(Object o) { LambdaInfo that = (LambdaInfo) o; - if (awsRequestId != null ? !awsRequestId - .equals(that.awsRequestId) : that.awsRequestId != null) { + if (!Objects.equals(awsRequestId, that.awsRequestId)) { return false; } - if (logGroupName != null ? !logGroupName - .equals(that.logGroupName) : that.logGroupName != null) { + if (!Objects.equals(logGroupName, that.logGroupName)) { return false; } - if (logStreamName != null ? !logStreamName - .equals(that.logStreamName) : that.logStreamName != null) { + if (!Objects.equals(logStreamName, that.logStreamName)) { return false; } - if (functionName != null ? !functionName - .equals(that.functionName) : that.functionName != null) { + if (!Objects.equals(functionName, that.functionName)) { return false; } - if (functionVersion != null ? !functionVersion - .equals(that.functionVersion) : that.functionVersion != null) { + if (!Objects.equals(functionVersion, that.functionVersion)) { return false; } - return memoryLimitInMb != null ? memoryLimitInMb - .equals(that.memoryLimitInMb) : that.memoryLimitInMb == null; + return Objects.equals(memoryLimitInMb, that.memoryLimitInMb); } @Override 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 a16358a54328..7fdb8ad38f2a 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 @@ -27,7 +27,6 @@ import com.amazonaws.services.lambda.runtime.RequestHandler; import com.iluwatar.serverless.faas.ApiGatewayResponse; import com.iluwatar.serverless.faas.LambdaInfo; -import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,13 +45,11 @@ public class LambdaInfoApiHandler public ApiGatewayResponse handleRequest(Map input, Context context) { LOG.info("received: " + input); - return new ApiGatewayResponse - .ApiGatewayResponseBuilder() + return new ApiGatewayResponse.ApiGatewayResponseBuilder() .headers(headers()) .statusCode(SUCCESS_STATUS_CODE) .body(lambdaInfo(context)) .build(); - } /** @@ -69,14 +66,10 @@ private LambdaInfo lambdaInfo(Context context) { lambdaInfo.setLogGroupName(context.getLogGroupName()); lambdaInfo.setLogStreamName(context.getLogStreamName()); lambdaInfo.setMemoryLimitInMb(context.getMemoryLimitInMB()); - return lambdaInfo; } private Map headers() { - var headers = new HashMap(); - headers.put("Content-Type", "application/json"); - - return headers; + return Map.of("Content-Type", "application/json"); } } 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 a688bdf9d0ac..19d0cab23403 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 @@ -23,27 +23,23 @@ package com.iluwatar.serverless.baas.api; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; -import com.iluwatar.serverless.baas.api.FindPersonApiHandler; -import com.iluwatar.serverless.baas.api.SavePersonApiHandler; import com.iluwatar.serverless.baas.model.Person; +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import java.util.Collections; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - /** - * Unit tests for FindPersonApiHandler - * Created by dheeraj.mummar on 3/5/18. + * Unit tests for FindPersonApiHandler Created by dheeraj.mummar on 3/5/18. */ @RunWith(MockitoJUnitRunner.class) public class FindPersonApiHandlerTest { @@ -66,8 +62,7 @@ public void handleRequest() { } private APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent() { - return new APIGatewayProxyRequestEvent() - .withPathParamters(Collections - .singletonMap("id", "37e7a1fe-3544-473d-b764-18128f02d72d")); + var request = new APIGatewayProxyRequestEvent(); + return request.withPathParamters(Map.of("id", "37e7a1fe-3544-473d-b764-18128f02d72d")); } } 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 66636c011458..ef3909adc8a1 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 @@ -23,13 +23,15 @@ package com.iluwatar.serverless.baas.api; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.iluwatar.serverless.baas.api.SavePersonApiHandler; import com.iluwatar.serverless.baas.model.Address; import com.iluwatar.serverless.baas.model.Person; import org.junit.Assert; @@ -39,11 +41,8 @@ import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import static org.mockito.Mockito.*; - /** - * Unit tests for SavePersonApiHandler - * Created by dheeraj.mummar on 3/4/18. + * Unit tests for SavePersonApiHandler Created by dheeraj.mummar on 3/4/18. */ @RunWith(MockitoJUnitRunner.class) public class SavePersonApiHandlerTest { @@ -63,40 +62,40 @@ public void setUp() { @Test public void handleRequestSavePersonSuccessful() throws JsonProcessingException { - Person person = newPerson(); - APIGatewayProxyResponseEvent apiGatewayProxyResponseEvent = - this.savePersonApiHandler - .handleRequest(apiGatewayProxyRequestEvent(objectMapper.writeValueAsString(person)), mock(Context.class)); + var person = newPerson(); + var body = objectMapper.writeValueAsString(person); + var request = apiGatewayProxyRequestEvent(body); + var ctx = mock(Context.class); + var apiGatewayProxyResponseEvent = this.savePersonApiHandler.handleRequest(request, ctx); verify(dynamoDbMapper, times(1)).save(person); Assert.assertNotNull(apiGatewayProxyResponseEvent); - Assert.assertEquals(new Integer(201), apiGatewayProxyResponseEvent.getStatusCode()); + Assert.assertEquals(Integer.valueOf(201), apiGatewayProxyResponseEvent.getStatusCode()); } @Test public void handleRequestSavePersonException() { - APIGatewayProxyResponseEvent apiGatewayProxyResponseEvent = - this.savePersonApiHandler - .handleRequest(apiGatewayProxyRequestEvent("invalid sample request"), mock(Context.class)); + var request = apiGatewayProxyRequestEvent("invalid sample request"); + var ctx = mock(Context.class); + var apiGatewayProxyResponseEvent = this.savePersonApiHandler.handleRequest(request, ctx); Assert.assertNotNull(apiGatewayProxyResponseEvent); - Assert.assertEquals(new Integer(400), apiGatewayProxyResponseEvent.getStatusCode()); + Assert.assertEquals(Integer.valueOf(400), apiGatewayProxyResponseEvent.getStatusCode()); } private APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent(String body) { - APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent = new APIGatewayProxyRequestEvent(); + var apiGatewayProxyRequestEvent = new APIGatewayProxyRequestEvent(); return apiGatewayProxyRequestEvent.withBody(body); } private Person newPerson() { - Person person = new Person(); + var person = new Person(); person.setFirstName("Thor"); person.setLastName("Odinson"); - Address address = new Address(); + var address = new Address(); address.setAddressLineOne("1 Odin ln"); address.setCity("Asgard"); address.setState("country of the Gods"); address.setZipCode("00001"); person.setAddress(address); - return person; } } 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 ec6872973449..2231d59e539f 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 @@ -23,16 +23,16 @@ package com.iluwatar.serverless.faas.api; -import com.amazonaws.services.lambda.runtime.Context; -import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNull.notNullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.amazonaws.services.lambda.runtime.Context; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + /** * Unit tests for LambdaInfoApiHandler */ @@ -41,8 +41,8 @@ public class LambdaInfoApiHandlerTest { @Test public void handleRequestWithMockContext() { - LambdaInfoApiHandler lambdaInfoApiHandler = new LambdaInfoApiHandler(); - Context context = mock(Context.class); + var lambdaInfoApiHandler = new LambdaInfoApiHandler(); + var context = mock(Context.class); when(context.getAwsRequestId()).thenReturn("mock aws request id"); assertThat(lambdaInfoApiHandler.handleRequest(null, context), notNullValue()); diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 809454907b10..881ec8ba6090 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -60,5 +60,23 @@ test - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.servicelayer.app.App + + + + + + + + diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java index 22e1700856d9..ea660f01e7bc 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java @@ -31,7 +31,6 @@ import com.iluwatar.servicelayer.spellbook.SpellbookDaoImpl; import com.iluwatar.servicelayer.wizard.Wizard; import com.iluwatar.servicelayer.wizard.WizardDaoImpl; -import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -178,29 +177,21 @@ public static void initData() { * Query the data. */ public static void queryData() { - var service = - new MagicServiceImpl(new WizardDaoImpl(), new SpellbookDaoImpl(), new SpellDaoImpl()); + var wizardDao = new WizardDaoImpl(); + var spellbookDao = new SpellbookDaoImpl(); + var spellDao = new SpellDaoImpl(); + var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); LOGGER.info("Enumerating all wizards"); - for (Wizard w : service.findAllWizards()) { - LOGGER.info(w.getName()); - } + service.findAllWizards().stream().map(Wizard::getName).forEach(LOGGER::info); LOGGER.info("Enumerating all spellbooks"); - for (Spellbook s : service.findAllSpellbooks()) { - LOGGER.info(s.getName()); - } + service.findAllSpellbooks().stream().map(Spellbook::getName).forEach(LOGGER::info); LOGGER.info("Enumerating all spells"); - for (Spell s : service.findAllSpells()) { - LOGGER.info(s.getName()); - } + service.findAllSpells().stream().map(Spell::getName).forEach(LOGGER::info); LOGGER.info("Find wizards with spellbook 'Book of Idores'"); - List wizardsWithSpellbook = service.findWizardsWithSpellbook("Book of Idores"); - for (Wizard w : wizardsWithSpellbook) { - LOGGER.info("{} has 'Book of Idores'", w.getName()); - } + var wizardsWithSpellbook = service.findWizardsWithSpellbook("Book of Idores"); + wizardsWithSpellbook.forEach(w -> LOGGER.info("{} has 'Book of Idores'", w.getName())); LOGGER.info("Find wizards with spell 'Fireball'"); - List wizardsWithSpell = service.findWizardsWithSpell("Fireball"); - for (Wizard w : wizardsWithSpell) { - LOGGER.info("{} has 'Fireball'", w.getName()); - } + var wizardsWithSpell = service.findWizardsWithSpell("Fireball"); + wizardsWithSpell.forEach(w -> LOGGER.info("{} has 'Fireball'", w.getName())); } } diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java index 3c2ae6ed92a7..cf77e4f6e83e 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java @@ -52,10 +52,9 @@ protected SessionFactory getSessionFactory() { @Override public E find(Long id) { - var session = getSessionFactory().openSession(); Transaction tx = null; - E result = null; - try { + E result; + try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); var criteria = session.createCriteria(persistentClass); criteria.add(Restrictions.idEq(id)); @@ -66,17 +65,14 @@ public E find(Long id) { tx.rollback(); } throw e; - } finally { - session.close(); } return result; } @Override public void persist(E entity) { - var session = getSessionFactory().openSession(); Transaction tx = null; - try { + try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); session.persist(entity); tx.commit(); @@ -85,17 +81,14 @@ public void persist(E entity) { tx.rollback(); } throw e; - } finally { - session.close(); } } @Override public E merge(E entity) { - var session = getSessionFactory().openSession(); Transaction tx = null; E result = null; - try { + try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); result = (E) session.merge(entity); tx.commit(); @@ -104,17 +97,14 @@ public E merge(E entity) { tx.rollback(); } throw e; - } finally { - session.close(); } return result; } @Override public void delete(E entity) { - var session = getSessionFactory().openSession(); Transaction tx = null; - try { + try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); session.delete(entity); tx.commit(); @@ -123,17 +113,14 @@ public void delete(E entity) { tx.rollback(); } throw e; - } finally { - session.close(); } } @Override public List findAll() { - var session = getSessionFactory().openSession(); Transaction tx = null; - List result = null; - try { + List result; + try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); Criteria criteria = session.createCriteria(persistentClass); result = criteria.list(); @@ -142,8 +129,6 @@ public List findAll() { tx.rollback(); } throw e; - } finally { - session.close(); } return result; } diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java b/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java index 44c4c12a2d85..bc2e51f138c5 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java @@ -54,14 +54,15 @@ private HibernateUtil() { public static synchronized SessionFactory getSessionFactory() { if (sessionFactory == null) { try { - sessionFactory = - new Configuration().addAnnotatedClass(Wizard.class).addAnnotatedClass(Spellbook.class) - .addAnnotatedClass(Spell.class) - .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect") - .setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1") - .setProperty("hibernate.current_session_context_class", "thread") - .setProperty("hibernate.show_sql", "false") - .setProperty("hibernate.hbm2ddl.auto", "create-drop").buildSessionFactory(); + sessionFactory = new Configuration() + .addAnnotatedClass(Wizard.class) + .addAnnotatedClass(Spellbook.class) + .addAnnotatedClass(Spell.class) + .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect") + .setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1") + .setProperty("hibernate.current_session_context_class", "thread") + .setProperty("hibernate.show_sql", "false") + .setProperty("hibernate.hbm2ddl.auto", "create-drop").buildSessionFactory(); } catch (Throwable ex) { LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java index 06e898a88538..aff1a37c57cf 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java @@ -35,7 +35,7 @@ public class SpellDaoImpl extends DaoBaseImpl implements SpellDao { @Override public Spell findByName(String name) { Transaction tx = null; - Spell result = null; + Spell result; try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); var criteria = session.createCriteria(persistentClass); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java index dcacd2786cda..bc05ebe77356 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java @@ -34,24 +34,19 @@ public class SpellbookDaoImpl extends DaoBaseImpl implements Spellboo @Override public Spellbook findByName(String name) { - var session = getSessionFactory().openSession(); Transaction tx = null; - Spellbook result = null; - try { + Spellbook result; + try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); var criteria = session.createCriteria(persistentClass); criteria.add(Restrictions.eq("name", name)); result = (Spellbook) criteria.uniqueResult(); - result.getSpells().size(); - result.getWizards().size(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; - } finally { - session.close(); } return result; } diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java index ee2f2a03857d..eb27b70f7719 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java @@ -24,9 +24,6 @@ package com.iluwatar.servicelayer.wizard; import com.iluwatar.servicelayer.common.DaoBaseImpl; -import com.iluwatar.servicelayer.spellbook.Spellbook; -import org.hibernate.Criteria; -import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; @@ -37,25 +34,19 @@ public class WizardDaoImpl extends DaoBaseImpl implements WizardDao { @Override public Wizard findByName(String name) { - Session session = getSessionFactory().openSession(); Transaction tx = null; - Wizard result = null; - try { + Wizard result; + try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); - Criteria criteria = session.createCriteria(persistentClass); + var criteria = session.createCriteria(persistentClass); criteria.add(Restrictions.eq("name", name)); result = (Wizard) criteria.uniqueResult(); - for (Spellbook s : result.getSpellbooks()) { - s.getSpells().size(); - } tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; - } finally { - session.close(); } return result; } diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java index f144e026633e..26aa2b168c97 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java @@ -28,16 +28,13 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } @AfterEach diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java index e70cf0625ac7..6b85065ba824 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java @@ -23,22 +23,20 @@ package com.iluwatar.servicelayer.common; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import com.iluwatar.servicelayer.hibernate.HibernateUtil; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - /** - * Date: 12/28/15 - 10:53 PM - * Test for Base Data Access Objects + * Date: 12/28/15 - 10:53 PM Test for Base Data Access Objects + * * @param Type of Base Entity * @param Type of Dao Base Implementation * @author Jeroen Meulemeester @@ -79,8 +77,8 @@ public BaseDaoTest(final Function factory, final D dao) { @BeforeEach public void setUp() { for (int i = 0; i < INITIAL_COUNT; i++) { - final String className = dao.persistentClass.getSimpleName(); - final String entityName = String.format("%s%d", className, ID_GENERATOR.incrementAndGet()); + final var className = dao.persistentClass.getSimpleName(); + final var entityName = String.format("%s%d", className, ID_GENERATOR.incrementAndGet()); this.dao.persist(this.factory.apply(entityName)); } } @@ -96,9 +94,9 @@ protected final D getDao() { @Test public void testFind() { - final List all = this.dao.findAll(); - for (final E entity : all) { - final E byId = this.dao.find(entity.getId()); + final var all = this.dao.findAll(); + for (final var entity : all) { + final var byId = this.dao.find(entity.getId()); assertNotNull(byId); assertEquals(byId.getId(), byId.getId()); } @@ -106,39 +104,39 @@ public void testFind() { @Test public void testDelete() { - final List originalEntities = this.dao.findAll(); + final var originalEntities = this.dao.findAll(); this.dao.delete(originalEntities.get(1)); this.dao.delete(originalEntities.get(2)); - final List entitiesLeft = this.dao.findAll(); + final var entitiesLeft = this.dao.findAll(); assertNotNull(entitiesLeft); assertEquals(INITIAL_COUNT - 2, entitiesLeft.size()); } @Test public void testFindAll() { - final List all = this.dao.findAll(); + final var all = this.dao.findAll(); assertNotNull(all); assertEquals(INITIAL_COUNT, all.size()); } @Test public void testSetId() { - final E entity = this.factory.apply("name"); + final var entity = this.factory.apply("name"); assertNull(entity.getId()); - final Long expectedId = 1L; + final var expectedId = 1L; entity.setId(expectedId); assertEquals(expectedId, entity.getId()); } @Test public void testSetName() { - final E entity = this.factory.apply("name"); + final var entity = this.factory.apply("name"); assertEquals("name", entity.getName()); assertEquals("name", entity.toString()); - final String expectedName = "new name"; + final var expectedName = "new name"; entity.setName(expectedName); assertEquals(expectedName, entity.getName()); assertEquals(expectedName, entity.toString()); diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java index b4b3c5714ca3..f559d2d759be 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java @@ -23,18 +23,6 @@ package com.iluwatar.servicelayer.magic; -import com.iluwatar.servicelayer.spell.Spell; -import com.iluwatar.servicelayer.spell.SpellDao; -import com.iluwatar.servicelayer.spellbook.Spellbook; -import com.iluwatar.servicelayer.spellbook.SpellbookDao; -import com.iluwatar.servicelayer.wizard.Wizard; -import com.iluwatar.servicelayer.wizard.WizardDao; -import org.junit.jupiter.api.Test; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Matchers.eq; @@ -44,6 +32,15 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; +import com.iluwatar.servicelayer.spell.Spell; +import com.iluwatar.servicelayer.spell.SpellDao; +import com.iluwatar.servicelayer.spellbook.Spellbook; +import com.iluwatar.servicelayer.spellbook.SpellbookDao; +import com.iluwatar.servicelayer.wizard.Wizard; +import com.iluwatar.servicelayer.wizard.WizardDao; +import java.util.Set; +import org.junit.jupiter.api.Test; + /** * Date: 12/29/15 - 12:06 AM * @@ -53,11 +50,11 @@ public class MagicServiceImplTest { @Test public void testFindAllWizards() { - final WizardDao wizardDao = mock(WizardDao.class); - final SpellbookDao spellbookDao = mock(SpellbookDao.class); - final SpellDao spellDao = mock(SpellDao.class); + final var wizardDao = mock(WizardDao.class); + final var spellbookDao = mock(SpellbookDao.class); + final var spellDao = mock(SpellDao.class); - final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyZeroInteractions(wizardDao, spellbookDao, spellDao); service.findAllWizards(); @@ -66,12 +63,12 @@ public void testFindAllWizards() { } @Test - public void testFindAllSpellbooks() throws Exception { - final WizardDao wizardDao = mock(WizardDao.class); - final SpellbookDao spellbookDao = mock(SpellbookDao.class); - final SpellDao spellDao = mock(SpellDao.class); + public void testFindAllSpellbooks() { + final var wizardDao = mock(WizardDao.class); + final var spellbookDao = mock(SpellbookDao.class); + final var spellDao = mock(SpellDao.class); - final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyZeroInteractions(wizardDao, spellbookDao, spellDao); service.findAllSpellbooks(); @@ -80,12 +77,12 @@ public void testFindAllSpellbooks() throws Exception { } @Test - public void testFindAllSpells() throws Exception { - final WizardDao wizardDao = mock(WizardDao.class); - final SpellbookDao spellbookDao = mock(SpellbookDao.class); - final SpellDao spellDao = mock(SpellDao.class); + public void testFindAllSpells() { + final var wizardDao = mock(WizardDao.class); + final var spellbookDao = mock(SpellbookDao.class); + final var spellDao = mock(SpellDao.class); - final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyZeroInteractions(wizardDao, spellbookDao, spellDao); service.findAllSpells(); @@ -94,26 +91,27 @@ public void testFindAllSpells() throws Exception { } @Test - public void testFindWizardsWithSpellbook() throws Exception { - final String bookname = "bookname"; - final Spellbook spellbook = mock(Spellbook.class); - final Set wizards = Set.of( - mock(Wizard.class), - mock(Wizard.class), - mock(Wizard.class)); + public void testFindWizardsWithSpellbook() { + final var bookname = "bookname"; + final var spellbook = mock(Spellbook.class); + final var wizards = Set.of( + mock(Wizard.class), + mock(Wizard.class), + mock(Wizard.class) + ); when(spellbook.getWizards()).thenReturn(wizards); - final SpellbookDao spellbookDao = mock(SpellbookDao.class); + final var spellbookDao = mock(SpellbookDao.class); when(spellbookDao.findByName(eq(bookname))).thenReturn(spellbook); - final WizardDao wizardDao = mock(WizardDao.class); - final SpellDao spellDao = mock(SpellDao.class); + final var wizardDao = mock(WizardDao.class); + final var spellDao = mock(SpellDao.class); - final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyZeroInteractions(wizardDao, spellbookDao, spellDao, spellbook); - final List result = service.findWizardsWithSpellbook(bookname); + final var result = service.findWizardsWithSpellbook(bookname); verify(spellbookDao).findByName(eq(bookname)); verify(spellbook).getWizards(); @@ -125,27 +123,28 @@ public void testFindWizardsWithSpellbook() throws Exception { @Test public void testFindWizardsWithSpell() throws Exception { - final Set wizards = Set.of( - mock(Wizard.class), - mock(Wizard.class), - mock(Wizard.class)); - final Spellbook spellbook = mock(Spellbook.class); + final var wizards = Set.of( + mock(Wizard.class), + mock(Wizard.class), + mock(Wizard.class) + ); + final var spellbook = mock(Spellbook.class); when(spellbook.getWizards()).thenReturn(wizards); - final SpellbookDao spellbookDao = mock(SpellbookDao.class); - final WizardDao wizardDao = mock(WizardDao.class); + final var spellbookDao = mock(SpellbookDao.class); + final var wizardDao = mock(WizardDao.class); - final Spell spell = mock(Spell.class); + final var spell = mock(Spell.class); when(spell.getSpellbook()).thenReturn(spellbook); - final String spellName = "spellname"; - final SpellDao spellDao = mock(SpellDao.class); + final var spellName = "spellname"; + final var spellDao = mock(SpellDao.class); when(spellDao.findByName(eq(spellName))).thenReturn(spell); - final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyZeroInteractions(wizardDao, spellbookDao, spellDao, spellbook); - final List result = service.findWizardsWithSpell(spellName); + final var result = service.findWizardsWithSpell(spellName); verify(spellDao).findByName(eq(spellName)); verify(spellbook).getWizards(); diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java index bd6afaedc187..1768df10e616 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java @@ -23,14 +23,12 @@ package com.iluwatar.servicelayer.spell; -import com.iluwatar.servicelayer.common.BaseDaoTest; -import org.junit.jupiter.api.Test; - -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.iluwatar.servicelayer.common.BaseDaoTest; +import org.junit.jupiter.api.Test; + /** * Date: 12/28/15 - 11:02 PM * @@ -44,10 +42,10 @@ public SpellDaoImplTest() { @Test public void testFindByName() { - final SpellDaoImpl dao = getDao(); - final List allSpells = dao.findAll(); - for (final Spell spell : allSpells) { - final Spell spellByName = dao.findByName(spell.getName()); + final var dao = getDao(); + final var allSpells = dao.findAll(); + for (final var spell : allSpells) { + final var spellByName = dao.findByName(spell.getName()); assertNotNull(spellByName); assertEquals(spell.getId(), spellByName.getId()); assertEquals(spell.getName(), spellByName.getName()); diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java index 01fed1bcb79a..f9e4e59f1079 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java @@ -23,14 +23,12 @@ package com.iluwatar.servicelayer.spellbook; -import com.iluwatar.servicelayer.common.BaseDaoTest; -import org.junit.jupiter.api.Test; - -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.iluwatar.servicelayer.common.BaseDaoTest; +import org.junit.jupiter.api.Test; + /** * Date: 12/28/15 - 11:44 PM * @@ -44,10 +42,10 @@ public SpellbookDaoImplTest() { @Test public void testFindByName() { - final SpellbookDaoImpl dao = getDao(); - final List allBooks = dao.findAll(); - for (final Spellbook book : allBooks) { - final Spellbook spellByName = dao.findByName(book.getName()); + final var dao = getDao(); + final var allBooks = dao.findAll(); + for (final var book : allBooks) { + final var spellByName = dao.findByName(book.getName()); assertNotNull(spellByName); assertEquals(book.getId(), spellByName.getId()); assertEquals(book.getName(), spellByName.getName()); diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java index ca2b679c9e2e..e25e434f1c0c 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java @@ -23,14 +23,12 @@ package com.iluwatar.servicelayer.wizard; -import com.iluwatar.servicelayer.common.BaseDaoTest; -import org.junit.jupiter.api.Test; - -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.iluwatar.servicelayer.common.BaseDaoTest; +import org.junit.jupiter.api.Test; + /** * Date: 12/28/15 - 11:46 PM * @@ -44,10 +42,10 @@ public WizardDaoImplTest() { @Test public void testFindByName() { - final WizardDaoImpl dao = getDao(); - final List allWizards = dao.findAll(); - for (final Wizard spell : allWizards) { - final Wizard byName = dao.findByName(spell.getName()); + final var dao = getDao(); + final var allWizards = dao.findAll(); + for (final var spell : allWizards) { + final var byName = dao.findByName(spell.getName()); assertNotNull(byName); assertEquals(spell.getId(), byName.getId()); assertEquals(spell.getName(), byName.getName()); diff --git a/service-locator/pom.xml b/service-locator/pom.xml index 56a11da10b3f..1d8e9fcd878d 100644 --- a/service-locator/pom.xml +++ b/service-locator/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.servicelocator.App + + + + + + + + diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java index 2f3bc9c15092..775de114bbc6 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java @@ -53,15 +53,14 @@ public ServiceCache() { * @return {@link Service} */ public Service getService(String serviceName) { - Service cachedService = null; - for (String serviceJndiName : serviceCache.keySet()) { - if (serviceJndiName.equals(serviceName)) { - cachedService = serviceCache.get(serviceJndiName); - LOGGER.info("(cache call) Fetched service {}({}) from cache... !", - cachedService.getName(), cachedService.getId()); - } + if (serviceCache.containsKey(serviceName)) { + var cachedService = serviceCache.get(serviceName); + var name = cachedService.getName(); + var id = cachedService.getId(); + LOGGER.info("(cache call) Fetched service {}({}) from cache... !", name, id); + return cachedService; } - return cachedService; + return null; } /** diff --git a/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java b/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java index f77f1c612edf..cb4c98c078bb 100644 --- a/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java +++ b/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java b/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java index 16bc934eb017..f4369a7687a1 100644 --- a/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java +++ b/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java @@ -23,14 +23,15 @@ package com.iluwatar.servicelocator; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.List; +import org.junit.jupiter.api.Test; + /** * Date: 12/29/15 - 19:07 PM * @@ -52,12 +53,10 @@ public void testGetNonExistentService() { */ @Test public void testServiceCache() { - final String[] serviceNames = new String[]{ - "jndi/serviceA", "jndi/serviceB" - }; + final var serviceNames = List.of("jndi/serviceA", "jndi/serviceB"); - for (final String serviceName : serviceNames) { - final Service service = ServiceLocator.getService(serviceName); + for (final var serviceName : serviceNames) { + final var service = ServiceLocator.getService(serviceName); assertNotNull(service); assertEquals(serviceName, service.getName()); assertTrue(service.getId() > 0); // The id is generated randomly, but the minimum value is '1' diff --git a/sharding/pom.xml b/sharding/pom.xml index eb24071fa4d5..a641ce3754ad 100644 --- a/sharding/pom.xml +++ b/sharding/pom.xml @@ -41,5 +41,23 @@ junit - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.sharding.App + + + + + + + + \ No newline at end of file diff --git a/sharding/src/main/java/com/iluwatar/sharding/App.java b/sharding/src/main/java/com/iluwatar/sharding/App.java index 482b056b165f..fe3cb79238d9 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/App.java +++ b/sharding/src/main/java/com/iluwatar/sharding/App.java @@ -24,14 +24,14 @@ package com.iluwatar.sharding; /** - * Sharding pattern means dividing a data store into a set of horizontal partitions - * or shards. This pattern can improve scalability when storing and accessing large - * volumes of data. + * Sharding pattern means dividing a data store into a set of horizontal partitions or shards. This + * pattern can improve scalability when storing and accessing large volumes of data. */ public class App { /** * Program main entry point. + * * @param args program runtime arguments */ public static void main(String[] args) { @@ -45,7 +45,7 @@ public static void main(String[] args) { var shard2 = new Shard(2); var shard3 = new Shard(3); - ShardManager manager = new LookupShardManager(); + var manager = new LookupShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); @@ -58,27 +58,27 @@ public static void main(String[] args) { shard2.clearData(); shard3.clearData(); - manager = new RangeShardManager(); - manager.addNewShard(shard1); - manager.addNewShard(shard2); - manager.addNewShard(shard3); - manager.storeData(data1); - manager.storeData(data2); - manager.storeData(data3); - manager.storeData(data4); + var rangeShardManager = new RangeShardManager(); + rangeShardManager.addNewShard(shard1); + rangeShardManager.addNewShard(shard2); + rangeShardManager.addNewShard(shard3); + rangeShardManager.storeData(data1); + rangeShardManager.storeData(data2); + rangeShardManager.storeData(data3); + rangeShardManager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); - manager = new HashShardManager(); - manager.addNewShard(shard1); - manager.addNewShard(shard2); - manager.addNewShard(shard3); - manager.storeData(data1); - manager.storeData(data2); - manager.storeData(data3); - manager.storeData(data4); + var hashShardManager = new HashShardManager(); + hashShardManager.addNewShard(shard1); + hashShardManager.addNewShard(shard2); + hashShardManager.addNewShard(shard3); + hashShardManager.storeData(data1); + hashShardManager.storeData(data2); + hashShardManager.storeData(data3); + hashShardManager.storeData(data4); shard1.clearData(); shard2.clearData(); diff --git a/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java index f282afd28bf8..4948c2a190c4 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java +++ b/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java @@ -58,8 +58,7 @@ protected int allocateShard(Data data) { return lookupMap.get(key); } else { var shardCount = shardMap.size(); - var allocatedShardId = new Random().nextInt(shardCount - 1) + 1; - return allocatedShardId; + return new Random().nextInt(shardCount - 1) + 1; } } diff --git a/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java index f7a8a90af601..bdb862571e65 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java +++ b/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java @@ -27,8 +27,8 @@ import org.slf4j.LoggerFactory; /** - * ShardManager with range strategy. This strategy groups related items together - * in the same shard, and orders them by shard key. + * ShardManager with range strategy. This strategy groups related items together in the same shard, + * and orders them by shard key. */ public class RangeShardManager extends ShardManager { @@ -46,21 +46,16 @@ public int storeData(Data data) { @Override protected int allocateShard(Data data) { var type = data.getType(); - var shardId = -1; switch (type) { case type1: - shardId = 1; - break; + return 1; case type2: - shardId = 2; - break; + return 2; case type3: - shardId = 3; - break; + return 3; default: - break; + return -1; } - return shardId; } } diff --git a/sharding/src/test/java/com/iluwatar/sharding/AppTest.java b/sharding/src/test/java/com/iluwatar/sharding/AppTest.java index fce8d89a3ca6..40e6391bfdf7 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/AppTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/AppTest.java @@ -32,8 +32,7 @@ public class AppTest { @Test public void testMain() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java index 7379859b8272..70650bb506c6 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java @@ -24,7 +24,6 @@ package com.iluwatar.sharding; import java.util.Map; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -57,7 +56,7 @@ public void testStoreData() { lookupShardManager.storeData(data); var field = LookupShardManager.class.getDeclaredField("lookupMap"); field.setAccessible(true); - Map lookupMap = (Map) field.get(lookupShardManager); + var lookupMap = (Map) field.get(lookupShardManager); var shardId = lookupMap.get(1); var shard = lookupShardManager.getShardById(shardId); Assert.assertEquals(data, shard.getDataById(1)); diff --git a/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java index ff4544973ef7..992ad8d5211e 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java @@ -24,7 +24,6 @@ package com.iluwatar.sharding; import java.util.Map; - import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -57,7 +56,7 @@ public void testAddNewShard() { shardManager.addNewShard(shard); var field = ShardManager.class.getDeclaredField("shardMap"); field.setAccessible(true); - Map map = (Map) field.get(shardManager); + var map = (Map) field.get(shardManager); Assert.assertEquals(1, map.size()); Assert.assertEquals(shard, map.get(1)); } catch (NoSuchFieldException | IllegalAccessException e) { @@ -73,7 +72,7 @@ public void testRemoveShardById() { boolean flag = shardManager.removeShardById(1); var field = ShardManager.class.getDeclaredField("shardMap"); field.setAccessible(true); - Map map = (Map) field.get(shardManager); + var map = (Map) field.get(shardManager); Assert.assertEquals(true, flag); Assert.assertEquals(0, map.size()); } catch (IllegalAccessException | NoSuchFieldException e) { @@ -83,9 +82,9 @@ public void testRemoveShardById() { @Test public void testGetShardById() { - Shard shard = new Shard(1); + var shard = new Shard(1); shardManager.addNewShard(shard); - Shard tmpShard = shardManager.getShardById(1); + var tmpShard = shardManager.getShardById(1); Assert.assertEquals(shard, tmpShard); } diff --git a/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java b/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java index 4c0f74fa2e8d..a747933af888 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java @@ -25,7 +25,6 @@ import java.util.HashMap; import java.util.Map; - import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -48,7 +47,8 @@ public void setup() { } @After - public void tearDown() {} + public void tearDown() { + } @Test public void testStoreData() { @@ -56,7 +56,7 @@ public void testStoreData() { shard.storeData(data); var field = Shard.class.getDeclaredField("dataStore"); field.setAccessible(true); - Map dataMap = (Map) field.get(shard); + var dataMap = (Map) field.get(shard); Assert.assertEquals(1, dataMap.size()); Assert.assertEquals(data, dataMap.get(1)); } catch (NoSuchFieldException | IllegalAccessException e) { @@ -68,13 +68,13 @@ public void testStoreData() { @Test public void testClearData() { try { - Map dataMap = new HashMap<>(); + var dataMap = new HashMap(); dataMap.put(1, data); var field = Shard.class.getDeclaredField("dataStore"); field.setAccessible(true); field.set(shard, dataMap); shard.clearData(); - dataMap = (Map) field.get(shard); + dataMap = (HashMap) field.get(shard); Assert.assertEquals(0, dataMap.size()); } catch (NoSuchFieldException | IllegalAccessException e) { Assert.fail("Fail to modify field access."); diff --git a/singleton/README.md b/singleton/README.md index 8c145f1df8be..b2fc0420e25a 100644 --- a/singleton/README.md +++ b/singleton/README.md @@ -41,8 +41,8 @@ public enum EnumIvoryTower { Then in order to use ```java -EnumIvoryTower enumIvoryTower1 = EnumIvoryTower.INSTANCE; -EnumIvoryTower enumIvoryTower2 = EnumIvoryTower.INSTANCE; +var enumIvoryTower1 = EnumIvoryTower.INSTANCE; +var enumIvoryTower2 = EnumIvoryTower.INSTANCE; assertEquals(enumIvoryTower1, enumIvoryTower2); // true ``` diff --git a/singleton/pom.xml b/singleton/pom.xml index 7862cd2a090b..b09602d0ed3e 100644 --- a/singleton/pom.xml +++ b/singleton/pom.xml @@ -43,4 +43,23 @@ junit + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.singleton.App + + + + + + + + diff --git a/singleton/src/main/java/com/iluwatar/singleton/App.java b/singleton/src/main/java/com/iluwatar/singleton/App.java index 604b81184674..319e077ef42b 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/App.java +++ b/singleton/src/main/java/com/iluwatar/singleton/App.java @@ -45,8 +45,7 @@ * example is found in {@link EnumIvoryTower}. At first glance the code looks short and simple. * However, you should be aware of the downsides including committing to implementation strategy, * extending the enum class, serializability and restrictions to coding. These are extensively - * discussed in Stack Overflow: - * http://programmers.stackexchange.com/questions/179386/what-are-the-downsides-of-implementing + * discussed in Stack Overflow: http://programmers.stackexchange.com/questions/179386/what-are-the-downsides-of-implementing * -a-singleton-with-javas-enum

* *

{@link ThreadSafeLazyLoadedIvoryTower} is a Singleton implementation that is initialized on @@ -54,9 +53,9 @@ * synchronized.

* *

Another Singleton implementation that is initialized on demand is found in - * {@link ThreadSafeDoubleCheckLocking}. It is somewhat faster than - * {@link ThreadSafeLazyLoadedIvoryTower} since it doesn't synchronize the whole access method but - * only the method internals on specific conditions.

+ * {@link ThreadSafeDoubleCheckLocking}. It is somewhat faster than {@link + * ThreadSafeLazyLoadedIvoryTower} since it doesn't synchronize the whole access method but only the + * method internals on specific conditions.

* *

Yet another way to implement thread safe lazily initialized Singleton can be found in * {@link InitializingOnDemandHolderIdiom}. However, this implementation requires at least Java 8 @@ -80,10 +79,8 @@ public static void main(String[] args) { LOGGER.info("ivoryTower2={}", ivoryTower2); // lazily initialized singleton - var threadSafeIvoryTower1 = - ThreadSafeLazyLoadedIvoryTower.getInstance(); - var threadSafeIvoryTower2 = - ThreadSafeLazyLoadedIvoryTower.getInstance(); + var threadSafeIvoryTower1 = ThreadSafeLazyLoadedIvoryTower.getInstance(); + var threadSafeIvoryTower2 = ThreadSafeLazyLoadedIvoryTower.getInstance(); LOGGER.info("threadSafeIvoryTower1={}", threadSafeIvoryTower1); LOGGER.info("threadSafeIvoryTower2={}", threadSafeIvoryTower2); @@ -100,11 +97,9 @@ public static void main(String[] args) { LOGGER.info(dcl2.toString()); // initialize on demand holder idiom - var demandHolderIdiom = - InitializingOnDemandHolderIdiom.getInstance(); + var demandHolderIdiom = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom.toString()); - var demandHolderIdiom2 = - InitializingOnDemandHolderIdiom.getInstance(); + var demandHolderIdiom2 = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom2.toString()); } } diff --git a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java index 75043eae0bdc..b7c55ddeafc5 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java @@ -32,7 +32,6 @@ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java b/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java index e855550129f2..cb933666733a 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java @@ -29,7 +29,7 @@ * @author Jeroen Meulemeester */ public class InitializingOnDemandHolderIdiomTest - extends SingletonTest { + extends SingletonTest { /** * Create a new singleton test instance using the given 'getInstance' method. diff --git a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java index 4dc1ecdff589..63d13add4e97 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java @@ -29,13 +29,11 @@ import static org.junit.jupiter.api.Assertions.assertTimeout; import java.util.ArrayList; -import java.util.List; import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; import java.util.function.Supplier; - +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.junit.jupiter.api.Test; /** @@ -73,9 +71,9 @@ public SingletonTest(final Supplier singletonInstanceMethod) { @Test public void testMultipleCallsReturnTheSameObjectInSameThread() { // Create several instances in the same calling thread - S instance1 = this.singletonInstanceMethod.get(); - S instance2 = this.singletonInstanceMethod.get(); - S instance3 = this.singletonInstanceMethod.get(); + var instance1 = this.singletonInstanceMethod.get(); + var instance2 = this.singletonInstanceMethod.get(); + var instance3 = this.singletonInstanceMethod.get(); // now check they are equal assertSame(instance1, instance2); assertSame(instance1, instance3); @@ -89,19 +87,18 @@ public void testMultipleCallsReturnTheSameObjectInSameThread() { public void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exception { assertTimeout(ofMillis(10000), () -> { // Create 10000 tasks and inside each callable instantiate the singleton class - final List> tasks = new ArrayList<>(); - for (int i = 0; i < 10000; i++) { - tasks.add(this.singletonInstanceMethod::get); - } + final var tasks = IntStream.range(0, 10000) + .>mapToObj(i -> this.singletonInstanceMethod::get) + .collect(Collectors.toCollection(ArrayList::new)); // Use up to 8 concurrent threads to handle the tasks - final ExecutorService executorService = Executors.newFixedThreadPool(8); - final List> results = executorService.invokeAll(tasks); + final var executorService = Executors.newFixedThreadPool(8); + final var results = executorService.invokeAll(tasks); // wait for all of the threads to complete - final S expectedInstance = this.singletonInstanceMethod.get(); - for (Future res : results) { - final S instance = res.get(); + final var expectedInstance = this.singletonInstanceMethod.get(); + for (var res : results) { + final var instance = res.get(); assertNotNull(instance); assertSame(expectedInstance, instance); } diff --git a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java index 8babb081e634..b6ba2e5afe71 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java @@ -23,9 +23,7 @@ package com.iluwatar.singleton; -import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; - import org.junit.Test; /** @@ -47,11 +45,10 @@ public ThreadSafeDoubleCheckLockingTest() { */ @Test(expected = InvocationTargetException.class) public void testCreatingNewInstanceByRefection() throws Exception { - ThreadSafeDoubleCheckLocking instance1 = ThreadSafeDoubleCheckLocking.getInstance(); - Constructor constructor = ThreadSafeDoubleCheckLocking.class.getDeclaredConstructor(); + ThreadSafeDoubleCheckLocking.getInstance(); + var constructor = ThreadSafeDoubleCheckLocking.class.getDeclaredConstructor(); constructor.setAccessible(true); - ThreadSafeDoubleCheckLocking instance2 = - (ThreadSafeDoubleCheckLocking) constructor.newInstance(null); + constructor.newInstance((Object[]) null); } -} \ No newline at end of file +} diff --git a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java index da04722fc5e0..cfc3bd030b19 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java @@ -29,7 +29,7 @@ * @author Jeroen Meulemeester */ public class ThreadSafeLazyLoadedIvoryTowerTest - extends SingletonTest { + extends SingletonTest { /** * Create a new singleton test instance using the given 'getInstance' method. diff --git a/spatial-partition/README.md b/spatial-partition/README.md index 8484de876ce0..29d54533dc62 100644 --- a/spatial-partition/README.md +++ b/spatial-partition/README.md @@ -19,9 +19,9 @@ Say, you are building a war game with hundreds, or maybe even thousands of playe ```java public void handleMeLee(Unit units[], int numUnits) { - for (int a = 0; a < numUnits - 1; a++) + for (var a = 0; a < numUnits - 1; a++) { - for (int b = a + 1; b < numUnits; b++) + for (var b = a + 1; b < numUnits; b++) { if (units[a].position() == units[b].position()) { diff --git a/spatial-partition/pom.xml b/spatial-partition/pom.xml index 4b048714de72..7312427d0350 100644 --- a/spatial-partition/pom.xml +++ b/spatial-partition/pom.xml @@ -55,5 +55,24 @@ junit-jupiter-engine test - + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.spatialpartition.App + + + + + + + + diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java index 9a24f22299f3..8a0e2383c293 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java @@ -23,8 +23,6 @@ package com.iluwatar.spatialpartition; -import java.util.ArrayList; -import java.util.Enumeration; import java.util.Hashtable; import java.util.Random; import org.slf4j.Logger; @@ -62,58 +60,46 @@ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - static void noSpatialPartition(int height, int width, - int numOfMovements, Hashtable bubbles) { - ArrayList bubblesToCheck = new ArrayList(); - for (Enumeration e = bubbles.keys(); e.hasMoreElements(); ) { - bubblesToCheck.add(bubbles - .get(e.nextElement())); //all bubbles have to be checked for collision for all bubbles - } + static void noSpatialPartition(int numOfMovements, Hashtable bubbles) { + //all bubbles have to be checked for collision for all bubbles + var bubblesToCheck = bubbles.values(); //will run numOfMovement times or till all bubbles have popped while (numOfMovements > 0 && !bubbles.isEmpty()) { - for (Enumeration e = bubbles.keys(); e.hasMoreElements(); ) { - Integer i = e.nextElement(); + bubbles.forEach((i, bubble) -> { // bubble moves, new position gets updated // and collisions are checked with all bubbles in bubblesToCheck - bubbles.get(i).move(); - bubbles.replace(i, bubbles.get(i)); - bubbles.get(i).handleCollision(bubblesToCheck, bubbles); - } + bubble.move(); + bubbles.replace(i, bubble); + bubble.handleCollision(bubblesToCheck, bubbles); + }); numOfMovements--; } - for (Integer key : bubbles.keySet()) { - //bubbles not popped - LOGGER.info("Bubble " + key + " not popped"); - } + //bubbles not popped + bubbles.keySet().stream().map(key -> "Bubble " + key + " not popped").forEach(LOGGER::info); } static void withSpatialPartition( int height, int width, int numOfMovements, Hashtable bubbles) { //creating quadtree - Rect rect = new Rect(width / 2, height / 2, width, height); - QuadTree quadTree = new QuadTree(rect, 4); + var rect = new Rect(width / 2, height / 2, width, height); + var quadTree = new QuadTree(rect, 4); //will run numOfMovement times or till all bubbles have popped while (numOfMovements > 0 && !bubbles.isEmpty()) { //quadtree updated each time - for (Enumeration e = bubbles.keys(); e.hasMoreElements(); ) { - quadTree.insert(bubbles.get(e.nextElement())); - } - for (Enumeration e = bubbles.keys(); e.hasMoreElements(); ) { - Integer i = e.nextElement(); + bubbles.values().forEach(quadTree::insert); + bubbles.forEach((i, bubble) -> { //bubble moves, new position gets updated, quadtree used to reduce computations - bubbles.get(i).move(); - bubbles.replace(i, bubbles.get(i)); - SpatialPartitionBubbles sp = new SpatialPartitionBubbles(bubbles, quadTree); - sp.handleCollisionsUsingQt(bubbles.get(i)); - } + bubble.move(); + bubbles.replace(i, bubble); + var sp = new SpatialPartitionBubbles(bubbles, quadTree); + sp.handleCollisionsUsingQt(bubble); + }); numOfMovements--; } - for (Integer key : bubbles.keySet()) { - //bubbles not popped - LOGGER.info("Bubble " + key + " not popped"); - } + //bubbles not popped + bubbles.keySet().stream().map(key -> "Bubble " + key + " not popped").forEach(LOGGER::info); } /** @@ -123,23 +109,23 @@ static void withSpatialPartition( */ public static void main(String[] args) { - Hashtable bubbles1 = new Hashtable(); - Hashtable bubbles2 = new Hashtable(); - Random rand = new Random(); + var bubbles1 = new Hashtable(); + var bubbles2 = new Hashtable(); + var rand = new Random(); for (int i = 0; i < 10000; i++) { - Bubble b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); + var b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); bubbles1.put(i, b); bubbles2.put(i, b); LOGGER.info("Bubble " + i + " with radius " + b.radius + " added at (" + b.coordinateX + "," + b.coordinateY + ")"); } - long start1 = System.currentTimeMillis(); - App.noSpatialPartition(300, 300, 20, bubbles1); - long end1 = System.currentTimeMillis(); - long start2 = System.currentTimeMillis(); + var start1 = System.currentTimeMillis(); + App.noSpatialPartition(20, bubbles1); + var end1 = System.currentTimeMillis(); + var start2 = System.currentTimeMillis(); App.withSpatialPartition(300, 300, 20, bubbles2); - long end2 = System.currentTimeMillis(); + var end2 = System.currentTimeMillis(); LOGGER.info("Without spatial partition takes " + (end1 - start1) + "ms"); LOGGER.info("With spatial partition takes " + (end2 - start2) + "ms"); } diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java index 57dc06491cc6..9c39c29c8542 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java @@ -23,7 +23,7 @@ package com.iluwatar.spatialpartition; -import java.util.ArrayList; +import java.util.Collection; import java.util.Hashtable; import java.util.Random; import org.slf4j.Logger; @@ -64,10 +64,10 @@ void pop(Hashtable allBubbles) { allBubbles.remove(this.id); } - void handleCollision(ArrayList bubblesToCheck, Hashtable allBubbles) { - boolean toBePopped = false; //if any other bubble collides with it, made true - for (int i = 0; i < bubblesToCheck.size(); i++) { - Integer otherId = bubblesToCheck.get(i).id; + void handleCollision(Collection toCheck, Hashtable allBubbles) { + var toBePopped = false; //if any other bubble collides with it, made true + for (var point : toCheck) { + var otherId = point.id; if (allBubbles.get(otherId) != null && //the bubble hasn't been popped yet this.id != otherId && //the two bubbles are not the same this.touches(allBubbles.get(otherId))) { //the bubbles touch diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java index ed4fb22cdbc8..410beae349a7 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java @@ -23,7 +23,7 @@ package com.iluwatar.spatialpartition; -import java.util.ArrayList; +import java.util.Collection; import java.util.Hashtable; /** @@ -61,8 +61,8 @@ public abstract class Point { /** * handling interactions/collisions with other objects. * - * @param pointsToCheck contains the objects which need to be checked - * @param allPoints contains hashtable of all points on field at this time + * @param toCheck contains the objects which need to be checked + * @param all contains hashtable of all points on field at this time */ - abstract void handleCollision(ArrayList pointsToCheck, Hashtable allPoints); + abstract void handleCollision(Collection toCheck, Hashtable all); } diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java index 79731e6acba1..5eda3df2ebe2 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java @@ -23,8 +23,7 @@ package com.iluwatar.spatialpartition; -import java.util.ArrayList; -import java.util.Enumeration; +import java.util.Collection; import java.util.Hashtable; /** @@ -47,7 +46,7 @@ public class QuadTree { this.boundary = boundary; this.capacity = capacity; this.divided = false; - this.points = new Hashtable(); + this.points = new Hashtable<>(); this.northwest = null; this.northeast = null; this.southwest = null; @@ -76,30 +75,29 @@ void insert(Point p) { } void divide() { - double x = this.boundary.coordinateX; - double y = this.boundary.coordinateY; - double width = this.boundary.width; - double height = this.boundary.height; - Rect nw = new Rect(x - width / 4, y + height / 4, width / 2, height / 2); + var x = this.boundary.coordinateX; + var y = this.boundary.coordinateY; + var width = this.boundary.width; + var height = this.boundary.height; + var nw = new Rect(x - width / 4, y + height / 4, width / 2, height / 2); this.northwest = new QuadTree(nw, this.capacity); - Rect ne = new Rect(x + width / 4, y + height / 4, width / 2, height / 2); + var ne = new Rect(x + width / 4, y + height / 4, width / 2, height / 2); this.northeast = new QuadTree(ne, this.capacity); - Rect sw = new Rect(x - width / 4, y - height / 4, width / 2, height / 2); + var sw = new Rect(x - width / 4, y - height / 4, width / 2, height / 2); this.southwest = new QuadTree(sw, this.capacity); - Rect se = new Rect(x + width / 4, y - height / 4, width / 2, height / 2); + var se = new Rect(x + width / 4, y - height / 4, width / 2, height / 2); this.southeast = new QuadTree(se, this.capacity); this.divided = true; } - ArrayList query(Rect r, ArrayList relevantPoints) { + Collection query(Rect r, Collection relevantPoints) { //could also be a circle instead of a rectangle if (this.boundary.intersects(r)) { - for (Enumeration e = this.points.keys(); e.hasMoreElements(); ) { - Integer i = e.nextElement(); - if (r.contains(this.points.get(i))) { - relevantPoints.add(this.points.get(i)); - } - } + this.points + .values() + .stream() + .filter(r::contains) + .forEach(relevantPoints::add); if (this.divided) { this.northwest.query(r, relevantPoints); this.northeast.query(r, relevantPoints); diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java index 3dd6c113b6a8..b3f60632f5d9 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java @@ -24,6 +24,7 @@ package com.iluwatar.spatialpartition; import java.util.ArrayList; +import java.util.Collection; import java.util.Hashtable; /** @@ -44,8 +45,8 @@ public class SpatialPartitionBubbles extends SpatialPartitionGeneric { void handleCollisionsUsingQt(Bubble b) { // finding points within area of a square drawn with centre same as // centre of bubble and length = radius of bubble - Rect rect = new Rect(b.coordinateX, b.coordinateY, 2 * b.radius, 2 * b.radius); - ArrayList quadTreeQueryResult = new ArrayList(); + var rect = new Rect(b.coordinateX, b.coordinateY, 2 * b.radius, 2 * b.radius); + var quadTreeQueryResult = new ArrayList(); this.quadTree.query(rect, quadTreeQueryResult); //handling these collisions b.handleCollision(quadTreeQueryResult, this.bubbles); diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java index c9fab045b006..957a36ce37f0 100644 --- a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java +++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java @@ -23,62 +23,71 @@ package com.iluwatar.spatialpartition; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Hashtable; import org.junit.jupiter.api.Test; /** -* Testing methods in Bubble class. -*/ + * Testing methods in Bubble class. + */ class BubbleTest { @Test void moveTest() { - Bubble b = new Bubble(10,10,1,2); - int initialX = b.coordinateX; - int initialY = b.coordinateY; + var b = new Bubble(10, 10, 1, 2); + var initialX = b.coordinateX; + var initialY = b.coordinateY; b.move(); //change in x and y < |2| - assertTrue((b.coordinateX - initialX < 2 && b.coordinateX - initialX > -2) && (b.coordinateY - initialY < 2 && b.coordinateY - initialY > -2)); + assertTrue(b.coordinateX - initialX < 2 && b.coordinateX - initialX > -2); + assertTrue(b.coordinateY - initialY < 2 && b.coordinateY - initialY > -2); } @Test void touchesTest() { - Bubble b1 = new Bubble(0,0,1,2); - Bubble b2 = new Bubble(1,1,2,1); - Bubble b3 = new Bubble(10,10,3,1); + var b1 = new Bubble(0, 0, 1, 2); + var b2 = new Bubble(1, 1, 2, 1); + var b3 = new Bubble(10, 10, 3, 1); //b1 touches b2 but not b3 - assertTrue(b1.touches(b2) && !b1.touches(b3)); + assertTrue(b1.touches(b2)); + assertFalse(b1.touches(b3)); } @Test void popTest() { - Bubble b1 = new Bubble(10,10,1,2); - Bubble b2 = new Bubble(0,0,2,2); - Hashtable bubbles = new Hashtable(); - bubbles.put(1, b1); + var b1 = new Bubble(10, 10, 1, 2); + var b2 = new Bubble(0, 0, 2, 2); + var bubbles = new Hashtable(); + bubbles.put(1, b1); bubbles.put(2, b2); b1.pop(bubbles); //after popping, bubble no longer in hashtable containing all bubbles - assertTrue(bubbles.get(1) == null && bubbles.get(2) != null); + assertNull(bubbles.get(1)); + assertNotNull(bubbles.get(2)); } @Test void handleCollisionTest() { - Bubble b1 = new Bubble(0,0,1,2); - Bubble b2 = new Bubble(1,1,2,1); - Bubble b3 = new Bubble(10,10,3,1); - Hashtable bubbles = new Hashtable(); - bubbles.put(1, b1); - bubbles.put(2, b2); + var b1 = new Bubble(0, 0, 1, 2); + var b2 = new Bubble(1, 1, 2, 1); + var b3 = new Bubble(10, 10, 3, 1); + var bubbles = new Hashtable(); + bubbles.put(1, b1); + bubbles.put(2, b2); bubbles.put(3, b3); - ArrayList bubblesToCheck = new ArrayList(); - bubblesToCheck.add(b2); + var bubblesToCheck = new ArrayList(); + bubblesToCheck.add(b2); bubblesToCheck.add(b3); b1.handleCollision(bubblesToCheck, bubbles); //b1 touches b2 and not b3, so b1, b2 will be popped - assertTrue(bubbles.get(1) == null && bubbles.get(2) == null && bubbles.get(3) != null); + assertNull(bubbles.get(1)); + assertNull(bubbles.get(2)); + assertNotNull(bubbles.get(3)); } } diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java index 9335cd9c9641..66306fa36423 100644 --- a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java +++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java @@ -23,12 +23,13 @@ package com.iluwatar.spatialpartition; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; +import java.util.Collection; import java.util.Hashtable; import java.util.Random; - - +import java.util.stream.Collectors; import org.junit.jupiter.api.Test; /** @@ -39,41 +40,34 @@ class QuadTreeTest { @Test void queryTest() { - ArrayList points = new ArrayList(); - Random rand = new Random(); + var points = new ArrayList(); + var rand = new Random(); for (int i = 0; i < 20; i++) { - Bubble p = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); + var p = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); points.add(p); } - Rect field = new Rect(150,150,300,300); //size of field - Rect queryRange = new Rect(70,130,100,100); //result = all points lying in this rectangle + var field = new Rect(150, 150, 300, 300); //size of field + var queryRange = new Rect(70, 130, 100, 100); //result = all points lying in this rectangle //points found in the query range using quadtree and normal method is same - assertTrue(QuadTreeTest.quadTreeTest(points, field, queryRange).equals(QuadTreeTest.verify(points, queryRange))); + var points1 = QuadTreeTest.quadTreeTest(points, field, queryRange); + var points2 = QuadTreeTest.verify(points, queryRange); + assertEquals(points1, points2); } - static Hashtable quadTreeTest(ArrayList points, Rect field, Rect queryRange) { + static Hashtable quadTreeTest(Collection points, Rect field, Rect queryRange) { //creating quadtree and inserting all points - QuadTree qTree = new QuadTree(queryRange, 4); - for (int i = 0; i < points.size(); i++) { - qTree.insert(points.get(i)); - } + var qTree = new QuadTree(queryRange, 4); + points.forEach(qTree::insert); - ArrayList queryResult = qTree.query(field, new ArrayList()); - Hashtable result = new Hashtable(); - for (int i = 0; i < queryResult.size(); i++) { - Point p = queryResult.get(i); - result.put(p.id, p); - } - return result; + return qTree + .query(field, new ArrayList<>()) + .stream() + .collect(Collectors.toMap(p -> p.id, p -> p, (a, b) -> b, Hashtable::new)); } - static Hashtable verify(ArrayList points, Rect queryRange) { - Hashtable result = new Hashtable(); - for (int i = 0; i < points.size(); i++) { - if (queryRange.contains(points.get(i))) { - result.put(points.get(i).id, points.get(i)); - } - } - return result; + static Hashtable verify(Collection points, Rect queryRange) { + return points.stream() + .filter(queryRange::contains) + .collect(Collectors.toMap(point -> point.id, point -> point, (a, b) -> b, Hashtable::new)); } } diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java index 599b0d9f48ae..8ec4b992e3a6 100644 --- a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java +++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java @@ -23,7 +23,9 @@ package com.iluwatar.spatialpartition; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.Test; /** @@ -34,19 +36,21 @@ class RectTest { @Test void containsTest() { - Rect r = new Rect(10,10,20,20); - Bubble b1 = new Bubble(2,2,1,1); - Bubble b2 = new Bubble(30,30,2,1); + var r = new Rect(10, 10, 20, 20); + var b1 = new Bubble(2, 2, 1, 1); + var b2 = new Bubble(30, 30, 2, 1); //r contains b1 and not b2 - assertTrue(r.contains(b1) && !r.contains(b2)); + assertTrue(r.contains(b1)); + assertFalse(r.contains(b2)); } @Test void intersectsTest() { - Rect r1 = new Rect(10,10,20,20); - Rect r2 = new Rect(15,15,20,20); - Rect r3 = new Rect(50,50,20,20); + var r1 = new Rect(10, 10, 20, 20); + var r2 = new Rect(15, 15, 20, 20); + var r3 = new Rect(50, 50, 20, 20); //r1 intersects r2 and not r3 - assertTrue(r1.intersects(r2) && !r1.intersects(r3)); + assertTrue(r1.intersects(r2)); + assertFalse(r1.intersects(r3)); } } diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java index aac2e0d69992..3470b27ccba0 100644 --- a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java +++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java @@ -23,7 +23,9 @@ package com.iluwatar.spatialpartition; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.util.Hashtable; import org.junit.jupiter.api.Test; @@ -35,24 +37,27 @@ class SpatialPartitionBubblesTest { @Test void handleCollisionsUsingQtTest() { - Bubble b1 = new Bubble(10,10,1,3); - Bubble b2 = new Bubble(5,5,2,1); - Bubble b3 = new Bubble(9,9,3,1); - Bubble b4 = new Bubble(8,8,4,2); - Hashtable bubbles = new Hashtable(); - bubbles.put(1, b1); - bubbles.put(2, b2); - bubbles.put(3, b3); + var b1 = new Bubble(10, 10, 1, 3); + var b2 = new Bubble(5, 5, 2, 1); + var b3 = new Bubble(9, 9, 3, 1); + var b4 = new Bubble(8, 8, 4, 2); + var bubbles = new Hashtable(); + bubbles.put(1, b1); + bubbles.put(2, b2); + bubbles.put(3, b3); bubbles.put(4, b4); - Rect r = new Rect(10,10,20,20); - QuadTree qt = new QuadTree(r,4); - qt.insert(b1); - qt.insert(b2); - qt.insert(b3); + var r = new Rect(10, 10, 20, 20); + var qt = new QuadTree(r, 4); + qt.insert(b1); + qt.insert(b2); + qt.insert(b3); qt.insert(b4); - SpatialPartitionBubbles sp = new SpatialPartitionBubbles(bubbles, qt); + var sp = new SpatialPartitionBubbles(bubbles, qt); sp.handleCollisionsUsingQt(b1); //b1 touches b3 and b4 but not b2 - so b1,b3,b4 get popped - assertTrue(bubbles.get(1) == null && bubbles.get(2) != null && bubbles.get(3) == null && bubbles.get(4) == null); + assertNull(bubbles.get(1)); + assertNotNull(bubbles.get(2)); + assertNull(bubbles.get(3)); + assertNull(bubbles.get(4)); } } diff --git a/specification/README.md b/specification/README.md index d5e7edf20bed..6e52bd2e77b7 100644 --- a/specification/README.md +++ b/specification/README.md @@ -100,24 +100,24 @@ public class MassGreaterThanSelector extends AbstractSelector { With these building blocks in place, we can perform a search for red creatures as follows: ```java - List redCreatures = creatures.stream().filter(new ColorSelector(Color.RED)) + var redCreatures = creatures.stream().filter(new ColorSelector(Color.RED)) .collect(Collectors.toList()); ``` But we could also use our parameterized selector like this: ```java - List heavyCreatures = creatures.stream().filter(new MassGreaterThanSelector(500.0) + var heavyCreatures = creatures.stream().filter(new MassGreaterThanSelector(500.0) .collect(Collectors.toList()); ``` Our third option is to combine multiple selectors together. Performing a search for special creatures (defined as red, flying, and not small) could be done as follows: ```java - AbstractSelector specialCreaturesSelector = + var specialCreaturesSelector = new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)).and(new SizeSelector(Size.SMALL).not()); - List specialCreatures = creatures.stream().filter(specialCreaturesSelector) + var specialCreatures = creatures.stream().filter(specialCreaturesSelector) .collect(Collectors.toList()); ``` diff --git a/specification/pom.xml b/specification/pom.xml index 79d81fd5c3a8..9214e984e90b 100644 --- a/specification/pom.xml +++ b/specification/pom.xml @@ -49,4 +49,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.specification.app.App + + + + + + + + diff --git a/specification/src/main/java/com/iluwatar/specification/app/App.java b/specification/src/main/java/com/iluwatar/specification/app/App.java index 2f9633313d83..2ccb3047fa52 100644 --- a/specification/src/main/java/com/iluwatar/specification/app/App.java +++ b/specification/src/main/java/com/iluwatar/specification/app/App.java @@ -32,14 +32,14 @@ import com.iluwatar.specification.creature.Troll; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Movement; -import com.iluwatar.specification.selector.AbstractSelector; import com.iluwatar.specification.selector.ColorSelector; import com.iluwatar.specification.selector.MassEqualSelector; import com.iluwatar.specification.selector.MassGreaterThanSelector; import com.iluwatar.specification.selector.MassSmallerThanOrEqSelector; import com.iluwatar.specification.selector.MovementSelector; import java.util.List; -import java.util.stream.Collectors; +import java.util.Objects; +import java.util.function.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -63,57 +63,47 @@ public class App { */ public static void main(String[] args) { // initialize creatures list - List creatures = List.of(new Goblin(), new Octopus(), new Dragon(), new Shark(), - new Troll(), new KillerBee()); + var creatures = List.of( + new Goblin(), + new Octopus(), + new Dragon(), + new Shark(), + new Troll(), + new KillerBee() + ); // so-called "hard-coded" specification LOGGER.info("Demonstrating hard-coded specification :"); // find all walking creatures LOGGER.info("Find all walking creatures"); - List walkingCreatures = - creatures.stream().filter(new MovementSelector(Movement.WALKING)) - .collect(Collectors.toList()); - walkingCreatures.forEach(c -> LOGGER.info(c.toString())); + print(creatures, new MovementSelector(Movement.WALKING)); // find all dark creatures LOGGER.info("Find all dark creatures"); - List darkCreatures = - creatures.stream().filter(new ColorSelector(Color.DARK)).collect(Collectors.toList()); - darkCreatures.forEach(c -> LOGGER.info(c.toString())); - + print(creatures, new ColorSelector(Color.DARK)); LOGGER.info("\n"); // so-called "parameterized" specification LOGGER.info("Demonstrating parameterized specification :"); // find all creatures heavier than 500kg LOGGER.info("Find all creatures heavier than 600kg"); - List heavyCreatures = - creatures.stream().filter(new MassGreaterThanSelector(600.0)) - .collect(Collectors.toList()); - heavyCreatures.forEach(c -> LOGGER.info(c.toString())); + print(creatures, new MassGreaterThanSelector(600.0)); // find all creatures heavier than 500kg LOGGER.info("Find all creatures lighter than or weighing exactly 500kg"); - List lightCreatures = - creatures.stream().filter(new MassSmallerThanOrEqSelector(500.0)) - .collect(Collectors.toList()); - lightCreatures.forEach(c -> LOGGER.info(c.toString())); - + print(creatures, new MassSmallerThanOrEqSelector(500.0)); LOGGER.info("\n"); // so-called "composite" specification LOGGER.info("Demonstrating composite specification :"); // find all red and flying creatures LOGGER.info("Find all red and flying creatures"); - List redAndFlyingCreatures = - creatures.stream() - .filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING))) - .collect(Collectors.toList()); - redAndFlyingCreatures.forEach(c -> LOGGER.info(c.toString())); + var redAndFlying = new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)); + print(creatures, redAndFlying); // find all creatures dark or red, non-swimming, and heavier than or equal to 400kg LOGGER.info("Find all scary creatures"); - AbstractSelector scaryCreaturesSelector = new ColorSelector(Color.DARK) + var scaryCreaturesSelector = new ColorSelector(Color.DARK) .or(new ColorSelector(Color.RED)).and(new MovementSelector(Movement.SWIMMING).not()) .and(new MassGreaterThanSelector(400.0).or(new MassEqualSelector(400.0))); - List scaryCreatures = - creatures.stream() - .filter(scaryCreaturesSelector) - .collect(Collectors.toList()); - scaryCreatures.forEach(c -> LOGGER.info(c.toString())); + print(creatures, scaryCreaturesSelector); + } + + private static void print(List creatures, Predicate selector) { + creatures.stream().filter(selector).map(Objects::toString).forEach(LOGGER::info); } } diff --git a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java index 7585a113d34d..bc6f2226f6f8 100644 --- a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java +++ b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java @@ -32,7 +32,6 @@ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java b/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java index 58af7248a867..c0a10c19ee74 100644 --- a/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java +++ b/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java @@ -83,27 +83,24 @@ public void testGetMovement(Creature testedCreature, String name, Size size, Mov @ParameterizedTest @MethodSource("dataProvider") public void testGetColor(Creature testedCreature, String name, Size size, Movement movement, - Color color) { + Color color) { assertEquals(color, testedCreature.getColor()); } @ParameterizedTest @MethodSource("dataProvider") public void testGetMass(Creature testedCreature, String name, Size size, Movement movement, - Color color, Mass mass) { + Color color, Mass mass) { assertEquals(mass, testedCreature.getMass()); } @ParameterizedTest @MethodSource("dataProvider") public void testToString(Creature testedCreature, String name, Size size, Movement movement, - Color color, Mass mass) { - final String toString = testedCreature.toString(); + Color color, Mass mass) { + final var toString = testedCreature.toString(); assertNotNull(toString); - assertEquals( - String.format("%s [size=%s, movement=%s, color=%s, mass=%s]", name, size, movement, color, - mass), - toString - ); + assertEquals(String + .format("%s [size=%s, movement=%s, color=%s, mass=%s]", name, size, movement, color, mass), toString); } } \ No newline at end of file diff --git a/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java index f1029063dc50..61224819fd1a 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java @@ -44,13 +44,13 @@ public class ColorSelectorTest { */ @Test public void testColor() { - final Creature greenCreature = mock(Creature.class); + final var greenCreature = mock(Creature.class); when(greenCreature.getColor()).thenReturn(Color.GREEN); - final Creature redCreature = mock(Creature.class); + final var redCreature = mock(Creature.class); when(redCreature.getColor()).thenReturn(Color.RED); - final ColorSelector greenSelector = new ColorSelector(Color.GREEN); + final var greenSelector = new ColorSelector(Color.GREEN); assertTrue(greenSelector.test(greenCreature)); assertFalse(greenSelector.test(redCreature)); diff --git a/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java b/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java index 75809c54280f..62febf78dc2c 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java @@ -40,16 +40,16 @@ public class CompositeSelectorsTest { */ @Test public void testAndComposition() { - final Creature swimmingHeavyCreature = mock(Creature.class); + final var swimmingHeavyCreature = mock(Creature.class); when(swimmingHeavyCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingHeavyCreature.getMass()).thenReturn(new Mass(100.0)); - final Creature swimmingLightCreature = mock(Creature.class); + final var swimmingLightCreature = mock(Creature.class); when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); - final AbstractSelector lightAndSwimmingSelector = new MassSmallerThanOrEqSelector( - 50.0).and(new MovementSelector(Movement.SWIMMING)); + final var lightAndSwimmingSelector = new MassSmallerThanOrEqSelector(50.0) + .and(new MovementSelector(Movement.SWIMMING)); assertFalse(lightAndSwimmingSelector.test(swimmingHeavyCreature)); assertTrue(lightAndSwimmingSelector.test(swimmingLightCreature)); } @@ -59,15 +59,15 @@ public void testAndComposition() { */ @Test public void testOrComposition() { - final Creature swimmingHeavyCreature = mock(Creature.class); + final var swimmingHeavyCreature = mock(Creature.class); when(swimmingHeavyCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingHeavyCreature.getMass()).thenReturn(new Mass(100.0)); - final Creature swimmingLightCreature = mock(Creature.class); + final var swimmingLightCreature = mock(Creature.class); when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); - final AbstractSelector lightOrSwimmingSelector = new MassSmallerThanOrEqSelector(50.0) + final var lightOrSwimmingSelector = new MassSmallerThanOrEqSelector(50.0) .or(new MovementSelector(Movement.SWIMMING)); assertTrue(lightOrSwimmingSelector.test(swimmingHeavyCreature)); assertTrue(lightOrSwimmingSelector.test(swimmingLightCreature)); @@ -78,15 +78,15 @@ public void testOrComposition() { */ @Test public void testNotComposition() { - final Creature swimmingHeavyCreature = mock(Creature.class); + final var swimmingHeavyCreature = mock(Creature.class); when(swimmingHeavyCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingHeavyCreature.getMass()).thenReturn(new Mass(100.0)); - final Creature swimmingLightCreature = mock(Creature.class); + final var swimmingLightCreature = mock(Creature.class); when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); - final AbstractSelector heavySelector = new MassSmallerThanOrEqSelector(50.0).not(); + final var heavySelector = new MassSmallerThanOrEqSelector(50.0).not(); assertTrue(heavySelector.test(swimmingHeavyCreature)); assertFalse(heavySelector.test(swimmingLightCreature)); } diff --git a/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java index 287f401648e6..346cf52317ff 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java @@ -39,13 +39,13 @@ public class MassSelectorTest { */ @Test public void testMass() { - final Creature lightCreature = mock(Creature.class); + final var lightCreature = mock(Creature.class); when(lightCreature.getMass()).thenReturn(new Mass(50.0)); - final Creature heavyCreature = mock(Creature.class); + final var heavyCreature = mock(Creature.class); when(heavyCreature.getMass()).thenReturn(new Mass(2500.0)); - final MassSmallerThanOrEqSelector lightSelector = new MassSmallerThanOrEqSelector(500.0); + final var lightSelector = new MassSmallerThanOrEqSelector(500.0); assertTrue(lightSelector.test(lightCreature)); assertFalse(lightSelector.test(heavyCreature)); } diff --git a/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java index f3d2482ad9fc..7a8b052aab7a 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java @@ -44,13 +44,13 @@ public class MovementSelectorTest { */ @Test public void testMovement() { - final Creature swimmingCreature = mock(Creature.class); + final var swimmingCreature = mock(Creature.class); when(swimmingCreature.getMovement()).thenReturn(Movement.SWIMMING); - final Creature flyingCreature = mock(Creature.class); + final var flyingCreature = mock(Creature.class); when(flyingCreature.getMovement()).thenReturn(Movement.FLYING); - final MovementSelector swimmingSelector = new MovementSelector(Movement.SWIMMING); + final var swimmingSelector = new MovementSelector(Movement.SWIMMING); assertTrue(swimmingSelector.test(swimmingCreature)); assertFalse(swimmingSelector.test(flyingCreature)); diff --git a/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java index 7dcb30ee22f9..4fe9b72eb355 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java @@ -44,13 +44,13 @@ public class SizeSelectorTest { */ @Test public void testMovement() { - final Creature normalCreature = mock(Creature.class); + final var normalCreature = mock(Creature.class); when(normalCreature.getSize()).thenReturn(Size.NORMAL); - final Creature smallCreature = mock(Creature.class); + final var smallCreature = mock(Creature.class); when(smallCreature.getSize()).thenReturn(Size.SMALL); - final SizeSelector normalSelector = new SizeSelector(Size.NORMAL); + final var normalSelector = new SizeSelector(Size.NORMAL); assertTrue(normalSelector.test(normalCreature)); assertFalse(normalSelector.test(smallCreature)); } diff --git a/state/pom.xml b/state/pom.xml index cb90a53f856a..b1ff3f5f3656 100644 --- a/state/pom.xml +++ b/state/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.state.App + + + + + + + + diff --git a/state/src/test/java/com/iluwatar/state/AppTest.java b/state/src/test/java/com/iluwatar/state/AppTest.java index b61fdcb10371..9f7b65ff2bd6 100644 --- a/state/src/test/java/com/iluwatar/state/AppTest.java +++ b/state/src/test/java/com/iluwatar/state/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/state/src/test/java/com/iluwatar/state/MammothTest.java b/state/src/test/java/com/iluwatar/state/MammothTest.java index 1286d74266d7..15624c7abc74 100644 --- a/state/src/test/java/com/iluwatar/state/MammothTest.java +++ b/state/src/test/java/com/iluwatar/state/MammothTest.java @@ -23,20 +23,19 @@ package com.iluwatar.state; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - /** * Date: 12/29/15 - 8:27 PM * @@ -62,27 +61,27 @@ public void tearDown() { */ @Test public void testTimePasses() { - final Mammoth mammoth = new Mammoth(); + final var mammoth = new Mammoth(); mammoth.observe(); assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); - assertEquals(1 , appender.getLogSize()); + assertEquals(1, appender.getLogSize()); mammoth.timePasses(); assertEquals("The mammoth gets angry!", appender.getLastMessage()); - assertEquals(2 , appender.getLogSize()); + assertEquals(2, appender.getLogSize()); mammoth.observe(); assertEquals("The mammoth is furious!", appender.getLastMessage()); - assertEquals(3 , appender.getLogSize()); + assertEquals(3, appender.getLogSize()); mammoth.timePasses(); assertEquals("The mammoth calms down.", appender.getLastMessage()); - assertEquals(4 , appender.getLogSize()); + assertEquals(4, appender.getLogSize()); mammoth.observe(); assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); - assertEquals(5 , appender.getLogSize()); + assertEquals(5, appender.getLogSize()); } @@ -91,7 +90,7 @@ public void testTimePasses() { */ @Test public void testToString() { - final String toString = new Mammoth().toString(); + final var toString = new Mammoth().toString(); assertNotNull(toString); assertEquals("The mammoth", toString); } diff --git a/step-builder/pom.xml b/step-builder/pom.xml index 7733af66dfc9..3cea3b158058 100644 --- a/step-builder/pom.xml +++ b/step-builder/pom.xml @@ -40,4 +40,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.stepbuilder.App + + + + + + + + diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java index 3a9021a0f65b..5216b41064e3 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java @@ -67,21 +67,34 @@ public class App { */ public static void main(String[] args) { - var warrior = - CharacterStepBuilder.newBuilder().name("Amberjill").fighterClass("Paladin") - .withWeapon("Sword").noAbilities().build(); + var warrior = CharacterStepBuilder + .newBuilder() + .name("Amberjill") + .fighterClass("Paladin") + .withWeapon("Sword") + .noAbilities() + .build(); LOGGER.info(warrior.toString()); - var mage = - CharacterStepBuilder.newBuilder().name("Riobard").wizardClass("Sorcerer") - .withSpell("Fireball").withAbility("Fire Aura").withAbility("Teleport") - .noMoreAbilities().build(); + var mage = CharacterStepBuilder + .newBuilder() + .name("Riobard") + .wizardClass("Sorcerer") + .withSpell("Fireball") + .withAbility("Fire Aura") + .withAbility("Teleport") + .noMoreAbilities() + .build(); LOGGER.info(mage.toString()); - var thief = - CharacterStepBuilder.newBuilder().name("Desmond").fighterClass("Rogue").noWeapon().build(); + var thief = CharacterStepBuilder + .newBuilder() + .name("Desmond") + .fighterClass("Rogue") + .noWeapon() + .build(); LOGGER.info(thief.toString()); } diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java index ba460c06fa1c..43bb874f8468 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java @@ -91,15 +91,15 @@ public void setAbilities(List abilities) { @Override public String toString() { - var sb = new StringBuilder(); - sb.append("This is a ") + return new StringBuilder() + .append("This is a ") .append(fighterClass != null ? fighterClass : wizardClass) .append(" named ") .append(name) .append(" armed with a ") .append(weapon != null ? weapon : spell != null ? spell : "with nothing") .append(abilities != null ? " and wielding " + abilities + " abilities" : "") - .append('.'); - return sb.toString(); + .append('.') + .toString(); } } diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java index 9eed4d8bce07..a0c7f84e6eba 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java @@ -165,7 +165,7 @@ public BuildStep noAbilities() { @Override public Character build() { - Character character = new Character(name); + var character = new Character(name); if (fighterClass != null) { character.setFighterClass(fighterClass); diff --git a/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java b/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java index d4e99bc9ea1e..1f3fc6238648 100644 --- a/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java +++ b/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java b/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java index 4c8ebbd3975a..f46541f971fe 100644 --- a/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java +++ b/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java @@ -23,15 +23,13 @@ package com.iluwatar.stepbuilder; -import org.junit.jupiter.api.Test; - -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * Date: 12/29/15 - 9:21 PM * @@ -44,7 +42,7 @@ public class CharacterStepBuilderTest { */ @Test public void testBuildWizard() { - final Character character = CharacterStepBuilder.newBuilder() + final var character = CharacterStepBuilder.newBuilder() .name("Merlin") .wizardClass("alchemist") .withSpell("poison") @@ -58,7 +56,7 @@ public void testBuildWizard() { assertEquals("poison", character.getSpell()); assertNotNull(character.toString()); - final List abilities = character.getAbilities(); + final var abilities = character.getAbilities(); assertNotNull(abilities); assertEquals(2, abilities.size()); assertTrue(abilities.contains("invisibility")); @@ -72,7 +70,7 @@ public void testBuildWizard() { */ @Test public void testBuildPoorWizard() { - final Character character = CharacterStepBuilder.newBuilder() + final var character = CharacterStepBuilder.newBuilder() .name("Merlin") .wizardClass("alchemist") .noSpell() @@ -91,7 +89,7 @@ public void testBuildPoorWizard() { */ @Test public void testBuildWeakWizard() { - final Character character = CharacterStepBuilder.newBuilder() + final var character = CharacterStepBuilder.newBuilder() .name("Merlin") .wizardClass("alchemist") .withSpell("poison") @@ -112,7 +110,7 @@ public void testBuildWeakWizard() { */ @Test public void testBuildWarrior() { - final Character character = CharacterStepBuilder.newBuilder() + final var character = CharacterStepBuilder.newBuilder() .name("Cuauhtemoc") .fighterClass("aztec") .withWeapon("spear") @@ -126,7 +124,7 @@ public void testBuildWarrior() { assertEquals("spear", character.getWeapon()); assertNotNull(character.toString()); - final List abilities = character.getAbilities(); + final var abilities = character.getAbilities(); assertNotNull(abilities); assertEquals(2, abilities.size()); assertTrue(abilities.contains("speed")); @@ -140,7 +138,7 @@ public void testBuildWarrior() { */ @Test public void testBuildPoorWarrior() { - final Character character = CharacterStepBuilder.newBuilder() + final var character = CharacterStepBuilder.newBuilder() .name("Poor warrior") .fighterClass("none") .noWeapon() @@ -160,7 +158,7 @@ public void testBuildPoorWarrior() { */ @Test public void testBuildWeakWarrior() { - final Character character = CharacterStepBuilder.newBuilder() + final var character = CharacterStepBuilder.newBuilder() .name("Weak warrior") .fighterClass("none") .withWeapon("Slingshot") diff --git a/strategy/pom.xml b/strategy/pom.xml index a0f09297ecf2..cd1395c7a764 100644 --- a/strategy/pom.xml +++ b/strategy/pom.xml @@ -49,4 +49,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.subclasssandbox.App + + + + + + + + diff --git a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java index 713eecf43bdd..f1137c4c5f86 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java @@ -32,7 +32,6 @@ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java index c956126836b4..625aa5eaba65 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java @@ -41,8 +41,8 @@ public class DragonSlayerTest { */ @Test public void testGoToBattle() { - final DragonSlayingStrategy strategy = mock(DragonSlayingStrategy.class); - final DragonSlayer dragonSlayer = new DragonSlayer(strategy); + final var strategy = mock(DragonSlayingStrategy.class); + final var dragonSlayer = new DragonSlayer(strategy); dragonSlayer.goToBattle(); verify(strategy).execute(); @@ -54,13 +54,13 @@ public void testGoToBattle() { */ @Test public void testChangeStrategy() { - final DragonSlayingStrategy initialStrategy = mock(DragonSlayingStrategy.class); - final DragonSlayer dragonSlayer = new DragonSlayer(initialStrategy); + final var initialStrategy = mock(DragonSlayingStrategy.class); + final var dragonSlayer = new DragonSlayer(initialStrategy); dragonSlayer.goToBattle(); verify(initialStrategy).execute(); - final DragonSlayingStrategy newStrategy = mock(DragonSlayingStrategy.class); + final var newStrategy = mock(DragonSlayingStrategy.class); dragonSlayer.changeStrategy(newStrategy); dragonSlayer.goToBattle(); diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java index 15106cdd9f8d..cca82cefc066 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java @@ -28,11 +28,9 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; - import java.util.Collection; import java.util.LinkedList; import java.util.List; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; @@ -53,18 +51,18 @@ public class DragonSlayingStrategyTest { */ static Collection dataProvider() { return List.of( - new Object[]{ - new MeleeStrategy(), - "With your Excalibur you sever the dragon's head!" - }, - new Object[]{ - new ProjectileStrategy(), - "You shoot the dragon with the magical crossbow and it falls dead on the ground!" - }, - new Object[]{ - new SpellStrategy(), - "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!" - } + new Object[]{ + new MeleeStrategy(), + "With your Excalibur you sever the dragon's head!" + }, + new Object[]{ + new ProjectileStrategy(), + "You shoot the dragon with the magical crossbow and it falls dead on the ground!" + }, + new Object[]{ + new SpellStrategy(), + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!" + } ); } diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java index 51ed0d455052..83ba5315fd80 100644 --- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java @@ -32,7 +32,6 @@ public class AppTest { @Test public void testMain() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java index ff052a81eb30..97e2ac67d16f 100644 --- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java @@ -70,8 +70,8 @@ public void testSpawnParticles() { public void testActivate() { log.clearLog(); var groundDive = new GroundDive(); - groundDive.activate();; - String[] logs = log.getLog().split("\n"); + groundDive.activate(); + var 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 )"; diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java index 58a349bb5dfd..e192737f6320 100644 --- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java @@ -70,8 +70,8 @@ public void testSpawnParticles() { public void testActivate() { log.clearLog(); var skyLaunch = new SkyLaunch(); - skyLaunch.activate();; - String[] logs = log.getLog().split("\n"); + skyLaunch.activate(); + var 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 )"; diff --git a/template-method/pom.xml b/template-method/pom.xml index e236c28c8340..c449ef04f024 100644 --- a/template-method/pom.xml +++ b/template-method/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.templatemethod.App + + + + + + + + diff --git a/thread-pool/pom.xml b/thread-pool/pom.xml index 14946b393710..0ea0b1266d66 100644 --- a/thread-pool/pom.xml +++ b/thread-pool/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.threadpool.App + + + + + + + + diff --git a/throttling/pom.xml b/throttling/pom.xml index 5192ba28abb7..6ae062c5ea15 100644 --- a/throttling/pom.xml +++ b/throttling/pom.xml @@ -41,5 +41,23 @@ test - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.throttling.App + + + + + + + + diff --git a/tls/pom.xml b/tls/pom.xml index 48273ca715fd..7100ae295927 100644 --- a/tls/pom.xml +++ b/tls/pom.xml @@ -39,4 +39,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.tls.App + + + + + + + + diff --git a/tolerant-reader/pom.xml b/tolerant-reader/pom.xml index c0ebaeaec7e6..2966cca19c9e 100644 --- a/tolerant-reader/pom.xml +++ b/tolerant-reader/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.tolerantreader.App + + + + + + + + diff --git a/trampoline/pom.xml b/trampoline/pom.xml index 1129de4fb265..c72557803a5f 100644 --- a/trampoline/pom.xml +++ b/trampoline/pom.xml @@ -65,6 +65,21 @@ false + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.trampoline.TrampolineApp + + + + + + diff --git a/twin/pom.xml b/twin/pom.xml index bdde082d229f..cb60511c95c9 100644 --- a/twin/pom.xml +++ b/twin/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.twin.App + + + + + + + + diff --git a/typeobjectpattern/pom.xml b/typeobjectpattern/pom.xml index 0d56a8376fdb..c8f0005afd58 100644 --- a/typeobjectpattern/pom.xml +++ b/typeobjectpattern/pom.xml @@ -47,4 +47,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.typeobject.App + + + + + + + + diff --git a/unit-of-work/pom.xml b/unit-of-work/pom.xml index a92cc4110100..cd6ce06f1e8b 100644 --- a/unit-of-work/pom.xml +++ b/unit-of-work/pom.xml @@ -49,6 +49,23 @@ mockito-core - - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.unitofwork.App + + + + + + + + \ No newline at end of file diff --git a/update-method/pom.xml b/update-method/pom.xml index ede79f8f6c06..a89364328ca5 100644 --- a/update-method/pom.xml +++ b/update-method/pom.xml @@ -39,6 +39,23 @@ junit - - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.updatemethod.App + + + + + + + + \ No newline at end of file diff --git a/value-object/pom.xml b/value-object/pom.xml index bf8e4a1e2696..aa4101b5cb94 100644 --- a/value-object/pom.xml +++ b/value-object/pom.xml @@ -37,7 +37,7 @@ com.google.guava guava-testlib - 19.0 + 23.0 test @@ -51,4 +51,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.value.object.App + + + + + + + + diff --git a/visitor/pom.xml b/visitor/pom.xml index c7097611fde5..00497b41f420 100644 --- a/visitor/pom.xml +++ b/visitor/pom.xml @@ -44,4 +44,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.visitor.App + + + + + + + +