From 1fa8a604eb9fa5b2ca3866fd1fe0ca7bcee8fd1e Mon Sep 17 00:00:00 2001 From: Azureyjt Date: Fri, 8 Nov 2019 14:20:32 +0800 Subject: [PATCH 01/32] Sharding Pattern (#1056) * Create sharding module * Add Unit Tests * Fix readme hyperlink * Fix check-style issue --- pom.xml | 1 + sharding/README.md | 27 +++++ sharding/pom.xml | 45 ++++++++ .../main/java/com/iluwatar/sharding/App.java | 88 +++++++++++++++ .../main/java/com/iluwatar/sharding/Data.java | 84 ++++++++++++++ .../iluwatar/sharding/HashShardManager.java | 55 +++++++++ .../iluwatar/sharding/LookupShardManager.java | 66 +++++++++++ .../iluwatar/sharding/RangeShardManager.java | 66 +++++++++++ .../java/com/iluwatar/sharding/Shard.java | 59 ++++++++++ .../com/iluwatar/sharding/ShardManager.java | 103 +++++++++++++++++ .../java/com/iluwatar/sharding/AppTest.java | 39 +++++++ .../sharding/HashShardManagerTest.java | 64 +++++++++++ .../sharding/LookupShardManagerTest.java | 68 ++++++++++++ .../sharding/RangeShardManagerTest.java | 58 ++++++++++ .../iluwatar/sharding/ShardManagerTest.java | 104 ++++++++++++++++++ .../java/com/iluwatar/sharding/ShardTest.java | 83 ++++++++++++++ 16 files changed, 1010 insertions(+) create mode 100644 sharding/README.md create mode 100644 sharding/pom.xml create mode 100644 sharding/src/main/java/com/iluwatar/sharding/App.java create mode 100644 sharding/src/main/java/com/iluwatar/sharding/Data.java create mode 100644 sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java create mode 100644 sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java create mode 100644 sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java create mode 100644 sharding/src/main/java/com/iluwatar/sharding/Shard.java create mode 100644 sharding/src/main/java/com/iluwatar/sharding/ShardManager.java create mode 100644 sharding/src/test/java/com/iluwatar/sharding/AppTest.java create mode 100644 sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java create mode 100644 sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java create mode 100644 sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java create mode 100644 sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java create mode 100644 sharding/src/test/java/com/iluwatar/sharding/ShardTest.java diff --git a/pom.xml b/pom.xml index 8b8139f790e3..6a666caabb3a 100644 --- a/pom.xml +++ b/pom.xml @@ -184,6 +184,7 @@ subclass-sandbox circuit-breaker double-buffer + sharding diff --git a/sharding/README.md b/sharding/README.md new file mode 100644 index 000000000000..b40f08cfccd5 --- /dev/null +++ b/sharding/README.md @@ -0,0 +1,27 @@ + +--- +layout: pattern +title: Sharding +folder: sharding +permalink: /patterns/sharding/ +categories: Other +tags: + - Java + - Difficulty-Beginner +--- + +## Intent +Sharding pattern means divide the data store into horizontal partitions or shards. Each shard has the same schema, but holds its own distinct subset of the data. +A shard is a data store in its own right (it can contain the data for many entities of different types), running on a server acting as a storage node. + +## Applicability +This pattern offers the following benefits: + +- You can scale the system out by adding further shards running on additional storage nodes. +- A system can use off the shelf commodity hardware rather than specialized (and expensive) computers for each storage node. +- You can reduce contention and improved performance by balancing the workload across shards. +- In the cloud, shards can be located physically close to the users that will access the data. + +## Credits + +* [Cloud Design Patterns: Prescriptive Architecture Guidance for Cloud Applications - Sharding Pattern](https://docs.microsoft.com/en-us/previous-versions/msp-n-p/dn589797(v=pandp.10)?redirectedfrom=MSDN) \ No newline at end of file diff --git a/sharding/pom.xml b/sharding/pom.xml new file mode 100644 index 000000000000..f0dd01a7c8a2 --- /dev/null +++ b/sharding/pom.xml @@ -0,0 +1,45 @@ + + + + + java-design-patterns + com.iluwatar + 1.22.0-SNAPSHOT + + 4.0.0 + + sharding + + + + junit + junit + + + + \ 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 new file mode 100644 index 000000000000..482b056b165f --- /dev/null +++ b/sharding/src/main/java/com/iluwatar/sharding/App.java @@ -0,0 +1,88 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.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. + */ +public class App { + + /** + * Program main entry point. + * @param args program runtime arguments + */ + public static void main(String[] args) { + + var data1 = new Data(1, "data1", Data.DataType.type1); + var data2 = new Data(2, "data2", Data.DataType.type2); + var data3 = new Data(3, "data3", Data.DataType.type3); + var data4 = new Data(4, "data4", Data.DataType.type1); + + var shard1 = new Shard(1); + var shard2 = new Shard(2); + var shard3 = new Shard(3); + + ShardManager manager = new LookupShardManager(); + manager.addNewShard(shard1); + manager.addNewShard(shard2); + manager.addNewShard(shard3); + manager.storeData(data1); + manager.storeData(data2); + manager.storeData(data3); + manager.storeData(data4); + + shard1.clearData(); + 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); + + 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); + + shard1.clearData(); + shard2.clearData(); + shard3.clearData(); + } + +} diff --git a/sharding/src/main/java/com/iluwatar/sharding/Data.java b/sharding/src/main/java/com/iluwatar/sharding/Data.java new file mode 100644 index 000000000000..92e84e93ae18 --- /dev/null +++ b/sharding/src/main/java/com/iluwatar/sharding/Data.java @@ -0,0 +1,84 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +/** + * Basic data structure for each tuple stored in data shards. + */ +public class Data { + + private int key; + + private String value; + + private DataType type; + + /** + * Constructor of Data class. + * @param key data key + * @param value data vlue + * @param type data type + */ + public Data(final int key, final String value, final DataType type) { + this.key = key; + this.value = value; + this.type = type; + } + + public int getKey() { + return key; + } + + public void setKey(final int key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } + + public DataType getType() { + return type; + } + + public void setType(DataType type) { + this.type = type; + } + + enum DataType { + type1, type2, type3 + } + + @Override + public String toString() { + return "Data {" + "key=" + + key + ", value='" + value + + '\'' + ", type=" + type + '}'; + } +} + diff --git a/sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java new file mode 100644 index 000000000000..11ada60d72ae --- /dev/null +++ b/sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java @@ -0,0 +1,55 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ShardManager with hash strategy. The purpose of this strategy is to reduce the + * chance of hot-spots in the data. It aims to distribute the data across the shards + * in a way that achieves a balance between the size of each shard and the average + * load that each shard will encounter. + */ +public class HashShardManager extends ShardManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(HashShardManager.class); + + @Override + public int storeData(Data data) { + var shardId = allocateShard(data); + var shard = shardMap.get(shardId); + shard.storeData(data); + LOGGER.info(data.toString() + " is stored in Shard " + shardId); + return shardId; + } + + @Override + protected int allocateShard(Data data) { + var shardCount = shardMap.size(); + var hash = data.getKey() % shardCount; + return hash == 0 ? hash + shardCount : hash; + } + +} diff --git a/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java new file mode 100644 index 000000000000..f282afd28bf8 --- /dev/null +++ b/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java @@ -0,0 +1,66 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ShardManager with lookup strategy. In this strategy the sharding logic implements + * a map that routes a request for data to the shard that contains that data by using + * the shard key. + */ +public class LookupShardManager extends ShardManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(LookupShardManager.class); + + private Map lookupMap = new HashMap<>(); + + @Override + public int storeData(Data data) { + var shardId = allocateShard(data); + lookupMap.put(data.getKey(), shardId); + var shard = shardMap.get(shardId); + shard.storeData(data); + LOGGER.info(data.toString() + " is stored in Shard " + shardId); + return shardId; + } + + @Override + protected int allocateShard(Data data) { + var key = data.getKey(); + if (lookupMap.containsKey(key)) { + return lookupMap.get(key); + } else { + var shardCount = shardMap.size(); + var allocatedShardId = new Random().nextInt(shardCount - 1) + 1; + return allocatedShardId; + } + } + +} diff --git a/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java new file mode 100644 index 000000000000..f7a8a90af601 --- /dev/null +++ b/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java @@ -0,0 +1,66 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 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 { + + private static final Logger LOGGER = LoggerFactory.getLogger(RangeShardManager.class); + + @Override + public int storeData(Data data) { + var shardId = allocateShard(data); + var shard = shardMap.get(shardId); + shard.storeData(data); + LOGGER.info(data.toString() + " is stored in Shard " + shardId); + return shardId; + } + + @Override + protected int allocateShard(Data data) { + var type = data.getType(); + var shardId = -1; + switch (type) { + case type1: + shardId = 1; + break; + case type2: + shardId = 2; + break; + case type3: + shardId = 3; + break; + default: + break; + } + return shardId; + } + +} diff --git a/sharding/src/main/java/com/iluwatar/sharding/Shard.java b/sharding/src/main/java/com/iluwatar/sharding/Shard.java new file mode 100644 index 000000000000..eb081425887e --- /dev/null +++ b/sharding/src/main/java/com/iluwatar/sharding/Shard.java @@ -0,0 +1,59 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import java.util.HashMap; +import java.util.Map; + +/** + * The Shard class stored data in a HashMap. + */ +public class Shard { + + private final int id; + + private Map dataStore; + + public Shard(final int id) { + this.id = id; + this.dataStore = new HashMap<>(); + } + + public void storeData(Data data) { + dataStore.put(data.getKey(), data); + } + + public void clearData() { + dataStore.clear(); + } + + public Data getDataById(final int id) { + return dataStore.get(id); + } + + public int getId() { + return id; + } + +} diff --git a/sharding/src/main/java/com/iluwatar/sharding/ShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/ShardManager.java new file mode 100644 index 000000000000..f244509d503a --- /dev/null +++ b/sharding/src/main/java/com/iluwatar/sharding/ShardManager.java @@ -0,0 +1,103 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Abstract class for ShardManager. + */ +public abstract class ShardManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(ShardManager.class); + + protected Map shardMap; + + public ShardManager() { + shardMap = new HashMap<>(); + } + + /** + * Add a provided shard instance to shardMap. + * + * @param shard new shard instance. + * @return {@code true} if succeed to add the new instance. + * {@code false} if the shardId is already existed. + */ + public boolean addNewShard(final Shard shard) { + var shardId = shard.getId(); + if (!shardMap.containsKey(shardId)) { + shardMap.put(shardId, shard); + return true; + } else { + return false; + } + } + + /** + * Remove a shard instance by provided Id. + * + * @param shardId Id of shard instance to remove. + * @return {@code true} if removed. {@code false} if the shardId is not existed. + */ + public boolean removeShardById(final int shardId) { + if (shardMap.containsKey(shardId)) { + shardMap.remove(shardId); + return true; + } else { + return false; + } + } + + /** + * Get shard instance by provided shardId. + * + * @param shardId id of shard instance to get + * @return required shard instance + */ + public Shard getShardById(final int shardId) { + return shardMap.get(shardId); + } + + /** + * Store data in proper shard instance. + * + * @param data new data + * @return id of shard that the data is stored in + */ + public abstract int storeData(final Data data); + + /** + * Allocate proper shard to provided data. + * + * @param data new data + * @return id of shard that the data should be stored + */ + protected abstract int allocateShard(final Data data); + +} diff --git a/sharding/src/test/java/com/iluwatar/sharding/AppTest.java b/sharding/src/test/java/com/iluwatar/sharding/AppTest.java new file mode 100644 index 000000000000..fce8d89a3ca6 --- /dev/null +++ b/sharding/src/test/java/com/iluwatar/sharding/AppTest.java @@ -0,0 +1,39 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import org.junit.Test; + +/** + * Unit tests for App class. + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } + +} diff --git a/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java new file mode 100644 index 000000000000..6418cf0c4f5b --- /dev/null +++ b/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java @@ -0,0 +1,64 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Unit tests for HashShardManager class. + */ +public class HashShardManagerTest { + + private HashShardManager hashShardManager; + + /** + * Initialize hashShardManager instance. + */ + @Before + public void setup() { + hashShardManager = new HashShardManager(); + var shard1 = new Shard(1); + var shard2 = new Shard(2); + var shard3 = new Shard(3); + hashShardManager.addNewShard(shard1); + hashShardManager.addNewShard(shard2); + hashShardManager.addNewShard(shard3); + } + + @After + public void tearDown() { + + } + + @Test + public void testStoreData() { + var data = new Data(1, "test", Data.DataType.type1); + hashShardManager.storeData(data); + Assert.assertEquals(data, hashShardManager.getShardById(1).getDataById(1)); + } + +} diff --git a/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java new file mode 100644 index 000000000000..7379859b8272 --- /dev/null +++ b/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java @@ -0,0 +1,68 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import java.util.Map; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Unit tests for LookupShardManager class. + */ +public class LookupShardManagerTest { + + private LookupShardManager lookupShardManager; + + /** + * Initialize lookupShardManager instance. + */ + @Before + public void setup() { + lookupShardManager = new LookupShardManager(); + var shard1 = new Shard(1); + var shard2 = new Shard(2); + var shard3 = new Shard(3); + lookupShardManager.addNewShard(shard1); + lookupShardManager.addNewShard(shard2); + lookupShardManager.addNewShard(shard3); + } + + @Test + public void testStoreData() { + try { + var data = new Data(1, "test", Data.DataType.type1); + lookupShardManager.storeData(data); + var field = LookupShardManager.class.getDeclaredField("lookupMap"); + field.setAccessible(true); + Map lookupMap = (Map) field.get(lookupShardManager); + var shardId = lookupMap.get(1); + var shard = lookupShardManager.getShardById(shardId); + Assert.assertEquals(data, shard.getDataById(1)); + } catch (NoSuchFieldException | IllegalAccessException e) { + Assert.fail("Fail to modify field access."); + } + } +} diff --git a/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java new file mode 100644 index 000000000000..997687dfc9f6 --- /dev/null +++ b/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java @@ -0,0 +1,58 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Unit tests for RangeShardManager class. + */ +public class RangeShardManagerTest { + + private RangeShardManager rangeShardManager; + + /** + * Initialize rangeShardManager instance. + */ + @Before + public void setup() { + rangeShardManager = new RangeShardManager(); + var shard1 = new Shard(1); + var shard2 = new Shard(2); + var shard3 = new Shard(3); + rangeShardManager.addNewShard(shard1); + rangeShardManager.addNewShard(shard2); + rangeShardManager.addNewShard(shard3); + } + + @Test + public void testStoreData() { + var data = new Data(1, "test", Data.DataType.type1); + rangeShardManager.storeData(data); + Assert.assertEquals(data, rangeShardManager.getShardById(1).getDataById(1)); + } + +} diff --git a/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java new file mode 100644 index 000000000000..ff4544973ef7 --- /dev/null +++ b/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java @@ -0,0 +1,104 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import java.util.Map; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Unit tests for ShardManager class. + */ +public class ShardManagerTest { + + private ShardManager shardManager; + + /** + * Initialize shardManager instance. + */ + @Before + public void setup() { + shardManager = new TestShardManager(); + } + + @After + public void tearDown() { + + } + + @Test + public void testAddNewShard() { + try { + var shard = new Shard(1); + shardManager.addNewShard(shard); + var field = ShardManager.class.getDeclaredField("shardMap"); + field.setAccessible(true); + Map map = (Map) field.get(shardManager); + Assert.assertEquals(1, map.size()); + Assert.assertEquals(shard, map.get(1)); + } catch (NoSuchFieldException | IllegalAccessException e) { + Assert.fail("Fail to modify field access."); + } + } + + @Test + public void testRemoveShardById() { + try { + var shard = new Shard(1); + shardManager.addNewShard(shard); + boolean flag = shardManager.removeShardById(1); + var field = ShardManager.class.getDeclaredField("shardMap"); + field.setAccessible(true); + Map map = (Map) field.get(shardManager); + Assert.assertEquals(true, flag); + Assert.assertEquals(0, map.size()); + } catch (IllegalAccessException | NoSuchFieldException e) { + Assert.fail("Fail to modify field access."); + } + } + + @Test + public void testGetShardById() { + Shard shard = new Shard(1); + shardManager.addNewShard(shard); + Shard tmpShard = shardManager.getShardById(1); + Assert.assertEquals(shard, tmpShard); + } + + class TestShardManager extends ShardManager { + + @Override + public int storeData(Data data) { + return 0; + } + + @Override + protected int allocateShard(Data data) { + return 0; + } + } +} diff --git a/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java b/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java new file mode 100644 index 000000000000..4c0f74fa2e8d --- /dev/null +++ b/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java @@ -0,0 +1,83 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.sharding; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +/** + * Unit tests for Shard class. + */ +public class ShardTest { + + private Data data; + + private Shard shard; + + @Before + public void setup() { + data = new Data(1, "test", Data.DataType.type1); + shard = new Shard(1); + } + + @After + public void tearDown() {} + + @Test + public void testStoreData() { + try { + shard.storeData(data); + var field = Shard.class.getDeclaredField("dataStore"); + field.setAccessible(true); + Map dataMap = (Map) field.get(shard); + Assert.assertEquals(1, dataMap.size()); + Assert.assertEquals(data, dataMap.get(1)); + } catch (NoSuchFieldException | IllegalAccessException e) { + Assert.fail("Fail to modify field access."); + } + + } + + @Test + public void testClearData() { + try { + Map 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); + Assert.assertEquals(0, dataMap.size()); + } catch (NoSuchFieldException | IllegalAccessException e) { + Assert.fail("Fail to modify field access."); + } + } +} From 6d1c0b1563caa1cc243cbe341864f99d42ee4fcb Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 00:33:22 +0530 Subject: [PATCH 02/32] Resolves checkstyle errors for ambassador, async-method-invocation, balking, bridge, builder (#1058) * Decreases checkstyle errors for ambassador pattern * Reduces checkstyle errors in async-method-invocation * Reduces checkstyle errors in balking * Reduces checkstyle errors in bridge * Reduces checkstyle errors in builder --- .../java/com/iluwatar/ambassador/App.java | 23 +++---- .../java/com/iluwatar/ambassador/Client.java | 5 +- .../iluwatar/ambassador/RemoteService.java | 10 +-- .../ambassador/ServiceAmbassador.java | 9 ++- .../iluwatar/async/method/invocation/App.java | 68 +++++++++---------- .../method/invocation/AsyncCallback.java | 8 +-- .../method/invocation/AsyncExecutor.java | 8 +-- .../async/method/invocation/AsyncResult.java | 5 +- .../invocation/ThreadAsyncExecutor.java | 30 ++++---- .../async/method/invocation/AppTest.java | 2 - .../invocation/ThreadAsyncExecutorTest.java | 64 ++++++++--------- .../main/java/com/iluwatar/balking/App.java | 21 +++--- .../com/iluwatar/balking/WashingMachine.java | 24 +++---- .../iluwatar/balking/WashingMachineState.java | 5 +- .../iluwatar/balking/WashingMachineTest.java | 5 +- .../main/java/com/iluwatar/bridge/App.java | 26 +++---- .../java/com/iluwatar/bridge/Enchantment.java | 4 +- .../iluwatar/bridge/FlyingEnchantment.java | 4 +- .../main/java/com/iluwatar/bridge/Hammer.java | 4 +- .../bridge/SoulEatingEnchantment.java | 4 +- .../main/java/com/iluwatar/bridge/Sword.java | 4 +- .../main/java/com/iluwatar/bridge/Weapon.java | 4 +- .../main/java/com/iluwatar/builder/App.java | 35 +++++----- .../main/java/com/iluwatar/builder/Armor.java | 4 +- .../java/com/iluwatar/builder/HairColor.java | 4 +- .../java/com/iluwatar/builder/HairType.java | 4 +- .../main/java/com/iluwatar/builder/Hero.java | 12 ++-- .../java/com/iluwatar/builder/Profession.java | 4 +- .../java/com/iluwatar/builder/Weapon.java | 4 +- 29 files changed, 179 insertions(+), 225 deletions(-) diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/App.java b/ambassador/src/main/java/com/iluwatar/ambassador/App.java index 6b0b048c8b97..c61ef4935fd1 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/App.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/App.java @@ -24,27 +24,26 @@ package com.iluwatar.ambassador; /** - * * The ambassador pattern creates a helper service that sends network requests on behalf of a * client. It is often used in cloud-based applications to offload features of a remote service. * - * An ambassador service can be thought of as an out-of-process proxy that is co-located with - * the client. Similar to the proxy design pattern, the ambassador service provides an interface - * for another remote service. In addition to the interface, the ambassador provides extra - * functionality and features, specifically offloaded common connectivity tasks. This usually - * consists of monitoring, logging, routing, security etc. This is extremely useful in - * legacy applications where the codebase is difficult to modify and allows for improvements - * in the application's networking capabilities. + *

An ambassador service can be thought of as an out-of-process proxy that is co-located with + * the client. Similar to the proxy design pattern, the ambassador service provides an interface for + * another remote service. In addition to the interface, the ambassador provides extra functionality + * and features, specifically offloaded common connectivity tasks. This usually consists of + * monitoring, logging, routing, security etc. This is extremely useful in legacy applications where + * the codebase is difficult to modify and allows for improvements in the application's networking + * capabilities. * - * In this example, we will the ({@link ServiceAmbassador}) class represents the ambassador while the + *

In this example, we will the ({@link ServiceAmbassador}) class represents the ambassador while + * the * ({@link RemoteService}) class represents a remote application. - * */ public class App { /** - * Entry point - */ + * Entry point. + */ public static void main(String[] args) { Client host1 = new Client(); Client host2 = new Client(); diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/Client.java b/ambassador/src/main/java/com/iluwatar/ambassador/Client.java index fdadd71d26dd..60d0e164dbf5 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/Client.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/Client.java @@ -23,12 +23,11 @@ package com.iluwatar.ambassador; -import org.slf4j.LoggerFactory; - import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * A simple Client + * A simple Client. */ public class Client { diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java index 10da79d0b937..34993159548f 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java @@ -23,12 +23,12 @@ package com.iluwatar.ambassador; +import static java.lang.Thread.sleep; + import com.iluwatar.ambassador.util.RandomProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static java.lang.Thread.sleep; - /** * A remote legacy application represented by a Singleton implementation. */ @@ -55,9 +55,11 @@ private RemoteService() { RemoteService(RandomProvider randomProvider) { this.randomProvider = randomProvider; } + /** - * Remote function takes a value and multiplies it by 10 taking a random amount of time. - * Will sometimes return -1. This imitates connectivity issues a client might have to account for. + * Remote function takes a value and multiplies it by 10 taking a random amount of time. Will + * sometimes return -1. This imitates connectivity issues a client might have to account for. + * * @param value integer value to be multiplied. * @return if waitTime is less than {@link RemoteService#THRESHOLD}, it returns value * 10, * otherwise {@link RemoteServiceInterface#FAILURE}. diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java b/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java index 37b6970b451d..4f191977c1c1 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java @@ -23,17 +23,15 @@ package com.iluwatar.ambassador; +import static java.lang.Thread.sleep; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static java.lang.Thread.sleep; - /** - * * ServiceAmbassador provides an interface for a ({@link Client}) to access ({@link RemoteService}). * The interface adds logging, latency testing and usage of the service in a safe way that will not * add stress to the remote service when connectivity issues occur. - * */ public class ServiceAmbassador implements RemoteServiceInterface { @@ -41,7 +39,8 @@ public class ServiceAmbassador implements RemoteServiceInterface { private static final int RETRIES = 3; private static final int DELAY_MS = 3000; - ServiceAmbassador() {} + ServiceAmbassador() { + } @Override public long doRemoteFunction(int value) { diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java index bc33494f73f5..a85a51ab815b 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java @@ -23,35 +23,34 @@ package com.iluwatar.async.method.invocation; +import java.util.concurrent.Callable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.Callable; - /** * This application demonstrates the async method invocation pattern. Key parts of the pattern are - * AsyncResult which is an intermediate container for an asynchronously evaluated value, - * AsyncCallback which can be provided to be executed on task completion and AsyncExecutor - * that manages the execution of the async tasks. - *

- * The main method shows example flow of async invocations. The main thread starts multiple tasks with variable - * durations and then continues its own work. When the main thread has done it's job it collects the results of the - * async tasks. Two of the tasks are handled with callbacks, meaning the callbacks are executed immediately when the - * tasks complete. - *

- * Noteworthy difference of thread usage between the async results and callbacks is that the async results are collected - * in the main thread but the callbacks are executed within the worker threads. This should be noted when working with - * thread pools. - *

- * Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture and - * ExecutorService are the real world implementations of this pattern. But due to the nature of parallel programming, - * the implementations are not trivial. This example does not take all possible scenarios into account but rather - * provides a simple version that helps to understand the pattern. + * AsyncResult which is an intermediate container for an asynchronously evaluated + * value, AsyncCallback which can be provided to be executed on task completion and + * AsyncExecutor that manages the execution of the async tasks. + * + *

The main method shows example flow of async invocations. The main thread starts multiple + * tasks with variable durations and then continues its own work. When the main thread has done it's + * job it collects the results of the async tasks. Two of the tasks are handled with callbacks, + * meaning the callbacks are executed immediately when the tasks complete. + * + *

Noteworthy difference of thread usage between the async results and callbacks is that the + * async results are collected in the main thread but the callbacks are executed within the worker + * threads. This should be noted when working with thread pools. + * + *

Java provides its own implementations of async method invocation pattern. FutureTask, + * CompletableFuture and ExecutorService are the real world implementations of this pattern. But due + * to the nature of parallel programming, the implementations are not trivial. This example does not + * take all possible scenarios into account but rather provides a simple version that helps to + * understand the pattern. * * @see AsyncResult * @see AsyncCallback * @see AsyncExecutor - * * @see java.util.concurrent.FutureTask * @see java.util.concurrent.CompletableFuture * @see java.util.concurrent.ExecutorService @@ -61,27 +60,29 @@ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point + * Program entry point. */ public static void main(String[] args) throws Exception { // construct a new executor that will run async tasks AsyncExecutor executor = new ThreadAsyncExecutor(); // start few async tasks with varying processing times, two last with callback handlers - AsyncResult asyncResult1 = executor.startProcess(lazyval(10, 500)); - AsyncResult asyncResult2 = executor.startProcess(lazyval("test", 300)); - AsyncResult asyncResult3 = executor.startProcess(lazyval(50L, 700)); - AsyncResult asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Callback result 4")); - AsyncResult asyncResult5 = executor.startProcess(lazyval("callback", 600), callback("Callback result 5")); + final AsyncResult asyncResult1 = executor.startProcess(lazyval(10, 500)); + final AsyncResult asyncResult2 = executor.startProcess(lazyval("test", 300)); + final AsyncResult asyncResult3 = executor.startProcess(lazyval(50L, 700)); + final AsyncResult asyncResult4 = + executor.startProcess(lazyval(20, 400), callback("Callback result 4")); + final AsyncResult asyncResult5 = + executor.startProcess(lazyval("callback", 600), callback("Callback result 5")); // emulate processing in the current thread while async tasks are running in their own threads Thread.sleep(350); // Oh boy I'm working hard here log("Some hard work done"); // wait for completion of the tasks - Integer result1 = executor.endProcess(asyncResult1); - String result2 = executor.endProcess(asyncResult2); - Long result3 = executor.endProcess(asyncResult3); + final Integer result1 = executor.endProcess(asyncResult1); + final String result2 = executor.endProcess(asyncResult2); + final Long result3 = executor.endProcess(asyncResult3); asyncResult4.await(); asyncResult5.await(); @@ -94,10 +95,8 @@ public static void main(String[] args) throws Exception { /** * Creates a callable that lazily evaluates to given value with artificial delay. * - * @param value - * value to evaluate - * @param delayMillis - * artificial delay in milliseconds + * @param value value to evaluate + * @param delayMillis artificial delay in milliseconds * @return new callable for lazy evaluation */ private static Callable lazyval(T value, long delayMillis) { @@ -111,8 +110,7 @@ private static Callable lazyval(T value, long delayMillis) { /** * Creates a simple callback that logs the complete status of the async result. * - * @param name - * callback name + * @param name callback name * @return new async callback */ private static AsyncCallback callback(String name) { diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.java index 950444fe7a17..22b36134ff97 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.java @@ -26,11 +26,9 @@ import java.util.Optional; /** - * - * AsyncCallback interface + * AsyncCallback interface. * - * @param - * + * @param Type of Result */ public interface AsyncCallback { @@ -38,7 +36,7 @@ public interface AsyncCallback { * Complete handler which is executed when async task is completed or fails execution. * * @param value the evaluated value from async task, undefined when execution fails - * @param ex empty value if execution succeeds, some exception if executions fails + * @param ex empty value if execution succeeds, some exception if executions fails */ void onComplete(T value, Optional ex); } diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java index 14e30cbebdc2..819ffd2377ca 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java @@ -27,9 +27,7 @@ import java.util.concurrent.ExecutionException; /** - * - * AsyncExecutor interface - * + * AsyncExecutor interface. */ public interface AsyncExecutor { @@ -45,7 +43,7 @@ public interface AsyncExecutor { * Starts processing of an async task. Returns immediately with async result. Executes callback * when the task is completed. * - * @param task task to be executed asynchronously + * @param task task to be executed asynchronously * @param callback callback to be executed on task completion * @return async result for the task */ @@ -57,7 +55,7 @@ public interface AsyncExecutor { * * @param asyncResult async result of a task * @return evaluated value of the completed task - * @throws ExecutionException if execution has failed, containing the root cause + * @throws ExecutionException if execution has failed, containing the root cause * @throws InterruptedException if the execution is interrupted */ T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException; diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java index c3b8467f1c8a..6aaf233b44f7 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java @@ -26,7 +26,8 @@ import java.util.concurrent.ExecutionException; /** - * AsyncResult interface + * AsyncResult interface. + * * @param parameter returned when getValue is invoked */ public interface AsyncResult { @@ -42,7 +43,7 @@ public interface AsyncResult { * Gets the value of completed async task. * * @return evaluated value or throws ExecutionException if execution has failed - * @throws ExecutionException if execution has failed, containing the root cause + * @throws ExecutionException if execution has failed, containing the root cause * @throws IllegalStateException if execution is not completed */ T getValue() throws ExecutionException; diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java index f05b83b4f21a..ecd28f51941d 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java @@ -29,13 +29,13 @@ import java.util.concurrent.atomic.AtomicInteger; /** - * * Implementation of async executor that creates a new thread for every task. - * */ public class ThreadAsyncExecutor implements AsyncExecutor { - /** Index for thread naming */ + /** + * Index for thread naming. + */ private final AtomicInteger idx = new AtomicInteger(0); @Override @@ -52,12 +52,13 @@ public AsyncResult startProcess(Callable task, AsyncCallback callba } catch (Exception ex) { result.setException(ex); } - } , "executor-" + idx.incrementAndGet()).start(); + }, "executor-" + idx.incrementAndGet()).start(); return result; } @Override - public T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException { + public T endProcess(AsyncResult asyncResult) throws ExecutionException, + InterruptedException { if (!asyncResult.isCompleted()) { asyncResult.await(); } @@ -65,8 +66,9 @@ public T endProcess(AsyncResult asyncResult) throws ExecutionException, I } /** - * Simple implementation of async result that allows completing it successfully with a value or exceptionally with an - * exception. A really simplified version from its real life cousins FutureTask and CompletableFuture. + * Simple implementation of async result that allows completing it successfully with a value or + * exceptionally with an exception. A really simplified version from its real life cousins + * FutureTask and CompletableFuture. * * @see java.util.concurrent.FutureTask * @see java.util.concurrent.CompletableFuture @@ -90,11 +92,10 @@ private static class CompletableResult implements AsyncResult { } /** - * Sets the value from successful execution and executes callback if available. Notifies any thread waiting for - * completion. + * Sets the value from successful execution and executes callback if available. Notifies any + * thread waiting for completion. * - * @param value - * value of the evaluated task + * @param value value of the evaluated task */ void setValue(T value) { this.value = value; @@ -106,11 +107,10 @@ void setValue(T value) { } /** - * Sets the exception from failed execution and executes callback if available. Notifies any thread waiting for - * completion. + * Sets the exception from failed execution and executes callback if available. Notifies any + * thread waiting for completion. * - * @param exception - * exception of the failed task + * @param exception exception of the failed task */ void setException(Exception exception) { this.exception = exception; diff --git a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java index 769cd66c4f90..75aebc0dfb91 100644 --- a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java +++ b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java @@ -26,9 +26,7 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { diff --git a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java index d240f3c2eca1..4d97d60e5d08 100644 --- a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java +++ b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java @@ -23,30 +23,18 @@ package com.iluwatar.async.method.invocation; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Matchers; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; +import static org.mockito.internal.verification.VerificationModeFactory.times; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; - -import static java.time.Duration.ofMillis; -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.assertSame; -import static org.junit.jupiter.api.Assertions.assertTimeout; -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.timeout; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; -import static org.mockito.internal.verification.VerificationModeFactory.times; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Matchers; /** * Date: 12/6/15 - 10:49 AM @@ -82,7 +70,8 @@ public void testSuccessfulTaskWithoutCallback() throws Exception { } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, + * AsyncCallback)} */ @Test public void testSuccessfulTaskWithCallback() throws Exception { @@ -104,7 +93,8 @@ public void testSuccessfulTaskWithCallback() throws Exception { verify(task, times(1)).call(); // ... same for the callback, we expect our object - final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + final ArgumentCaptor> optionalCaptor = + ArgumentCaptor.forClass((Class) Optional.class); verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture()); final Optional optionalException = optionalCaptor.getValue(); @@ -117,8 +107,8 @@ public void testSuccessfulTaskWithCallback() throws Exception { } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while - * to execute + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a + * task takes a while to execute */ @Test public void testLongRunningTaskWithoutCallback() throws Exception { @@ -158,8 +148,8 @@ public void testLongRunningTaskWithoutCallback() throws Exception { } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when a task - * takes a while to execute + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, + * AsyncCallback)} when a task takes a while to execute */ @Test public void testLongRunningTaskWithCallback() throws Exception { @@ -191,7 +181,8 @@ public void testLongRunningTaskWithCallback() throws Exception { // Our task should only execute once, but it can take a while ... verify(task, timeout(3000).times(1)).call(); - final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + final ArgumentCaptor> optionalCaptor = + ArgumentCaptor.forClass((Class) Optional.class); verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture()); final Optional optionalException = optionalCaptor.getValue(); @@ -209,8 +200,9 @@ public void testLongRunningTaskWithCallback() throws Exception { } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while - * to execute, while waiting on the result using {@link ThreadAsyncExecutor#endProcess(AsyncResult)} + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a + * task takes a while to execute, while waiting on the result using {@link + * ThreadAsyncExecutor#endProcess(AsyncResult)} */ @Test public void testEndProcess() throws Exception { @@ -247,7 +239,8 @@ public void testEndProcess() throws Exception { } /** - * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when the callable is 'null' + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when + * the callable is 'null' */ @Test public void testNullTask() throws Exception { @@ -273,8 +266,8 @@ public void testNullTask() throws Exception { } /** - * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when the - * callable is 'null', but the asynchronous callback is provided + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, + * AsyncCallback)} when the callable is 'null', but the asynchronous callback is provided */ @Test public void testNullTaskWithCallback() throws Exception { @@ -288,7 +281,8 @@ public void testNullTaskWithCallback() throws Exception { asyncResult.await(); // Prevent timing issues, and wait until the result is available assertTrue(asyncResult.isCompleted()); - final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + final ArgumentCaptor> optionalCaptor = + ArgumentCaptor.forClass((Class) Optional.class); verify(callback, times(1)).onComplete(Matchers.isNull(), optionalCaptor.capture()); final Optional optionalException = optionalCaptor.getValue(); @@ -312,8 +306,8 @@ public void testNullTaskWithCallback() throws Exception { } /** - * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when both - * the callable and the asynchronous callback are 'null' + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, + * AsyncCallback)} when both the callable and the asynchronous callback are 'null' */ @Test public void testNullTaskWithNullCallback() throws Exception { diff --git a/balking/src/main/java/com/iluwatar/balking/App.java b/balking/src/main/java/com/iluwatar/balking/App.java index bb3fb085c077..3e64a299032b 100644 --- a/balking/src/main/java/com/iluwatar/balking/App.java +++ b/balking/src/main/java/com/iluwatar/balking/App.java @@ -23,23 +23,22 @@ package com.iluwatar.balking; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * In Balking Design Pattern if an object’s method is invoked when it is in an inappropriate state, - * then the method will return without doing anything. Objects that use this pattern are generally only in a - * state that is prone to balking temporarily but for an unknown amount of time + * then the method will return without doing anything. Objects that use this pattern are generally + * only in a state that is prone to balking temporarily but for an unknown amount of time * - * In this example implementation WashingMachine is an object that has two states - * in which it can be: ENABLED and WASHING. If the machine is ENABLED - * the state is changed into WASHING that any other thread can't invoke this action on this and then do the job. - * On the other hand if it have been already washing and any other thread execute wash() - * it can't do that once again and returns doing nothing. + *

In this example implementation WashingMachine is an object that has two states in which it + * can be: ENABLED and WASHING. If the machine is ENABLED the state is changed into WASHING that any + * other thread can't invoke this action on this and then do the job. On the other hand if it have + * been already washing and any other thread execute wash() it can't do that once again and returns + * doing nothing. */ public class App { @@ -47,6 +46,8 @@ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** + * Entry Point. + * * @param args the command line arguments - not used */ public static void main(String... args) { diff --git a/balking/src/main/java/com/iluwatar/balking/WashingMachine.java b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java index 044b1b6e9f36..c47c96c3a091 100644 --- a/balking/src/main/java/com/iluwatar/balking/WashingMachine.java +++ b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java @@ -23,13 +23,12 @@ package com.iluwatar.balking; +import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.TimeUnit; - /** - * Washing machine class + * Washing machine class. */ public class WashingMachine { @@ -38,7 +37,7 @@ public class WashingMachine { private WashingMachineState washingMachineState; /** - * Creates a new instance of WashingMachine + * Creates a new instance of WashingMachine. */ public WashingMachine() { this((interval, timeUnit, task) -> { @@ -52,8 +51,8 @@ public WashingMachine() { } /** - * Creates a new instance of WashingMachine using provided delayProvider. This constructor is used only for - * unit testing purposes. + * Creates a new instance of WashingMachine using provided delayProvider. This constructor is used + * only for unit testing purposes. */ public WashingMachine(DelayProvider delayProvider) { this.delayProvider = delayProvider; @@ -65,17 +64,17 @@ public WashingMachineState getWashingMachineState() { } /** - * Method responsible for washing - * if the object is in appropriate state + * Method responsible for washing if the object is in appropriate state. */ public void wash() { synchronized (this) { - LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), getWashingMachineState()); - if (washingMachineState == WashingMachineState.WASHING) { + WashingMachineState machineState = getWashingMachineState(); + LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState); + if (this.washingMachineState == WashingMachineState.WASHING) { LOGGER.error("ERROR: Cannot wash if the machine has been already washing!"); return; } - washingMachineState = WashingMachineState.WASHING; + this.washingMachineState = WashingMachineState.WASHING; } LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); @@ -83,8 +82,7 @@ public void wash() { } /** - * Method responsible of ending the washing - * by changing machine state + * Method responsible of ending the washing by changing machine state. */ public synchronized void endOfWashing() { washingMachineState = WashingMachineState.ENABLED; diff --git a/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java b/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java index 0799d3fd8edb..664a4c0c9941 100644 --- a/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java +++ b/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java @@ -24,10 +24,9 @@ package com.iluwatar.balking; /** - * WashingMachineState enum describes in which state machine is, - * it can be enabled and ready to work as well as during washing + * WashingMachineState enum describes in which state machine is, it can be enabled and ready to work + * as well as during washing. */ - public enum WashingMachineState { ENABLED, WASHING } diff --git a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java index 8348f9256dee..7c6bd73ecae6 100644 --- a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java +++ b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java @@ -23,11 +23,10 @@ package com.iluwatar.balking; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * Tests for {@link WashingMachine} diff --git a/bridge/src/main/java/com/iluwatar/bridge/App.java b/bridge/src/main/java/com/iluwatar/bridge/App.java index 195f463cf40d..74104257eefa 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/App.java +++ b/bridge/src/main/java/com/iluwatar/bridge/App.java @@ -27,25 +27,25 @@ import org.slf4j.LoggerFactory; /** - * - * Composition over inheritance. The Bridge pattern can also be thought of as two layers of abstraction. - * With Bridge, you can decouple an abstraction from its implementation so that the two can vary independently. - *

- * In Bridge pattern both abstraction ({@link Weapon}) and implementation ( - * {@link Enchantment}) have their own class hierarchies. The interface of the implementations - * can be changed without affecting the clients. - *

- * In this example we have two class hierarchies. One of weapons and another one of enchantments. We can easily - * combine any weapon with any enchantment using composition instead of creating deep class hierarchy. - * + * Composition over inheritance. The Bridge pattern can also be thought of as two layers of + * abstraction. With Bridge, you can decouple an abstraction from its implementation so that the two + * can vary independently. + * + *

In Bridge pattern both abstraction ({@link Weapon}) and implementation ( {@link Enchantment}) + * have their own class hierarchies. The interface of the implementations can be changed without + * affecting the clients. + * + *

In this example we have two class hierarchies. One of weapons and another one of + * enchantments. We can easily combine any weapon with any enchantment using composition instead of + * creating deep class hierarchy. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java b/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java index 22acac8f9a1d..8388fe91eb2b 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java @@ -24,9 +24,7 @@ package com.iluwatar.bridge; /** - * - * Enchantment - * + * Enchantment. */ public interface Enchantment { diff --git a/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java b/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java index 14abe4c635cd..772456b88881 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * FlyingEnchantment - * + * FlyingEnchantment. */ public class FlyingEnchantment implements Enchantment { diff --git a/bridge/src/main/java/com/iluwatar/bridge/Hammer.java b/bridge/src/main/java/com/iluwatar/bridge/Hammer.java index 47f60613d239..ffab542cb169 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Hammer.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Hammer.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * Hammer - * + * Hammer. */ public class Hammer implements Weapon { diff --git a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java index 3655c7e97722..ede98d2cbd08 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * SoulEatingEnchantment - * + * SoulEatingEnchantment. */ public class SoulEatingEnchantment implements Enchantment { diff --git a/bridge/src/main/java/com/iluwatar/bridge/Sword.java b/bridge/src/main/java/com/iluwatar/bridge/Sword.java index ab6f4ab7feff..71f87a55dcd8 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Sword.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Sword.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * Sword - * + * Sword. */ public class Sword implements Weapon { diff --git a/bridge/src/main/java/com/iluwatar/bridge/Weapon.java b/bridge/src/main/java/com/iluwatar/bridge/Weapon.java index b264dddca794..76272332e76d 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Weapon.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Weapon.java @@ -24,9 +24,7 @@ package com.iluwatar.bridge; /** - * - * Weapon - * + * Weapon. */ public interface Weapon { diff --git a/builder/src/main/java/com/iluwatar/builder/App.java b/builder/src/main/java/com/iluwatar/builder/App.java index f57e4d42f26f..ae29ee3678d9 100644 --- a/builder/src/main/java/com/iluwatar/builder/App.java +++ b/builder/src/main/java/com/iluwatar/builder/App.java @@ -28,36 +28,33 @@ import org.slf4j.LoggerFactory; /** - * * The intention of the Builder pattern is to find a solution to the telescoping constructor * anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object * constructor parameter combination leads to an exponential list of constructors. Instead of using * numerous constructors, the builder pattern uses another object, a builder, that receives each * initialization parameter step by step and then returns the resulting constructed object at once. - *

- * The Builder pattern has another benefit. It can be used for objects that contain flat data (html - * code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. This - * type of data cannot be edited step by step and must be edited at once. The best way to construct - * such an object is to use a builder class. - *

- * In this example we have the Builder pattern variation as described by Joshua Bloch in Effective - * Java 2nd Edition. - *

- * We want to build {@link Hero} objects, but its construction is complex because of the many - * parameters needed. To aid the user we introduce {@link Builder} class. {@link Hero.Builder} - * takes the minimum parameters to build {@link Hero} object in its constructor. After that - * additional configuration for the {@link Hero} object can be done using the fluent - * {@link Builder} interface. When configuration is ready the build method is called to receive - * the final {@link Hero} object. - * + * + *

The Builder pattern has another benefit. It can be used for objects that contain flat data + * (html code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. + * This type of data cannot be edited step by step and must be edited at once. The best way to + * construct such an object is to use a builder class. + * + *

In this example we have the Builder pattern variation as described by Joshua Bloch in + * Effective Java 2nd Edition. + * + *

We want to build {@link Hero} objects, but its construction is complex because of the many + * parameters needed. To aid the user we introduce {@link Builder} class. {@link Hero.Builder} takes + * the minimum parameters to build {@link Hero} object in its constructor. After that additional + * configuration for the {@link Hero} object can be done using the fluent {@link Builder} interface. + * When configuration is ready the build method is called to receive the final {@link Hero} object. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/builder/src/main/java/com/iluwatar/builder/Armor.java b/builder/src/main/java/com/iluwatar/builder/Armor.java index 8cf57a361a9e..2ab9bf831899 100644 --- a/builder/src/main/java/com/iluwatar/builder/Armor.java +++ b/builder/src/main/java/com/iluwatar/builder/Armor.java @@ -24,9 +24,7 @@ package com.iluwatar.builder; /** - * - * Armor enumeration - * + * Armor enumeration. */ public enum Armor { diff --git a/builder/src/main/java/com/iluwatar/builder/HairColor.java b/builder/src/main/java/com/iluwatar/builder/HairColor.java index f94de35564a4..1beccff5e5b8 100644 --- a/builder/src/main/java/com/iluwatar/builder/HairColor.java +++ b/builder/src/main/java/com/iluwatar/builder/HairColor.java @@ -24,9 +24,7 @@ package com.iluwatar.builder; /** - * - * HairColor enumeration - * + * HairColor enumeration. */ public enum HairColor { diff --git a/builder/src/main/java/com/iluwatar/builder/HairType.java b/builder/src/main/java/com/iluwatar/builder/HairType.java index 6eece1e373dd..3d16eb4d741f 100644 --- a/builder/src/main/java/com/iluwatar/builder/HairType.java +++ b/builder/src/main/java/com/iluwatar/builder/HairType.java @@ -24,9 +24,7 @@ package com.iluwatar.builder; /** - * - * HairType enumeration - * + * HairType enumeration. */ public enum HairType { diff --git a/builder/src/main/java/com/iluwatar/builder/Hero.java b/builder/src/main/java/com/iluwatar/builder/Hero.java index a8f285b66eda..b33ce10078fe 100644 --- a/builder/src/main/java/com/iluwatar/builder/Hero.java +++ b/builder/src/main/java/com/iluwatar/builder/Hero.java @@ -24,9 +24,7 @@ package com.iluwatar.builder; /** - * * Hero, the class with many parameters. - * */ public final class Hero { @@ -75,9 +73,9 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("This is a ") - .append(profession) - .append(" named ") - .append(name); + .append(profession) + .append(" named ") + .append(name); if (hairColor != null || hairType != null) { sb.append(" with "); if (hairColor != null) { @@ -99,9 +97,7 @@ public String toString() { } /** - * * The builder class. - * */ public static class Builder { @@ -113,7 +109,7 @@ public static class Builder { private Weapon weapon; /** - * Constructor + * Constructor. */ public Builder(Profession profession, String name) { if (profession == null || name == null) { diff --git a/builder/src/main/java/com/iluwatar/builder/Profession.java b/builder/src/main/java/com/iluwatar/builder/Profession.java index 1e22a1c67d85..23b1ac220c92 100644 --- a/builder/src/main/java/com/iluwatar/builder/Profession.java +++ b/builder/src/main/java/com/iluwatar/builder/Profession.java @@ -24,9 +24,7 @@ package com.iluwatar.builder; /** - * - * Profession enumeration - * + * Profession enumeration. */ public enum Profession { diff --git a/builder/src/main/java/com/iluwatar/builder/Weapon.java b/builder/src/main/java/com/iluwatar/builder/Weapon.java index 51ddeafbce29..4ca78b95ff20 100644 --- a/builder/src/main/java/com/iluwatar/builder/Weapon.java +++ b/builder/src/main/java/com/iluwatar/builder/Weapon.java @@ -24,9 +24,7 @@ package com.iluwatar.builder; /** - * - * Weapon enumeration - * + * Weapon enumeration. */ public enum Weapon { From efc17fcc70781c13b1c3cc938de73b6514721cb7 Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 00:53:12 +0530 Subject: [PATCH 03/32] Resolves checkstyle errors for business-delegate, bytecode, caching (#1059) * Reduces checkstyle errors in business-delegate * Reduces checkstyle errors in bytecode * Reduces checkstyle errors in caching --- .../com/iluwatar/business/delegate/App.java | 4 +- .../business/delegate/BusinessDelegate.java | 2 +- .../business/delegate/BusinessLookup.java | 2 + .../business/delegate/BusinessService.java | 4 +- .../iluwatar/business/delegate/Client.java | 4 +- .../business/delegate/EjbService.java | 4 +- .../business/delegate/JmsService.java | 4 +- .../business/delegate/ServiceType.java | 4 +- .../main/java/com/iluwatar/bytecode/App.java | 54 ++++++++--------- .../com/iluwatar/bytecode/Instruction.java | 5 +- .../com/iluwatar/bytecode/VirtualMachine.java | 7 ++- .../java/com/iluwatar/bytecode/Wizard.java | 3 +- .../util/InstructionConverterUtil.java | 7 ++- .../main/java/com/iluwatar/caching/App.java | 22 ++++--- .../java/com/iluwatar/caching/AppManager.java | 13 ++--- .../java/com/iluwatar/caching/CacheStore.java | 29 +++++----- .../com/iluwatar/caching/CachingPolicy.java | 2 - .../java/com/iluwatar/caching/DbManager.java | 58 ++++++++++--------- .../java/com/iluwatar/caching/LruCache.java | 19 +++--- .../com/iluwatar/caching/UserAccount.java | 2 +- .../caching/constants/CachingConstants.java | 4 +- 21 files changed, 119 insertions(+), 134 deletions(-) diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java index 68e382c0f051..fcb1acd1b477 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java @@ -28,11 +28,11 @@ * tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate * encapsulates knowledge about how to locate, connect to, and interact with the business objects * that make up the application. - * + * *

Some of the services the Business Delegate uses are instantiated directly, and some can be * retrieved through service lookups. The Business Delegate itself may contain business logic too * potentially tying together multiple service calls, exception handling, retrying etc. - * + * *

In this example the client ({@link Client}) utilizes a business delegate ( * {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate * service and makes the service call. diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java index cf2b251295ad..c39a2ad39372 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java @@ -24,7 +24,7 @@ package com.iluwatar.business.delegate; /** - * BusinessDelegate separates the presentation and business tiers + * BusinessDelegate separates the presentation and business tiers. */ public class BusinessDelegate { diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java index e7d8400d3249..489caa23c407 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java @@ -33,6 +33,8 @@ public class BusinessLookup { private JmsService jmsService; /** + * Gets service instance based on service type. + * * @param serviceType Type of service instance to be returned. * @return Service instance. */ diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java index 6e08aca1f939..3094d3f6e95f 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java @@ -24,9 +24,7 @@ package com.iluwatar.business.delegate; /** - * - * Interface for service implementations - * + * Interface for service implementations. */ public interface BusinessService { diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java index c9c8950db3a4..dcf4ce6b29d3 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java @@ -24,9 +24,7 @@ package com.iluwatar.business.delegate; /** - * - * Client utilizes BusinessDelegate to call the business tier - * + * Client utilizes BusinessDelegate to call the business tier. */ public class Client { diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java index aa9457abfada..6f39abb1ae42 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * Service EJB implementation - * + * Service EJB implementation. */ public class EjbService implements BusinessService { diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java index 83abd9762301..2317d783af0f 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * Service JMS implementation - * + * Service JMS implementation. */ public class JmsService implements BusinessService { diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java index a09dde59c661..87fd1562da66 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java @@ -24,9 +24,7 @@ package com.iluwatar.business.delegate; /** - * - * Enumeration for service types - * + * Enumeration for service types. */ public enum ServiceType { diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/App.java b/bytecode/src/main/java/com/iluwatar/bytecode/App.java index 9a5f66d886fe..165043c70691 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/App.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/App.java @@ -24,57 +24,59 @@ package com.iluwatar.bytecode; import com.iluwatar.bytecode.util.InstructionConverterUtil; +import java.util.Stack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * The intention of Bytecode pattern is to give behavior the flexibility of data by encoding it as instructions - * for a virtual machine. - * An instruction set defines the low-level operations that can be performed. A series of instructions is encoded as - * a sequence of bytes. A virtual machine executes these instructions one at a time, - * using a stack for intermediate values. By combining instructions, complex high-level behavior can be defined. - * - * This pattern should be used when there is a need to define high number of behaviours and implementation engine - * is not a good choice because - * It is too lowe level - * Iterating on it takes too long due to slow compile times or other tooling issues. - * It has too much trust. If you want to ensure the behavior being defined can’t break the game, - * you need to sandbox it from the rest of the codebase. + * The intention of Bytecode pattern is to give behavior the flexibility of data by encoding it as + * instructions for a virtual machine. An instruction set defines the low-level operations that can + * be performed. A series of instructions is encoded as a sequence of bytes. A virtual machine + * executes these instructions one at a time, using a stack for intermediate values. By combining + * instructions, complex high-level behavior can be defined. * + *

This pattern should be used when there is a need to define high number of behaviours and + * implementation engine is not a good choice because It is too lowe level Iterating on it takes too + * long due to slow compile times or other tooling issues. It has too much trust. If you want to + * ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of + * the codebase. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Main app method + * Main app method. + * * @param args command line args */ public static void main(String[] args) { - VirtualMachine vm = new VirtualMachine(); Wizard wizard = new Wizard(); wizard.setHealth(45); wizard.setAgility(7); wizard.setWisdom(11); + + VirtualMachine vm = new VirtualMachine(); vm.getWizards()[0] = wizard; interpretInstruction("LITERAL 0", vm); - interpretInstruction( "LITERAL 0", vm); - interpretInstruction( "GET_HEALTH", vm); - interpretInstruction( "LITERAL 0", vm); - interpretInstruction( "GET_AGILITY", vm); - interpretInstruction( "LITERAL 0", vm); - interpretInstruction( "GET_WISDOM ", vm); - interpretInstruction( "ADD", vm); - interpretInstruction( "LITERAL 2", vm); - interpretInstruction( "DIVIDE", vm); - interpretInstruction( "ADD", vm); - interpretInstruction( "SET_HEALTH", vm); + interpretInstruction("LITERAL 0", vm); + interpretInstruction("GET_HEALTH", vm); + interpretInstruction("LITERAL 0", vm); + interpretInstruction("GET_AGILITY", vm); + interpretInstruction("LITERAL 0", vm); + interpretInstruction("GET_WISDOM ", vm); + interpretInstruction("ADD", vm); + interpretInstruction("LITERAL 2", vm); + interpretInstruction("DIVIDE", vm); + interpretInstruction("ADD", vm); + interpretInstruction("SET_HEALTH", vm); } private static void interpretInstruction(String instruction, VirtualMachine vm) { InstructionConverterUtil converter = new InstructionConverterUtil(); vm.execute(converter.convertToByteCode(instruction)); - LOGGER.info(instruction + String.format("%" + (12 - instruction.length()) + "s", "" ) + vm.getStack()); + Stack stack = vm.getStack(); + LOGGER.info(instruction + String.format("%" + (12 - instruction.length()) + "s", "") + stack); } } diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java b/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java index 99b632ed853e..7684c778dc55 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java @@ -24,7 +24,7 @@ package com.iluwatar.bytecode; /** - * Representation of instructions understandable by virtual machine + * Representation of instructions understandable by virtual machine. */ public enum Instruction { @@ -51,7 +51,8 @@ public int getIntValue() { } /** - * Converts integer value to Instruction + * Converts integer value to Instruction. + * * @param value value of instruction * @return representation of the instruction */ diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java b/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java index c6b120963284..111c27e7343a 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java @@ -26,7 +26,7 @@ import java.util.Stack; /** - * Implementation of virtual machine + * Implementation of virtual machine. */ public class VirtualMachine { @@ -35,7 +35,7 @@ public class VirtualMachine { private Wizard[] wizards = new Wizard[2]; /** - * Constructor + * Constructor. */ public VirtualMachine() { for (int i = 0; i < wizards.length; i++) { @@ -44,7 +44,8 @@ public VirtualMachine() { } /** - * Executes provided bytecode + * Executes provided bytecode. + * * @param bytecode to execute */ public void execute(int[] bytecode) { diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java b/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java index 434a1bddd1e8..5153969d9145 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java @@ -27,7 +27,8 @@ import org.slf4j.LoggerFactory; /** - * This class represent game objects which properties can be changed by instructions interpreted by virtual machine + * This class represent game objects which properties can be changed by instructions interpreted by + * virtual machine. */ public class Wizard { private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class); diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java b/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java index bdc0782dd593..1d3002cb104c 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java @@ -26,11 +26,11 @@ import com.iluwatar.bytecode.Instruction; /** - * Utility class used for instruction validation and conversion + * Utility class used for instruction validation and conversion. */ public class InstructionConverterUtil { /** - * Converts instructions represented as String + * Converts instructions represented as String. * * @param instructions to convert * @return array of int representing bytecode @@ -48,7 +48,8 @@ public static int[] convertToByteCode(String instructions) { } else if (isValidInt(splitedInstructions[i])) { bytecode[i] = Integer.valueOf(splitedInstructions[i]); } else { - throw new IllegalArgumentException("Invalid instruction or number: " + splitedInstructions[i]); + String errorMessage = "Invalid instruction or number: " + splitedInstructions[i]; + throw new IllegalArgumentException(errorMessage); } } diff --git a/caching/src/main/java/com/iluwatar/caching/App.java b/caching/src/main/java/com/iluwatar/caching/App.java index 4ef12b7de784..e1e4e67ca08c 100644 --- a/caching/src/main/java/com/iluwatar/caching/App.java +++ b/caching/src/main/java/com/iluwatar/caching/App.java @@ -27,7 +27,6 @@ import org.slf4j.LoggerFactory; /** - * * The Caching pattern describes how to avoid expensive re-acquisition of resources by not releasing * the resources immediately after their use. The resources retain their identity, are kept in some * fast-access storage, and are re-used to avoid having to acquire them again. There are four main @@ -43,8 +42,8 @@ * should be written back to the backing store (i.e. Database) and help keep both data sources * synchronized/up-to-date. This pattern can improve performance and also helps to maintain * consistency between data held in the cache and the data in the underlying data store. - *

- * In this example, the user account ({@link UserAccount}) entity is used as the underlying + * + *

In this example, the user account ({@link UserAccount}) entity is used as the underlying * application data. The cache itself is implemented as an internal (Java) data structure. It adopts * a Least-Recently-Used (LRU) strategy for evicting data from itself when its full. The four * strategies are individually tested. The testing of the cache is restricted towards saving and @@ -60,7 +59,6 @@ * @see CacheStore * @see LruCache * @see CachingPolicy - * */ public class App { @@ -68,15 +66,15 @@ public class App { /** - * Program entry point + * Program entry point. * * @param args command line args */ public static void main(String[] args) { AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests - // and the App class to avoid Maven compilation errors. Set flag to - // true to run the tests with MongoDB (provided that MongoDB is - // installed and socket connection is open). + // and the App class to avoid Maven compilation errors. Set flag to + // true to run the tests with MongoDB (provided that MongoDB is + // installed and socket connection is open). AppManager.initCacheCapacity(3); App app = new App(); app.useReadAndWriteThroughStrategy(); @@ -86,7 +84,7 @@ public static void main(String[] args) { } /** - * Read-through and write-through + * Read-through and write-through. */ public void useReadAndWriteThroughStrategy() { LOGGER.info("# CachingPolicy.THROUGH"); @@ -101,7 +99,7 @@ public void useReadAndWriteThroughStrategy() { } /** - * Read-through and write-around + * Read-through and write-around. */ public void useReadThroughAndWriteAroundStrategy() { LOGGER.info("# CachingPolicy.AROUND"); @@ -123,7 +121,7 @@ public void useReadThroughAndWriteAroundStrategy() { } /** - * Read-through and write-behind + * Read-through and write-behind. */ public void useReadThroughAndWriteBehindStrategy() { LOGGER.info("# CachingPolicy.BEHIND"); @@ -147,7 +145,7 @@ public void useReadThroughAndWriteBehindStrategy() { } /** - * Cache-Aside + * Cache-Aside. */ public void useCacheAsideStategy() { LOGGER.info("# CachingPolicy.ASIDE"); diff --git a/caching/src/main/java/com/iluwatar/caching/AppManager.java b/caching/src/main/java/com/iluwatar/caching/AppManager.java index 6939c6b80b79..ec7f0df6971f 100644 --- a/caching/src/main/java/com/iluwatar/caching/AppManager.java +++ b/caching/src/main/java/com/iluwatar/caching/AppManager.java @@ -26,13 +26,11 @@ import java.text.ParseException; /** - * * AppManager helps to bridge the gap in communication between the main class and the application's * back-end. DB connection is initialized through this class. The chosen caching strategy/policy is * also initialized here. Before the cache can be used, the size of the cache has to be set. * Depending on the chosen caching policy, AppManager will call the appropriate function in the * CacheStore class. - * */ public final class AppManager { @@ -42,7 +40,6 @@ private AppManager() { } /** - * * Developer/Tester is able to choose whether the application should use MongoDB as its underlying * data storage or a simple Java data structure to (temporarily) store the data/objects during * runtime. @@ -60,7 +57,7 @@ public static void initDb(boolean useMongoDb) { } /** - * Initialize caching policy + * Initialize caching policy. */ public static void initCachingPolicy(CachingPolicy policy) { cachingPolicy = policy; @@ -75,7 +72,7 @@ public static void initCacheCapacity(int capacity) { } /** - * Find user account + * Find user account. */ public static UserAccount find(String userId) { if (cachingPolicy == CachingPolicy.THROUGH || cachingPolicy == CachingPolicy.AROUND) { @@ -89,7 +86,7 @@ public static UserAccount find(String userId) { } /** - * Save user account + * Save user account. */ public static void save(UserAccount userAccount) { if (cachingPolicy == CachingPolicy.THROUGH) { @@ -108,7 +105,7 @@ public static String printCacheContent() { } /** - * Cache-Aside save user account helper + * Cache-Aside save user account helper. */ private static void saveAside(UserAccount userAccount) { DbManager.updateDb(userAccount); @@ -116,7 +113,7 @@ private static void saveAside(UserAccount userAccount) { } /** - * Cache-Aside find user account helper + * Cache-Aside find user account helper. */ private static UserAccount findAside(String userId) { UserAccount userAccount = CacheStore.get(userId); diff --git a/caching/src/main/java/com/iluwatar/caching/CacheStore.java b/caching/src/main/java/com/iluwatar/caching/CacheStore.java index e221f16e7878..17a733188c64 100644 --- a/caching/src/main/java/com/iluwatar/caching/CacheStore.java +++ b/caching/src/main/java/com/iluwatar/caching/CacheStore.java @@ -23,15 +23,12 @@ package com.iluwatar.caching; +import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; - /** - * * The caching strategies are implemented in this class. - * */ public class CacheStore { @@ -43,7 +40,7 @@ private CacheStore() { } /** - * Init cache capacity + * Init cache capacity. */ public static void initCapacity(int capacity) { if (cache == null) { @@ -54,7 +51,7 @@ public static void initCapacity(int capacity) { } /** - * Get user account using read-through cache + * Get user account using read-through cache. */ public static UserAccount readThrough(String userId) { if (cache.contains(userId)) { @@ -68,7 +65,7 @@ public static UserAccount readThrough(String userId) { } /** - * Get user account using write-through cache + * Get user account using write-through cache. */ public static void writeThrough(UserAccount userAccount) { if (cache.contains(userAccount.getUserId())) { @@ -80,20 +77,20 @@ public static void writeThrough(UserAccount userAccount) { } /** - * Get user account using write-around cache + * Get user account using write-around cache. */ public static void writeAround(UserAccount userAccount) { if (cache.contains(userAccount.getUserId())) { DbManager.updateDb(userAccount); cache.invalidate(userAccount.getUserId()); // Cache data has been updated -- remove older - // version from cache. + // version from cache. } else { DbManager.writeToDb(userAccount); } } /** - * Get user account using read-through cache with write-back policy + * Get user account using read-through cache with write-back policy. */ public static UserAccount readThroughWithWriteBackPolicy(String userId) { if (cache.contains(userId)) { @@ -112,7 +109,7 @@ public static UserAccount readThroughWithWriteBackPolicy(String userId) { } /** - * Set user account + * Set user account. */ public static void writeBehind(UserAccount userAccount) { if (cache.isFull() && !cache.contains(userAccount.getUserId())) { @@ -124,7 +121,7 @@ public static void writeBehind(UserAccount userAccount) { } /** - * Clears cache + * Clears cache. */ public static void clearCache() { if (cache != null) { @@ -147,7 +144,7 @@ public static void flushCache() { } /** - * Print user accounts + * Print user accounts. */ public static String print() { List listOfUserAccounts = cache.getCacheDataInListForm(); @@ -161,21 +158,21 @@ public static String print() { } /** - * Delegate to backing cache store + * Delegate to backing cache store. */ public static UserAccount get(String userId) { return cache.get(userId); } /** - * Delegate to backing cache store + * Delegate to backing cache store. */ public static void set(String userId, UserAccount userAccount) { cache.set(userId, userAccount); } /** - * Delegate to backing cache store + * Delegate to backing cache store. */ public static void invalidate(String userId) { cache.invalidate(userId); diff --git a/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java b/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java index 23be7d7e2b2d..6bc6dbd77d3a 100644 --- a/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java +++ b/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java @@ -24,9 +24,7 @@ package com.iluwatar.caching; /** - * * Enum class containing the four caching strategies implemented in the pattern. - * */ public enum CachingPolicy { THROUGH("through"), AROUND("around"), BEHIND("behind"), ASIDE("aside"); diff --git a/caching/src/main/java/com/iluwatar/caching/DbManager.java b/caching/src/main/java/com/iluwatar/caching/DbManager.java index 01b727fa540e..dbb885ee2277 100644 --- a/caching/src/main/java/com/iluwatar/caching/DbManager.java +++ b/caching/src/main/java/com/iluwatar/caching/DbManager.java @@ -23,28 +23,24 @@ package com.iluwatar.caching; -import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; - -import org.bson.Document; - import com.iluwatar.caching.constants.CachingConstants; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; +import org.bson.Document; /** + *

DBManager handles the communication with the underlying data store i.e. Database. It contains + * the implemented methods for querying, inserting, and updating data. MongoDB was used as the + * database for the application.

* - *

DBManager handles the communication with the underlying data store i.e. Database. It contains the - * implemented methods for querying, inserting, and updating data. MongoDB was used as the database - * for the application.

- * - *

Developer/Tester is able to choose whether the application should use MongoDB as its underlying - * data storage (connect()) or a simple Java data structure to (temporarily) store the data/objects - * during runtime (createVirtualDB()).

- * + *

Developer/Tester is able to choose whether the application should use MongoDB as its + * underlying data storage (connect()) or a simple Java data structure to (temporarily) store the + * data/objects during runtime (createVirtualDB()).

*/ public final class DbManager { @@ -58,7 +54,7 @@ private DbManager() { } /** - * Create DB + * Create DB. */ public static void createVirtualDb() { useMongoDB = false; @@ -66,7 +62,7 @@ public static void createVirtualDb() { } /** - * Connect to DB + * Connect to DB. */ public static void connect() throws ParseException { useMongoDB = true; @@ -75,7 +71,7 @@ public static void connect() throws ParseException { } /** - * Read user account from DB + * Read user account from DB. */ public static UserAccount readFromDb(String userId) { if (!useMongoDB) { @@ -91,17 +87,20 @@ public static UserAccount readFromDb(String userId) { e.printStackTrace(); } } - FindIterable iterable = - db.getCollection(CachingConstants.USER_ACCOUNT).find(new Document(CachingConstants.USER_ID, userId)); + FindIterable iterable = db + .getCollection(CachingConstants.USER_ACCOUNT) + .find(new Document(CachingConstants.USER_ID, userId)); if (iterable == null) { return null; } Document doc = iterable.first(); - return new UserAccount(userId, doc.getString(CachingConstants.USER_NAME), doc.getString(CachingConstants.ADD_INFO)); + String userName = doc.getString(CachingConstants.USER_NAME); + String appInfo = doc.getString(CachingConstants.ADD_INFO); + return new UserAccount(userId, userName, appInfo); } /** - * Write user account to DB + * Write user account to DB. */ public static void writeToDb(UserAccount userAccount) { if (!useMongoDB) { @@ -116,12 +115,14 @@ public static void writeToDb(UserAccount userAccount) { } } db.getCollection(CachingConstants.USER_ACCOUNT).insertOne( - new Document(CachingConstants.USER_ID ,userAccount.getUserId()).append(CachingConstants.USER_NAME, - userAccount.getUserName()).append(CachingConstants.ADD_INFO, userAccount.getAdditionalInfo())); + new Document(CachingConstants.USER_ID, userAccount.getUserId()) + .append(CachingConstants.USER_NAME, userAccount.getUserName()) + .append(CachingConstants.ADD_INFO, userAccount.getAdditionalInfo()) + ); } /** - * Update DB + * Update DB. */ public static void updateDb(UserAccount userAccount) { if (!useMongoDB) { @@ -142,7 +143,6 @@ public static void updateDb(UserAccount userAccount) { } /** - * * Insert data into DB if it does not exist. Else, update it. */ public static void upsertDb(UserAccount userAccount) { @@ -161,8 +161,10 @@ public static void upsertDb(UserAccount userAccount) { new Document(CachingConstants.USER_ID, userAccount.getUserId()), new Document("$set", new Document(CachingConstants.USER_ID, userAccount.getUserId()) - .append(CachingConstants.USER_NAME, userAccount.getUserName()).append(CachingConstants.ADD_INFO, - userAccount.getAdditionalInfo())), - new UpdateOptions().upsert(true)); + .append(CachingConstants.USER_NAME, userAccount.getUserName()) + .append(CachingConstants.ADD_INFO, userAccount.getAdditionalInfo()) + ), + new UpdateOptions().upsert(true) + ); } } diff --git a/caching/src/main/java/com/iluwatar/caching/LruCache.java b/caching/src/main/java/com/iluwatar/caching/LruCache.java index 0f2e53823a0a..32bb3838eb39 100644 --- a/caching/src/main/java/com/iluwatar/caching/LruCache.java +++ b/caching/src/main/java/com/iluwatar/caching/LruCache.java @@ -23,22 +23,19 @@ package com.iluwatar.caching; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * * Data structure/implementation of the application's cache. The data structure consists of a hash * table attached with a doubly linked-list. The linked-list helps in capturing and maintaining the * LRU data in the cache. When a data is queried (from the cache), added (to the cache), or updated, * the data is moved to the front of the list to depict itself as the most-recently-used data. The * LRU data is always at the end of the list. - * */ public class LruCache { @@ -66,7 +63,7 @@ public LruCache(int capacity) { } /** - * Get user account + * Get user account. */ public UserAccount get(String userId) { if (cache.containsKey(userId)) { @@ -110,7 +107,7 @@ public void setHead(Node node) { } /** - * Set user account + * Set user account. */ public void set(String userId, UserAccount userAccount) { if (cache.containsKey(userId)) { @@ -137,7 +134,7 @@ public boolean contains(String userId) { } /** - * Invalidate cache for user + * Invalidate cache for user. */ public void invalidate(String userId) { Node toBeRemoved = cache.remove(userId); @@ -156,7 +153,7 @@ public UserAccount getLruData() { } /** - * Clear cache + * Clear cache. */ public void clear() { head = null; @@ -178,12 +175,12 @@ public List getCacheDataInListForm() { } /** - * Set cache capacity + * Set cache capacity. */ public void setCapacity(int newCapacity) { if (capacity > newCapacity) { clear(); // Behavior can be modified to accommodate for decrease in cache size. For now, we'll - // just clear the cache. + // just clear the cache. } else { this.capacity = newCapacity; } diff --git a/caching/src/main/java/com/iluwatar/caching/UserAccount.java b/caching/src/main/java/com/iluwatar/caching/UserAccount.java index fc6b8cb4c5eb..4c58cfb08a59 100644 --- a/caching/src/main/java/com/iluwatar/caching/UserAccount.java +++ b/caching/src/main/java/com/iluwatar/caching/UserAccount.java @@ -32,7 +32,7 @@ public class UserAccount { private String additionalInfo; /** - * Constructor + * Constructor. */ public UserAccount(String userId, String userName, String additionalInfo) { this.userId = userId; diff --git a/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java b/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java index 7e53f61f0cf6..86d2bd2a7a8f 100644 --- a/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java +++ b/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java @@ -24,9 +24,7 @@ package com.iluwatar.caching.constants; /** - * - * Constant class for defining constants - * + * Constant class for defining constants. */ public class CachingConstants { From 31f27a720b3ebc420783bd2ac885a74f6a90c754 Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 00:57:14 +0530 Subject: [PATCH 04/32] Resolves checkstyle errors for callback, chain, circuit-breaker (#1060) * Reduces checkstyle errors in callback * Reduces checkstyle errors in chain * Reduces checkstyle errors in circuit-breaker --- .../main/java/com/iluwatar/callback/App.java | 14 ++--- .../java/com/iluwatar/callback/Callback.java | 4 +- .../com/iluwatar/callback/LambdasApp.java | 15 +++-- .../com/iluwatar/callback/SimpleTask.java | 10 ++-- .../main/java/com/iluwatar/callback/Task.java | 6 +- .../src/main/java/com/iluwatar/chain/App.java | 16 +++--- .../java/com/iluwatar/chain/OrcCommander.java | 4 +- .../main/java/com/iluwatar/chain/OrcKing.java | 2 - .../java/com/iluwatar/chain/OrcOfficer.java | 4 +- .../java/com/iluwatar/chain/OrcSoldier.java | 4 +- .../main/java/com/iluwatar/chain/Request.java | 16 +++--- .../com/iluwatar/chain/RequestHandler.java | 6 +- .../java/com/iluwatar/chain/RequestType.java | 4 +- .../java/com/iluwatar/circuitbreaker/App.java | 57 +++++++++---------- .../circuitbreaker/CircuitBreaker.java | 43 ++++++++------ .../circuitbreaker/DelayedService.java | 14 +++-- .../circuitbreaker/MonitoringService.java | 12 ++-- .../com/iluwatar/circuitbreaker/State.java | 8 +-- 18 files changed, 114 insertions(+), 125 deletions(-) diff --git a/callback/src/main/java/com/iluwatar/callback/App.java b/callback/src/main/java/com/iluwatar/callback/App.java index 842f01dcdf3d..1b92d98debb4 100644 --- a/callback/src/main/java/com/iluwatar/callback/App.java +++ b/callback/src/main/java/com/iluwatar/callback/App.java @@ -23,16 +23,14 @@ package com.iluwatar.callback; -import org.slf4j.Logger; - import static org.slf4j.LoggerFactory.getLogger; +import org.slf4j.Logger; + /** - * - * Callback pattern is more native for functional languages where functions are - * treated as first-class citizens. Prior to Java 8 callbacks can be simulated - * using simple (alike command) interfaces. - * + * Callback pattern is more native for functional languages where functions are treated as + * first-class citizens. Prior to Java 8 callbacks can be simulated using simple (alike command) + * interfaces. */ public final class App { @@ -42,7 +40,7 @@ private App() { } /** - * Program entry point + * Program entry point. */ public static void main(final String[] args) { Task task = new SimpleTask(); diff --git a/callback/src/main/java/com/iluwatar/callback/Callback.java b/callback/src/main/java/com/iluwatar/callback/Callback.java index 0158dcda0fe6..ad98e27deefa 100644 --- a/callback/src/main/java/com/iluwatar/callback/Callback.java +++ b/callback/src/main/java/com/iluwatar/callback/Callback.java @@ -24,9 +24,7 @@ package com.iluwatar.callback; /** - * - * Callback interface - * + * Callback interface. */ public interface Callback { diff --git a/callback/src/main/java/com/iluwatar/callback/LambdasApp.java b/callback/src/main/java/com/iluwatar/callback/LambdasApp.java index 18715e3b79ca..f87d04969d86 100644 --- a/callback/src/main/java/com/iluwatar/callback/LambdasApp.java +++ b/callback/src/main/java/com/iluwatar/callback/LambdasApp.java @@ -23,24 +23,23 @@ package com.iluwatar.callback; -import org.slf4j.Logger; - import static org.slf4j.LoggerFactory.getLogger; +import org.slf4j.Logger; + /** - * - * This example generates the exact same output as {@link App} however the - * callback has been defined as a Lambdas expression. - * + * This example generates the exact same output as {@link App} however the callback has been defined + * as a Lambdas expression. */ public final class LambdasApp { private static final Logger LOGGER = getLogger(LambdasApp.class); - private LambdasApp() { } + private LambdasApp() { + } /** - * Program entry point + * Program entry point. */ public static void main(final String[] args) { Task task = new SimpleTask(); diff --git a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java index 21162833a72c..f12448d9683c 100644 --- a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java +++ b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java @@ -23,14 +23,12 @@ package com.iluwatar.callback; -import org.slf4j.Logger; - import static org.slf4j.LoggerFactory.getLogger; +import org.slf4j.Logger; + /** - * - * Implementation of task that need to be executed - * + * Implementation of task that need to be executed. */ public final class SimpleTask extends Task { @@ -39,6 +37,6 @@ public final class SimpleTask extends Task { @Override public void execute() { LOGGER.info("Perform some important activity and after call the" - + " callback method."); + + " callback method."); } } diff --git a/callback/src/main/java/com/iluwatar/callback/Task.java b/callback/src/main/java/com/iluwatar/callback/Task.java index 15cd99e9ae70..09c8f67afcf8 100644 --- a/callback/src/main/java/com/iluwatar/callback/Task.java +++ b/callback/src/main/java/com/iluwatar/callback/Task.java @@ -24,14 +24,12 @@ package com.iluwatar.callback; /** - * - * Template-method class for callback hook execution - * + * Template-method class for callback hook execution. */ public abstract class Task { /** - * Execute with callback + * Execute with callback. */ final void executeWith(final Callback callback) { execute(); diff --git a/chain/src/main/java/com/iluwatar/chain/App.java b/chain/src/main/java/com/iluwatar/chain/App.java index c45d682769bf..d6b7ebe2ef10 100644 --- a/chain/src/main/java/com/iluwatar/chain/App.java +++ b/chain/src/main/java/com/iluwatar/chain/App.java @@ -24,23 +24,21 @@ package com.iluwatar.chain; /** - * * The Chain of Responsibility pattern is a design pattern consisting of command objects and a * series of processing objects. Each processing object contains logic that defines the types of * command objects that it can handle; the rest are passed to the next processing object in the * chain. A mechanism also exists for adding new processing objects to the end of this chain. - *

- * In this example we organize the request handlers ({@link RequestHandler}) into a chain where each - * handler has a chance to act on the request on its turn. Here the king ({@link OrcKing}) makes - * requests and the military orcs ({@link OrcCommander}, {@link OrcOfficer}, {@link OrcSoldier}) - * form the handler chain. - * + * + *

In this example we organize the request handlers ({@link RequestHandler}) into a chain where + * each handler has a chance to act on the request on its turn. Here the king ({@link OrcKing}) + * makes requests and the military orcs ({@link OrcCommander}, {@link OrcOfficer}, {@link + * OrcSoldier}) form the handler chain. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/chain/src/main/java/com/iluwatar/chain/OrcCommander.java b/chain/src/main/java/com/iluwatar/chain/OrcCommander.java index 4770eafcb624..a0dab903a76a 100644 --- a/chain/src/main/java/com/iluwatar/chain/OrcCommander.java +++ b/chain/src/main/java/com/iluwatar/chain/OrcCommander.java @@ -24,9 +24,7 @@ package com.iluwatar.chain; /** - * - * OrcCommander - * + * OrcCommander. */ public class OrcCommander extends RequestHandler { diff --git a/chain/src/main/java/com/iluwatar/chain/OrcKing.java b/chain/src/main/java/com/iluwatar/chain/OrcKing.java index 39243d0fdc5c..93c01da81c4b 100644 --- a/chain/src/main/java/com/iluwatar/chain/OrcKing.java +++ b/chain/src/main/java/com/iluwatar/chain/OrcKing.java @@ -24,9 +24,7 @@ package com.iluwatar.chain; /** - * * OrcKing makes requests that are handled by the chain. - * */ public class OrcKing { diff --git a/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java b/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java index 6cf78b11dcb7..abf1afe8bded 100644 --- a/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java +++ b/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java @@ -24,9 +24,7 @@ package com.iluwatar.chain; /** - * - * OrcOfficer - * + * OrcOfficer. */ public class OrcOfficer extends RequestHandler { diff --git a/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java b/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java index 686840d9548f..f1291a0a782b 100644 --- a/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java +++ b/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java @@ -24,9 +24,7 @@ package com.iluwatar.chain; /** - * - * OrcSoldier - * + * OrcSoldier. */ public class OrcSoldier extends RequestHandler { diff --git a/chain/src/main/java/com/iluwatar/chain/Request.java b/chain/src/main/java/com/iluwatar/chain/Request.java index c8962aafa954..621303d93749 100644 --- a/chain/src/main/java/com/iluwatar/chain/Request.java +++ b/chain/src/main/java/com/iluwatar/chain/Request.java @@ -26,24 +26,24 @@ import java.util.Objects; /** - * Request + * Request. */ public class Request { /** * The type of this request, used by each item in the chain to see if they should or can handle - * this particular request + * this particular request. */ private final RequestType requestType; /** - * A description of the request + * A description of the request. */ private final String requestDescription; /** * Indicates if the request is handled or not. A request can only switch state from unhandled to - * handled, there's no way to 'unhandle' a request + * handled, there's no way to 'unhandle' a request. */ private boolean handled; @@ -59,7 +59,7 @@ public Request(final RequestType requestType, final String requestDescription) { } /** - * Get a description of the request + * Get a description of the request. * * @return A human readable description of the request */ @@ -69,7 +69,7 @@ public String getRequestDescription() { /** * Get the type of this request, used by each person in the chain of command to see if they should - * or can handle this particular request + * or can handle this particular request. * * @return The request type */ @@ -78,14 +78,14 @@ public RequestType getRequestType() { } /** - * Mark the request as handled + * Mark the request as handled. */ public void markHandled() { this.handled = true; } /** - * Indicates if this request is handled or not + * Indicates if this request is handled or not. * * @return true when the request is handled, false if not */ diff --git a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java index aed5c0611cd6..7923f03a6ddb 100644 --- a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java +++ b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * RequestHandler - * + * RequestHandler. */ public abstract class RequestHandler { @@ -42,7 +40,7 @@ public RequestHandler(RequestHandler next) { } /** - * Request handler + * Request handler. */ public void handleRequest(Request req) { if (next != null) { diff --git a/chain/src/main/java/com/iluwatar/chain/RequestType.java b/chain/src/main/java/com/iluwatar/chain/RequestType.java index 4e377a2b6215..b63cf940270c 100644 --- a/chain/src/main/java/com/iluwatar/chain/RequestType.java +++ b/chain/src/main/java/com/iluwatar/chain/RequestType.java @@ -24,9 +24,7 @@ package com.iluwatar.chain; /** - * - * RequestType enumeration - * + * RequestType enumeration. */ public enum RequestType { diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java index 054158e9b6ae..c3465d801905 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java @@ -28,42 +28,39 @@ /** *

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

*

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

*

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

*/ public class App { - + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - * + + /** + * Program entry point. + * * @param args command line args */ @SuppressWarnings("squid:S2189") @@ -71,14 +68,14 @@ public static void main(String[] args) { //Create an object of monitoring service which makes both local and remote calls var obj = new MonitoringService(); //Set the circuit Breaker parameters - var circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); + var circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); var serverStartTime = System.nanoTime(); while (true) { LOGGER.info(obj.localResourceResponse()); LOGGER.info(obj.remoteResourceResponse(circuitBreaker, serverStartTime)); LOGGER.info(circuitBreaker.getState()); try { - Thread.sleep(5 * 1000); + Thread.sleep(5 * 1000); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java index 005a000dff49..18268b1ce107 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java @@ -24,7 +24,7 @@ package com.iluwatar.circuitbreaker; /** - * The circuit breaker class with all configurations + * The circuit breaker class with all configurations. */ public class CircuitBreaker { private final long timeout; @@ -36,27 +36,31 @@ public class CircuitBreaker { private final long futureTime = 1000 * 1000 * 1000 * 1000; /** - * Constructor to create an instance of Circuit Breaker - * @param timeout Timeout for the API request. Not necessary for this simple example - * @param failureThreshold Number of failures we receive from the depended service before changing state to 'OPEN' - * @param retryTimePeriod Time period after which a new request is made to remote service for status check. + * Constructor to create an instance of Circuit Breaker. + * + * @param timeout Timeout for the API request. Not necessary for this simple example + * @param failureThreshold Number of failures we receive from the depended service before changing + * state to 'OPEN' + * @param retryTimePeriod Time period after which a new request is made to remote service for + * status check. */ CircuitBreaker(long timeout, int failureThreshold, long retryTimePeriod) { // We start in a closed state hoping that everything is fine this.state = State.CLOSED; this.failureThreshold = failureThreshold; - // Timeout for the API request. Used to break the calls made to remote resource if it exceeds the limit + // Timeout for the API request. + // Used to break the calls made to remote resource if it exceeds the limit this.timeout = timeout; this.retryTimePeriod = retryTimePeriod; //An absurd amount of time in future which basically indicates the last failure never happened this.lastFailureTime = System.nanoTime() + futureTime; this.failureCount = 0; } - + //Reset everything to defaults private void reset() { this.failureCount = 0; - this.lastFailureTime = System.nanoTime() + futureTime; + this.lastFailureTime = System.nanoTime() + futureTime; this.state = State.CLOSED; } @@ -64,7 +68,7 @@ private void recordFailure() { failureCount = failureCount + 1; this.lastFailureTime = System.nanoTime(); } - + protected void setState() { if (failureCount > failureThreshold) { //Then something is wrong with remote service if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { @@ -79,23 +83,28 @@ protected void setState() { state = State.CLOSED; } } - + public String getState() { return state.name(); } - + /** - * Break the circuit beforehand if it is known service is down - * Or connect the circuit manually if service comes online before expected + * Break the circuit beforehand if it is known service is down Or connect the circuit manually if + * service comes online before expected. + * * @param state State at which circuit is in */ public void setStateForBypass(State state) { this.state = state; } - + /** - * @param serviceToCall The name of the service in String. Can be changed to data URLs in case of web applications - * @param serverStartTime Time at which actual server was started which makes calls to this service + * Executes service call. + * + * @param serviceToCall The name of the service in String. Can be changed to data URLs in case + * of web applications + * @param serverStartTime Time at which actual server was started which makes calls to this + * service * @return Value from the remote resource, stale response or a custom exception */ public String call(String serviceToCall, long serverStartTime) throws Exception { @@ -104,7 +113,7 @@ public String call(String serviceToCall, long serverStartTime) throws Exception // return cached response if no the circuit is in OPEN state return "This is stale response from API"; } else { - // Make the API request if the circuit is not OPEN + // Make the API request if the circuit is not OPEN if (serviceToCall.equals("delayedService")) { var delayedService = new DelayedService(20); var response = delayedService.response(serverStartTime); diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java index b291c3fe5bf3..13861923b7a4 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java @@ -24,14 +24,15 @@ package com.iluwatar.circuitbreaker; /** -* This simulates the remote service -* It responds only after a certain timeout period (default set to 20 seconds) -*/ + * This simulates the remote service It responds only after a certain timeout period (default set to + * 20 seconds). + */ public class DelayedService { private final int delay; /** - * Constructor to create an instance of DelayedService, which is down for first few seconds + * Constructor to create an instance of DelayedService, which is down for first few seconds. + * * @param delay the delay after which service would behave properly, in seconds */ public DelayedService(int delay) { @@ -43,7 +44,10 @@ public DelayedService() { } /** - * @param serverStartTime Time at which actual server was started which makes calls to this service + * Responds based on delay, current time and server start time if the service is down / working. + * + * @param serverStartTime Time at which actual server was started which makes calls to this + * service * @return The state of the service */ public String response(long serverStartTime) { diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java index f46843766527..e91367175a66 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java @@ -24,8 +24,8 @@ package com.iluwatar.circuitbreaker; /** - * The service class which makes local and remote calls - * Uses {@link CircuitBreaker} object to ensure remote calls don't use up resources + * The service class which makes local and remote calls Uses {@link CircuitBreaker} object to ensure + * remote calls don't use up resources. */ public class MonitoringService { @@ -35,9 +35,11 @@ public String localResourceResponse() { } /** - * Try to get result from remote server - * @param circuitBreaker The circuitBreaker object with all parameters - * @param serverStartTime Time at which actual server was started which makes calls to this service + * Try to get result from remote server. + * + * @param circuitBreaker The circuitBreaker object with all parameters + * @param serverStartTime Time at which actual server was started which makes calls to this + * service * @return result from the remote response or exception raised by it. */ public String remoteResourceResponse(CircuitBreaker circuitBreaker, long serverStartTime) { diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java index 92fe0f2546ef..95fdb08d65ca 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java @@ -24,10 +24,10 @@ package com.iluwatar.circuitbreaker; /** - * Enumeration for states the circuit breaker could be in + * Enumeration for states the circuit breaker could be in. */ public enum State { - CLOSED, - OPEN, - HALF_OPEN + CLOSED, + OPEN, + HALF_OPEN } \ No newline at end of file From 2f49648047e60bd4a7e14b58a8ebb2a2a2046201 Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 01:05:15 +0530 Subject: [PATCH 05/32] Resolves checkstyle errors for collection-pipeline, command, commander (#1061) * Reduces checkstyle errors in collection-pipeline * Reduces checkstyle errors in command * Reduces checkstyle errors in commander --- .../com/iluwatar/collectionpipeline/App.java | 42 +- .../com/iluwatar/collectionpipeline/Car.java | 9 +- .../collectionpipeline/CarFactory.java | 1 + .../iluwatar/collectionpipeline/Category.java | 2 +- .../FunctionalProgramming.java | 43 +-- .../ImperativeProgramming.java | 53 ++- .../iluwatar/collectionpipeline/Person.java | 1 + .../iluwatar/collectionpipeline/AppTest.java | 29 +- .../main/java/com/iluwatar/command/App.java | 27 +- .../java/com/iluwatar/command/Command.java | 2 - .../java/com/iluwatar/command/Goblin.java | 4 +- .../iluwatar/command/InvisibilitySpell.java | 4 +- .../com/iluwatar/command/ShrinkSpell.java | 4 +- .../main/java/com/iluwatar/command/Size.java | 2 - .../java/com/iluwatar/command/Target.java | 4 +- .../java/com/iluwatar/command/Visibility.java | 2 - .../java/com/iluwatar/command/Wizard.java | 15 +- .../commander/AppEmployeeDbFailCases.java | 50 +-- .../commander/AppMessagingFailCases.java | 95 +++-- .../commander/AppPaymentFailCases.java | 43 ++- .../iluwatar/commander/AppQueueFailCases.java | 99 +++-- .../commander/AppShippingFailCases.java | 55 +-- .../com/iluwatar/commander/Commander.java | 361 ++++++++++-------- .../java/com/iluwatar/commander/Database.java | 8 +- .../java/com/iluwatar/commander/Order.java | 12 +- .../java/com/iluwatar/commander/Retry.java | 37 +- .../java/com/iluwatar/commander/Service.java | 28 +- .../employeehandle/EmployeeDatabase.java | 8 +- .../employeehandle/EmployeeHandle.java | 12 +- .../DatabaseUnavailableException.java | 4 +- .../PaymentDetailsErrorException.java | 4 +- .../ShippingNotPossibleException.java | 4 +- .../messagingservice/MessagingDatabase.java | 6 +- .../messagingservice/MessagingService.java | 35 +- .../paymentservice/PaymentDatabase.java | 7 +- .../paymentservice/PaymentService.java | 16 +- .../com/iluwatar/commander/queue/Queue.java | 14 +- .../commander/queue/QueueDatabase.java | 19 +- .../iluwatar/commander/queue/QueueTask.java | 34 +- .../shippingservice/ShippingDatabase.java | 8 +- .../shippingservice/ShippingService.java | 17 +- 41 files changed, 646 insertions(+), 574 deletions(-) diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java index de19a3b15508..e0cc904d67bf 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java @@ -23,21 +23,18 @@ package com.iluwatar.collectionpipeline; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * In imperative-style programming, it is common to use for and while loops for - * most kinds of data processing. Function composition is a simple technique - * that lets you sequence modular functions to create more complex operations. - * When you run data through the sequence, you have a collection pipeline. - * Together, the Function Composition and Collection Pipeline patterns enable - * you to create sophisticated programs where data flow from upstream to - * downstream and is passed through a series of transformations. - * + * In imperative-style programming, it is common to use for and while loops for most kinds of data + * processing. Function composition is a simple technique that lets you sequence modular functions + * to create more complex operations. When you run data through the sequence, you have a collection + * pipeline. Together, the Function Composition and Collection Pipeline patterns enable you to + * create sophisticated programs where data flow from upstream to downstream and is passed through a + * series of transformations. */ public class App { @@ -45,32 +42,35 @@ public class App { /** * Program entry point. - * - * @param args - * command line args + * + * @param args command line args */ public static void main(String[] args) { List cars = CarFactory.createCars(); - + List modelsImperative = ImperativeProgramming.getModelsAfter2000(cars); LOGGER.info(modelsImperative.toString()); List modelsFunctional = FunctionalProgramming.getModelsAfter2000(cars); LOGGER.info(modelsFunctional.toString()); - - Map> groupingByCategoryImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); + + Map> groupingByCategoryImperative = + ImperativeProgramming.getGroupingOfCarsByCategory(cars); LOGGER.info(groupingByCategoryImperative.toString()); - Map> groupingByCategoryFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); + Map> groupingByCategoryFunctional = + FunctionalProgramming.getGroupingOfCarsByCategory(cars); LOGGER.info(groupingByCategoryFunctional.toString()); - + Person john = new Person(cars); - List sedansOwnedImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); + List sedansOwnedImperative = + ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); LOGGER.info(sedansOwnedImperative.toString()); - List sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); + List sedansOwnedFunctional = + FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); LOGGER.info(sedansOwnedFunctional.toString()); } } diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java index 314728797cfa..2828cffd4708 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java @@ -34,10 +34,11 @@ public class Car { /** * Constructor to create an instance of car. - * @param make the make of the car - * @param model the model of the car + * + * @param make the make of the car + * @param model the model of the car * @param yearOfMake the year of built of the car - * @param category the {@link Category} of the car + * @param category the {@link Category} of the car */ public Car(String make, String model, int yearOfMake, Category category) { this.make = make; @@ -103,7 +104,7 @@ public String getModel() { public int getYear() { return year; } - + public Category getCategory() { return category; } diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java index aee1e21932df..ea29ceda64a1 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java @@ -34,6 +34,7 @@ private CarFactory() { /** * Factory method to create a {@link List} of {@link Car} instances. + * * @return {@link List} of {@link Car} */ public static List createCars() { diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java index 170d4df33e65..2214ebd4c9f8 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java @@ -24,7 +24,7 @@ package com.iluwatar.collectionpipeline; /** - * Enum for the category of car + * Enum for the category of car. */ public enum Category { JEEP, SEDAN, CONVERTIBLE diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java index 2a72aa00848a..bb216d2bc507 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java @@ -30,20 +30,17 @@ /** * Iterating and sorting with a collection pipeline - * + * *

In functional programming, it's common to sequence complex operations through - * a series of smaller modular functions or operations. The series is called a - * composition of functions, or a function composition. When a collection of - * data flows through a function composition, it becomes a collection pipeline. - * Function Composition and Collection Pipeline are two design patterns - * frequently used in functional-style programming. - * + * a series of smaller modular functions or operations. The series is called a composition of + * functions, or a function composition. When a collection of data flows through a function + * composition, it becomes a collection pipeline. Function Composition and Collection Pipeline are + * two design patterns frequently used in functional-style programming. + * *

Instead of passing a lambda expression to the map method, we passed the - * method reference Car::getModel. Likewise, instead of passing the lambda - * expression car -> car.getYear() to the comparing method, we passed the method - * reference Car::getYear. Method references are short, concise, and expressive. - * It is best to use them wherever possible. - * + * method reference Car::getModel. Likewise, instead of passing the lambda expression car -> + * car.getYear() to the comparing method, we passed the method reference Car::getYear. Method + * references are short, concise, and expressive. It is best to use them wherever possible. */ public class FunctionalProgramming { private FunctionalProgramming() { @@ -51,35 +48,35 @@ private FunctionalProgramming() { /** * Method to get models using for collection pipeline. - * + * * @param cars {@link List} of {@link Car} to be used for filtering * @return {@link List} of {@link String} representing models built after year 2000 */ public static List getModelsAfter2000(List cars) { return cars.stream().filter(car -> car.getYear() > 2000) - .sorted(Comparator.comparing(Car::getYear)) - .map(Car::getModel).collect(Collectors.toList()); + .sorted(Comparator.comparing(Car::getYear)) + .map(Car::getModel).collect(Collectors.toList()); } - + /** - * Method to group cars by category using groupingBy - * + * Method to group cars by category using groupingBy. + * * @param cars {@link List} of {@link Car} to be used for grouping * @return {@link Map} with category as key and cars belonging to that category as value */ public static Map> getGroupingOfCarsByCategory(List cars) { return cars.stream().collect(Collectors.groupingBy(Car::getCategory)); } - + /** - * Method to get all Sedan cars belonging to a group of persons sorted by year of manufacture - * + * Method to get all Sedan cars belonging to a group of persons sorted by year of manufacture. + * * @param persons {@link List} of {@link Person} to be used * @return {@link List} of {@link Car} to belonging to the group */ public static List getSedanCarsOwnedSortedByDate(List persons) { return persons.stream().map(Person::getCars).flatMap(List::stream) - .filter(car -> Category.SEDAN.equals(car.getCategory())) - .sorted(Comparator.comparing(Car::getYear)).collect(Collectors.toList()); + .filter(car -> Category.SEDAN.equals(car.getCategory())) + .sorted(Comparator.comparing(Car::getYear)).collect(Collectors.toList()); } } diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java index 01d095e96099..a587e9c37084 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java @@ -31,23 +31,20 @@ import java.util.Map; /** - * Imperative-style programming to iterate over the list and get the names of - * cars made later than the year 2000. We then sort the models in ascending - * order by year. - * + * Imperative-style programming to iterate over the list and get the names of cars made later than + * the year 2000. We then sort the models in ascending order by year. + * *

As you can see, there's a lot of looping in this code. First, the - * getModelsAfter2000UsingFor method takes a list of cars as its parameter. It - * extracts or filters out cars made after the year 2000, putting them into a - * new list named carsSortedByYear. Next, it sorts that list in ascending order - * by year-of-make. Finally, it loops through the list carsSortedByYear to get - * the model names and returns them in a list. - * + * getModelsAfter2000UsingFor method takes a list of cars as its parameter. It extracts or filters + * out cars made after the year 2000, putting them into a new list named carsSortedByYear. Next, it + * sorts that list in ascending order by year-of-make. Finally, it loops through the list + * carsSortedByYear to get the model names and returns them in a list. + * *

This short example demonstrates what I call the effect of statements. While - * functions and methods in general can be used as expressions, the {@link Collections} - * sort method doesn't return a result. Because it is used as a statement, it - * mutates the list given as argument. Both of the for loops also mutate lists - * as they iterate. Being statements, that's just how these elements work. As a - * result, the code contains unnecessary garbage variables + * functions and methods in general can be used as expressions, the {@link Collections} sort method + * doesn't return a result. Because it is used as a statement, it mutates the list given as + * argument. Both of the for loops also mutate lists as they iterate. Being statements, that's just + * how these elements work. As a result, the code contains unnecessary garbage variables */ public class ImperativeProgramming { private ImperativeProgramming() { @@ -55,6 +52,7 @@ private ImperativeProgramming() { /** * Method to return the car models built after year 2000 using for loops. + * * @param cars {@link List} of {@link Car} to iterate over * @return {@link List} of {@link String} of car models built after year 2000 */ @@ -80,16 +78,16 @@ public int compare(Car car1, Car car2) { return models; } - + /** - * Method to group cars by category using for loops - * + * Method to group cars by category using for loops. + * * @param cars {@link List} of {@link Car} to be used for grouping * @return {@link Map} with category as key and cars belonging to that category as value */ public static Map> getGroupingOfCarsByCategory(List cars) { Map> groupingByCategory = new HashMap<>(); - for (Car car: cars) { + for (Car car : cars) { if (groupingByCategory.containsKey(car.getCategory())) { groupingByCategory.get(car.getCategory()).add(car); } else { @@ -100,33 +98,34 @@ public static Map> getGroupingOfCarsByCategory(List car } return groupingByCategory; } - + /** - * Method to get all Sedan cars belonging to a group of persons sorted by year of manufacture using for loops - * + * Method to get all Sedan cars belonging to a group of persons sorted by year of manufacture + * using for loops. + * * @param persons {@link List} of {@link Person} to be used * @return {@link List} of {@link Car} to belonging to the group */ public static List getSedanCarsOwnedSortedByDate(List persons) { List cars = new ArrayList<>(); - for (Person person: persons) { + for (Person person : persons) { cars.addAll(person.getCars()); } - + List sedanCars = new ArrayList<>(); - for (Car car: cars) { + for (Car car : cars) { if (Category.SEDAN.equals(car.getCategory())) { sedanCars.add(car); } } - + sedanCars.sort(new Comparator() { @Override public int compare(Car o1, Car o2) { return o1.getYear() - o2.getYear(); } }); - + return sedanCars; } } diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java index 9bf01052a667..2e564b701800 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java @@ -33,6 +33,7 @@ public class Person { /** * Constructor to create an instance of person. + * * @param cars the list of cars owned */ public Person(List cars) { diff --git a/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java index 6bc035920d88..1fa27ec4d12c 100644 --- a/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java +++ b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java @@ -23,14 +23,13 @@ package com.iluwatar.collectionpipeline; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Tests that Collection Pipeline methods work as expected. @@ -39,35 +38,35 @@ public class AppTest { private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class); private List cars = CarFactory.createCars(); - + @Test public void testGetModelsAfter2000UsingFor() { var models = ImperativeProgramming.getModelsAfter2000(cars); assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models); } - + @Test public void testGetModelsAfter2000UsingPipeline() { var models = FunctionalProgramming.getModelsAfter2000(cars); assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models); } - + @Test public void testGetGroupingOfCarsByCategory() { var modelsExpected = Map.of( - Category.CONVERTIBLE, List.of(new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), - new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)), - Category.SEDAN, List.of(new Car("Dodge", "Avenger", 2010, Category.SEDAN), - new Car("Ford", "Focus", 2012, Category.SEDAN)), - Category.JEEP, List.of(new Car("Jeep", "Wrangler", 2011, Category.JEEP), - new Car("Jeep", "Comanche", 1990, Category.JEEP))); + Category.CONVERTIBLE, List.of(new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), + new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)), + Category.SEDAN, List.of(new Car("Dodge", "Avenger", 2010, Category.SEDAN), + new Car("Ford", "Focus", 2012, Category.SEDAN)), + Category.JEEP, List.of(new Car("Jeep", "Wrangler", 2011, Category.JEEP), + new Car("Jeep", "Comanche", 1990, Category.JEEP))); var modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); var modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); LOGGER.info("Category " + modelsFunctional); assertEquals(modelsExpected, modelsFunctional); assertEquals(modelsExpected, modelsImperative); } - + @Test public void testGetSedanCarsOwnedSortedByDate() { var john = new Person(cars); diff --git a/command/src/main/java/com/iluwatar/command/App.java b/command/src/main/java/com/iluwatar/command/App.java index 39e59077e721..8e7ee31a81d0 100644 --- a/command/src/main/java/com/iluwatar/command/App.java +++ b/command/src/main/java/com/iluwatar/command/App.java @@ -24,31 +24,28 @@ package com.iluwatar.command; /** - * * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all * information needed to perform an action or trigger an event at a later time. This information * includes the method name, the object that owns the method and values for the method parameters. - *

- * Four terms always associated with the command pattern are command, receiver, invoker and client. - * A command object (spell) knows about the receiver (target) and invokes a method of the receiver. - * Values for parameters of the receiver method are stored in the command. The receiver then does - * the work. An invoker object (wizard) knows how to execute a command, and optionally does - * bookkeeping about the command execution. The invoker does not know anything about a concrete + * + *

Four terms always associated with the command pattern are command, receiver, invoker and + * client. A command object (spell) knows about the receiver (target) and invokes a method of the + * receiver. Values for parameters of the receiver method are stored in the command. The receiver + * then does the work. An invoker object (wizard) knows how to execute a command, and optionally + * does bookkeeping about the command execution. The invoker does not know anything about a concrete * command, it knows only about command interface. Both an invoker object and several command * objects are held by a client object (app). The client decides which commands to execute at which * points. To execute a command, it passes the command object to the invoker object. - *

- * In other words, in this example the wizard casts spells on the goblin. The wizard keeps track of - * the previous spells cast, so it is easy to undo them. In addition, the wizard keeps track of the - * spells undone, so they can be redone. - * - * + * + *

In other words, in this example the wizard casts spells on the goblin. The wizard keeps track + * of the previous spells cast, so it is easy to undo them. In addition, the wizard keeps track of + * the spells undone, so they can be redone. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/command/src/main/java/com/iluwatar/command/Command.java b/command/src/main/java/com/iluwatar/command/Command.java index b5854f6be3b8..85deff74efd8 100644 --- a/command/src/main/java/com/iluwatar/command/Command.java +++ b/command/src/main/java/com/iluwatar/command/Command.java @@ -24,9 +24,7 @@ package com.iluwatar.command; /** - * * Interface for Commands. - * */ public abstract class Command { diff --git a/command/src/main/java/com/iluwatar/command/Goblin.java b/command/src/main/java/com/iluwatar/command/Goblin.java index b2c0d75d0c2b..72ddc43b5c3f 100644 --- a/command/src/main/java/com/iluwatar/command/Goblin.java +++ b/command/src/main/java/com/iluwatar/command/Goblin.java @@ -24,9 +24,7 @@ package com.iluwatar.command; /** - * - * Goblin is the target of the spells - * + * Goblin is the target of the spells. */ public class Goblin extends Target { diff --git a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java b/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java index bdbc54889916..3e0f7bbf4fef 100644 --- a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java +++ b/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java @@ -24,9 +24,7 @@ package com.iluwatar.command; /** - * - * InvisibilitySpell is a concrete command - * + * InvisibilitySpell is a concrete command. */ public class InvisibilitySpell extends Command { diff --git a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java b/command/src/main/java/com/iluwatar/command/ShrinkSpell.java index 81f04d40747f..6bbc339f41f3 100644 --- a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java +++ b/command/src/main/java/com/iluwatar/command/ShrinkSpell.java @@ -24,9 +24,7 @@ package com.iluwatar.command; /** - * - * ShrinkSpell is a concrete command - * + * ShrinkSpell is a concrete command. */ public class ShrinkSpell extends Command { diff --git a/command/src/main/java/com/iluwatar/command/Size.java b/command/src/main/java/com/iluwatar/command/Size.java index a10fb84bc079..ae327d8b1ad8 100644 --- a/command/src/main/java/com/iluwatar/command/Size.java +++ b/command/src/main/java/com/iluwatar/command/Size.java @@ -24,9 +24,7 @@ package com.iluwatar.command; /** - * * Enumeration for target size. - * */ public enum Size { diff --git a/command/src/main/java/com/iluwatar/command/Target.java b/command/src/main/java/com/iluwatar/command/Target.java index 8bf652e6ce56..f5ac4344c918 100644 --- a/command/src/main/java/com/iluwatar/command/Target.java +++ b/command/src/main/java/com/iluwatar/command/Target.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * Base class for spell targets. - * */ public abstract class Target { @@ -59,7 +57,7 @@ public void setVisibility(Visibility visibility) { public abstract String toString(); /** - * Print status + * Print status. */ public void printStatus() { LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); diff --git a/command/src/main/java/com/iluwatar/command/Visibility.java b/command/src/main/java/com/iluwatar/command/Visibility.java index a8ed73052930..3c48990a0acf 100644 --- a/command/src/main/java/com/iluwatar/command/Visibility.java +++ b/command/src/main/java/com/iluwatar/command/Visibility.java @@ -24,9 +24,7 @@ package com.iluwatar.command; /** - * * Enumeration for target visibility. - * */ public enum Visibility { diff --git a/command/src/main/java/com/iluwatar/command/Wizard.java b/command/src/main/java/com/iluwatar/command/Wizard.java index a56c5650513d..fcd6e3a5b702 100644 --- a/command/src/main/java/com/iluwatar/command/Wizard.java +++ b/command/src/main/java/com/iluwatar/command/Wizard.java @@ -23,16 +23,13 @@ package com.iluwatar.command; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Deque; import java.util.LinkedList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * - * Wizard is the invoker of the commands - * + * Wizard is the invoker of the commands. */ public class Wizard { @@ -46,7 +43,7 @@ public Wizard() { } /** - * Cast spell + * Cast spell. */ public void castSpell(Command command, Target target) { LOGGER.info("{} casts {} at {}", this, command, target); @@ -55,7 +52,7 @@ public void castSpell(Command command, Target target) { } /** - * Undo last spell + * Undo last spell. */ public void undoLastSpell() { if (!undoStack.isEmpty()) { @@ -67,7 +64,7 @@ public void undoLastSpell() { } /** - * Redo last spell + * Redo last spell. */ public void redoLastSpell() { if (!redoStack.isEmpty()) { diff --git a/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java index b488056a6ac4..84297f828350 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java @@ -31,16 +31,15 @@ import com.iluwatar.commander.messagingservice.MessagingService; import com.iluwatar.commander.paymentservice.PaymentDatabase; import com.iluwatar.commander.paymentservice.PaymentService; +import com.iluwatar.commander.queue.QueueDatabase; import com.iluwatar.commander.shippingservice.ShippingDatabase; import com.iluwatar.commander.shippingservice.ShippingService; -import com.iluwatar.commander.queue.QueueDatabase; /** - * AppEmployeeDbFailCases class looks at possible cases when Employee handle service is + * AppEmployeeDbFailCases class looks at possible cases when Employee handle service is * available/unavailable. */ - -public class AppEmployeeDbFailCases { +public class AppEmployeeDbFailCases { final int numOfRetries = 3; final long retryDuration = 30000; final long queueTime = 240000; //4 mins @@ -50,33 +49,40 @@ public class AppEmployeeDbFailCases { final long employeeTime = 240000; //4 mins void employeeDatabaseUnavailableCase() throws Exception { - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); ShippingService ss = new ShippingService(new ShippingDatabase()); MessagingService ms = new MessagingService(new MessagingDatabase()); - EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); - QueueDatabase qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + EmployeeHandle eh = + new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + QueueDatabase qdb = + new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException()); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); } void employeeDbSuccessCase() throws Exception { - PaymentService ps = new PaymentService(new PaymentDatabase()); - ShippingService ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + PaymentService ps = new PaymentService(new PaymentDatabase()); + ShippingService ss = + new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); MessagingService ms = new MessagingService(new MessagingDatabase()); - EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + EmployeeHandle eh = + new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); QueueDatabase qdb = new QueueDatabase(); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); @@ -87,7 +93,7 @@ void employeeDbSuccessCase() throws Exception { * * @param args command line args */ - + public static void main(String[] args) throws Exception { AppEmployeeDbFailCases aefc = new AppEmployeeDbFailCases(); //aefc.employeeDatabaseUnavailableCase(); diff --git a/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java index a6010229e1ac..d644d1c1f0e4 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java @@ -30,12 +30,12 @@ import com.iluwatar.commander.messagingservice.MessagingService; import com.iluwatar.commander.paymentservice.PaymentDatabase; import com.iluwatar.commander.paymentservice.PaymentService; +import com.iluwatar.commander.queue.QueueDatabase; import com.iluwatar.commander.shippingservice.ShippingDatabase; import com.iluwatar.commander.shippingservice.ShippingService; -import com.iluwatar.commander.queue.QueueDatabase; /** - * AppMessagingFailCases class looks at possible cases when Messaging service is + * AppMessagingFailCases class looks at possible cases when Messaging service is * available/unavailable. */ @@ -50,15 +50,17 @@ public class AppMessagingFailCases { void messagingDatabaseUnavailableCasePaymentSuccess() throws Exception { //rest is successful - PaymentService ps = new PaymentService(new PaymentDatabase()); + PaymentService ps = new PaymentService(new PaymentDatabase()); ShippingService ss = new ShippingService(new ShippingDatabase()); - MessagingService ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + MessagingService ms = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); @@ -66,40 +68,52 @@ void messagingDatabaseUnavailableCasePaymentSuccess() throws Exception { void messagingDatabaseUnavailableCasePaymentError() throws Exception { //rest is successful - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); ShippingService ss = new ShippingService(new ShippingDatabase()); - MessagingService ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); + MessagingService ms = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); } - void messagingDatabaseUnavailableCasePaymentFailure() throws Exception { + void messagingDatabaseUnavailableCasePaymentFailure() throws Exception { //rest is successful - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); ShippingService ss = new ShippingService(new ShippingDatabase()); - MessagingService ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + MessagingService ms = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); - QueueDatabase qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration,queueTime,queueTaskTime, - paymentTime,messageTime,employeeTime); + QueueDatabase qdb = + new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException()); + Commander c = + new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, queueTime, queueTaskTime, + paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); @@ -107,16 +121,19 @@ void messagingDatabaseUnavailableCasePaymentFailure() throws Exception { void messagingSuccessCase() throws Exception { //done here - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); ShippingService ss = new ShippingService(new ShippingDatabase()); - MessagingService ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + MessagingService ms = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); @@ -127,7 +144,7 @@ void messagingSuccessCase() throws Exception { * * @param args command line args */ - + public static void main(String[] args) throws Exception { AppMessagingFailCases amfc = new AppMessagingFailCases(); //amfc.messagingDatabaseUnavailableCasePaymentSuccess(); diff --git a/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java index 86fd5a83c7f1..4e65b1d28cfb 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java @@ -31,13 +31,12 @@ import com.iluwatar.commander.messagingservice.MessagingService; import com.iluwatar.commander.paymentservice.PaymentDatabase; import com.iluwatar.commander.paymentservice.PaymentService; +import com.iluwatar.commander.queue.QueueDatabase; import com.iluwatar.commander.shippingservice.ShippingDatabase; import com.iluwatar.commander.shippingservice.ShippingService; -import com.iluwatar.commander.queue.QueueDatabase; /** - * AppPaymentFailCases class looks at possible cases when Payment service is - * available/unavailable. + * AppPaymentFailCases class looks at possible cases when Payment service is available/unavailable. */ public class AppPaymentFailCases { @@ -50,14 +49,16 @@ public class AppPaymentFailCases { final long employeeTime = 240000; //4 mins void paymentNotPossibleCase() throws Exception { - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new PaymentDetailsErrorException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), + new PaymentDetailsErrorException()); ShippingService ss = new ShippingService(new ShippingDatabase()); - MessagingService ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + MessagingService ms = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(new DatabaseUnavailableException()); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); @@ -65,15 +66,17 @@ void paymentNotPossibleCase() throws Exception { void paymentDatabaseUnavailableCase() throws Exception { //rest is successful - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); ShippingService ss = new ShippingService(new ShippingDatabase()); MessagingService ms = new MessagingService(new MessagingDatabase()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); @@ -81,14 +84,16 @@ void paymentDatabaseUnavailableCase() throws Exception { void paymentSuccessCase() throws Exception { //goes to message after 2 retries maybe - rest is successful for now - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); ShippingService ss = new ShippingService(new ShippingDatabase()); - MessagingService ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + MessagingService ms = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(new DatabaseUnavailableException()); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); @@ -99,7 +104,7 @@ void paymentSuccessCase() throws Exception { * * @param args command line args */ - + public static void main(String[] args) throws Exception { AppPaymentFailCases apfc = new AppPaymentFailCases(); //apfc.paymentNotPossibleCase(); diff --git a/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java index f8c3548b271b..34ed81c0fb84 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java @@ -31,13 +31,12 @@ import com.iluwatar.commander.messagingservice.MessagingService; import com.iluwatar.commander.paymentservice.PaymentDatabase; import com.iluwatar.commander.paymentservice.PaymentService; +import com.iluwatar.commander.queue.QueueDatabase; import com.iluwatar.commander.shippingservice.ShippingDatabase; import com.iluwatar.commander.shippingservice.ShippingService; -import com.iluwatar.commander.queue.QueueDatabase; /** - * AppQueueFailCases class looks at possible cases when Queue Database is - * available/unavailable. + * AppQueueFailCases class looks at possible cases when Queue Database is available/unavailable. */ public class AppQueueFailCases { @@ -50,71 +49,87 @@ public class AppQueueFailCases { final long employeeTime = 240000; //4 mins void queuePaymentTaskDatabaseUnavailableCase() throws Exception { - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); ShippingService ss = new ShippingService(new ShippingDatabase()); MessagingService ms = new MessagingService(new MessagingDatabase()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); - QueueDatabase qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + QueueDatabase qdb = + new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException()); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); } void queueMessageTaskDatabaseUnavailableCase() throws Exception { - PaymentService ps = new PaymentService(new PaymentDatabase()); + PaymentService ps = new PaymentService(new PaymentDatabase()); ShippingService ss = new ShippingService(new ShippingDatabase()); - MessagingService ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + MessagingService ms = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); - QueueDatabase qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + QueueDatabase qdb = + new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException()); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); } void queueEmployeeDbTaskDatabaseUnavailableCase() throws Exception { - PaymentService ps = new PaymentService(new PaymentDatabase()); - ShippingService ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + PaymentService ps = new PaymentService(new PaymentDatabase()); + ShippingService ss = + new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); MessagingService ms = new MessagingService(new MessagingDatabase()); - EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); - QueueDatabase qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + EmployeeHandle eh = + new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + QueueDatabase qdb = + new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException()); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); } void queueSuccessCase() throws Exception { - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); ShippingService ss = new ShippingService(new ShippingDatabase()); - MessagingService ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + MessagingService ms = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); - QueueDatabase qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException()); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + QueueDatabase qdb = + new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException()); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); diff --git a/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java index b65f4fa4e793..a055ba699694 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java @@ -32,12 +32,12 @@ import com.iluwatar.commander.messagingservice.MessagingService; import com.iluwatar.commander.paymentservice.PaymentDatabase; import com.iluwatar.commander.paymentservice.PaymentService; +import com.iluwatar.commander.queue.QueueDatabase; import com.iluwatar.commander.shippingservice.ShippingDatabase; import com.iluwatar.commander.shippingservice.ShippingService; -import com.iluwatar.commander.queue.QueueDatabase; /** - * AppShippingFailCases class looks at possible cases when Shipping service is + * AppShippingFailCases class looks at possible cases when Shipping service is * available/unavailable. */ @@ -51,26 +51,28 @@ public class AppShippingFailCases { final long employeeTime = 240000; //4 mins void itemUnavailableCase() throws Exception { - PaymentService ps = new PaymentService(new PaymentDatabase()); - ShippingService ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + PaymentService ps = new PaymentService(new PaymentDatabase()); + ShippingService ss = + new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); MessagingService ms = new MessagingService(new MessagingDatabase()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); } void shippingNotPossibleCase() throws Exception { - PaymentService ps = new PaymentService(new PaymentDatabase()); - ShippingService ss = new ShippingService(new ShippingDatabase(), new ShippingNotPossibleException()); + PaymentService ps = new PaymentService(new PaymentDatabase()); + ShippingService ss = + new ShippingService(new ShippingDatabase(), new ShippingNotPossibleException()); MessagingService ms = new MessagingService(new MessagingDatabase()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); @@ -78,15 +80,17 @@ void shippingNotPossibleCase() throws Exception { void shippingDatabaseUnavailableCase() throws Exception { //rest is successful - PaymentService ps = new PaymentService(new PaymentDatabase()); - ShippingService ss = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + PaymentService ps = new PaymentService(new PaymentDatabase()); + ShippingService ss = + new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); MessagingService ms = new MessagingService(new MessagingDatabase()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); @@ -94,25 +98,28 @@ void shippingDatabaseUnavailableCase() throws Exception { void shippingSuccessCase() throws Exception { //goes to payment after 2 retries maybe - rest is successful for now - PaymentService ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException()); - ShippingService ss = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - MessagingService ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + PaymentService ps = + new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException()); + ShippingService ss = + new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + MessagingService ms = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); EmployeeHandle eh = new EmployeeHandle(new EmployeeDatabase()); QueueDatabase qdb = new QueueDatabase(); - Commander c = new Commander(eh,ps,ss,ms,qdb,numOfRetries,retryDuration, - queueTime,queueTaskTime,paymentTime,messageTime,employeeTime); + Commander c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); c.placeOrder(order); } - + /** * Program entry point. * * @param args command line args */ - + public static void main(String[] args) throws Exception { AppShippingFailCases asfc = new AppShippingFailCases(); //asfc.itemUnavailableCase(); diff --git a/commander/src/main/java/com/iluwatar/commander/Commander.java b/commander/src/main/java/com/iluwatar/commander/Commander.java index d161f7b9ff00..0c0989adea0b 100644 --- a/commander/src/main/java/com/iluwatar/commander/Commander.java +++ b/commander/src/main/java/com/iluwatar/commander/Commander.java @@ -23,53 +23,51 @@ package com.iluwatar.commander; -import java.util.ArrayList; +import com.iluwatar.commander.Order.MessageSent; +import com.iluwatar.commander.Order.PaymentStatus; import com.iluwatar.commander.employeehandle.EmployeeHandle; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.exceptions.ItemUnavailableException; import com.iluwatar.commander.exceptions.PaymentDetailsErrorException; import com.iluwatar.commander.exceptions.ShippingNotPossibleException; import com.iluwatar.commander.messagingservice.MessagingService; -import com.iluwatar.commander.Order.MessageSent; -import com.iluwatar.commander.Order.PaymentStatus; import com.iluwatar.commander.paymentservice.PaymentService; import com.iluwatar.commander.queue.QueueDatabase; import com.iluwatar.commander.queue.QueueTask; import com.iluwatar.commander.queue.QueueTask.TaskType; import com.iluwatar.commander.shippingservice.ShippingService; +import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - *

Commander pattern is used to handle all issues that can come up while making a - * distributed transaction. The idea is to have a commander, which coordinates the - * execution of all instructions and ensures proper completion using retries and - * taking care of idempotence. By queueing instructions while they haven't been done, - * we can ensure a state of 'eventual consistency'.

+ *

Commander pattern is used to handle all issues that can come up while making a + * distributed transaction. The idea is to have a commander, which coordinates the execution of all + * instructions and ensures proper completion using retries and taking care of idempotence. By + * queueing instructions while they haven't been done, we can ensure a state of 'eventual + * consistency'.

*

In our example, we have an e-commerce application. When the user places an order, - * the shipping service is intimated first. If the service does not respond for some - * reason, the order is not placed. If response is received, the commander then calls - * for the payment service to be intimated. If this fails, the shipping still takes - * place (order converted to COD) and the item is queued. If the queue is also found - * to be unavailable, the payment is noted to be not done and this is added to an - * employee database. Three types of messages are sent to the user - one, if payment - * succeeds; two, if payment fails definitively; and three, if payment fails in the - * first attempt. If the message is not sent, this is also queued and is added to employee - * db. We also have a time limit for each instruction to be completed, after which, the - * instruction is not executed, thereby ensuring that resources are not held for too long. - * In the rare occasion in which everything fails, an individual would have to step in to - * figure out how to solve the issue.

+ * the shipping service is intimated first. If the service does not respond for some reason, the + * order is not placed. If response is received, the commander then calls for the payment service to + * be intimated. If this fails, the shipping still takes place (order converted to COD) and the item + * is queued. If the queue is also found to be unavailable, the payment is noted to be not done and + * this is added to an employee database. Three types of messages are sent to the user - one, if + * payment succeeds; two, if payment fails definitively; and three, if payment fails in the first + * attempt. If the message is not sent, this is also queued and is added to employee db. We also + * have a time limit for each instruction to be completed, after which, the instruction is not + * executed, thereby ensuring that resources are not held for too long. In the rare occasion in + * which everything fails, an individual would have to step in to figure out how to solve the + * issue.

*

We have abstract classes {@link Database} and {@link Service} which are extended - * by all the databases and services. Each service has a database to be updated, and - * receives request from an outside user (the {@link Commander} class here). There are - * 5 microservices - {@link ShippingService}, {@link PaymentService}, {@link MessagingService}, - * {@link EmployeeHandle} and a {@link QueueDatabase}. We use retries to execute any - * instruction using {@link Retry} class, and idempotence is ensured by going through some - * checks before making requests to services and making change in {@link Order} class fields - * if request succeeds or definitively fails. There are 5 classes - - * {@link AppShippingFailCases}, {@link AppPaymentFailCases}, {@link AppMessagingFailCases}, - * {@link AppQueueFailCases} and {@link AppEmployeeDbFailCases}, which look at the different - * scenarios that may be encountered during the placing of an order.

+ * by all the databases and services. Each service has a database to be updated, and receives + * request from an outside user (the {@link Commander} class here). There are 5 microservices - + * {@link ShippingService}, {@link PaymentService}, {@link MessagingService}, {@link EmployeeHandle} + * and a {@link QueueDatabase}. We use retries to execute any instruction using {@link Retry} class, + * and idempotence is ensured by going through some checks before making requests to services and + * making change in {@link Order} class fields if request succeeds or definitively fails. There are + * 5 classes - {@link AppShippingFailCases}, {@link AppPaymentFailCases}, {@link + * AppMessagingFailCases}, {@link AppQueueFailCases} and {@link AppEmployeeDbFailCases}, which look + * at the different scenarios that may be encountered during the placing of an order.

*/ public class Commander { @@ -86,17 +84,18 @@ public class Commander { private final long queueTaskTime; private final long paymentTime; private final long messageTime; - private final long employeeTime; + private final long employeeTime; private boolean finalSiteMsgShown; static final Logger LOG = LoggerFactory.getLogger(Commander.class); //we could also have another db where it stores all orders - - Commander(EmployeeHandle empDb, PaymentService pService, ShippingService sService, - MessagingService mService, QueueDatabase qdb, int numOfRetries, long retryDuration, - long queueTime, long queueTaskTime, long paymentTime, long messageTime, long employeeTime) { - this.paymentService = pService; - this.shippingService = sService; - this.messagingService = mService; + + Commander(EmployeeHandle empDb, PaymentService paymentService, ShippingService shippingService, + MessagingService messagingService, QueueDatabase qdb, int numOfRetries, + long retryDuration, long queueTime, long queueTaskTime, long paymentTime, + long messageTime, long employeeTime) { + this.paymentService = paymentService; + this.shippingService = shippingService; + this.messagingService = messagingService; this.employeeDb = empDb; this.queue = qdb; this.numOfRetries = numOfRetries; @@ -106,7 +105,7 @@ public class Commander { this.paymentTime = paymentTime; this.messageTime = messageTime; this.employeeTime = employeeTime; - this.finalSiteMsgShown = false; + this.finalSiteMsgShown = false; } void placeOrder(Order order) throws Exception { @@ -118,40 +117,43 @@ private void sendShippingRequest(Order order) throws Exception { Retry.Operation op = (l) -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug("Order " + order.id + ": Error in connecting to shipping service, trying again.."); + LOG.debug("Order " + order.id + ": Error in connecting to shipping service, " + + "trying again.."); } else { LOG.debug("Order " + order.id + ": Error in creating shipping request.."); } throw l.remove(0); - } - String transactionId = shippingService.receiveRequest(order.item, order.user.address); + } + String transactionId = shippingService.receiveRequest(order.item, order.user.address); //could save this transaction id in a db too - LOG.info("Order " + order.id + ": Shipping placed successfully, transaction id: " + transactionId); + LOG.info("Order " + order.id + ": Shipping placed successfully, transaction id: " + + transactionId); LOG.info("Order has been placed and will be shipped to you. Please wait while we make your" - + " payment... "); - sendPaymentRequest(order); - return; + + " payment... "); + sendPaymentRequest(order); + return; }; - Retry.HandleErrorIssue handleError = (o,err) -> { + Retry.HandleErrorIssue handleError = (o, err) -> { if (ShippingNotPossibleException.class.isAssignableFrom(err.getClass())) { - LOG.info("Shipping is currently not possible to your address. We are working on the problem " - + "and will get back to you asap."); + LOG.info("Shipping is currently not possible to your address. We are working on the problem" + + " and will get back to you asap."); finalSiteMsgShown = true; - LOG.info("Order " + order.id + ": Shipping not possible to address, trying to add problem to employee db.."); + LOG.info("Order " + order.id + ": Shipping not possible to address, trying to add problem " + + "to employee db.."); employeeHandleIssue(o); } else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) { - LOG.info("This item is currently unavailable. We will inform you as soon as the item becomes " - + "available again."); + LOG.info("This item is currently unavailable. We will inform you as soon as the item " + + "becomes available again."); finalSiteMsgShown = true; - LOG.info("Order " + order.id + ": Item " + order.item + " unavailable, trying to add problem to employee " - + "handle.."); + LOG.info("Order " + order.id + ": Item " + order.item + " unavailable, trying to add " + + "problem to employee handle.."); employeeHandleIssue(o); } else { LOG.info("Sorry, there was a problem in creating your order. Please try later."); LOG.error("Order " + order.id + ": Shipping service unavailable, order not placed.."); finalSiteMsgShown = true; } - return; + return; }; Retry r = new Retry(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); @@ -174,28 +176,31 @@ public void run() { Retry.Operation op = (l) -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug("Order " + order.id + ": Error in connecting to payment service, trying again.."); + LOG.debug("Order " + order.id + ": Error in connecting to payment service," + + " trying again.."); } else { LOG.debug("Order " + order.id + ": Error in creating payment request.."); } - throw l.remove(0); - } + throw l.remove(0); + } if (order.paid.equals(PaymentStatus.Trying)) { String transactionId = paymentService.receiveRequest(order.price); - order.paid = PaymentStatus.Done; - LOG.info("Order " + order.id + ": Payment successful, transaction Id: " + transactionId); - if (!finalSiteMsgShown) { - LOG.info("Payment made successfully, thank you for shopping with us!!"); - finalSiteMsgShown = true; - } - sendSuccessMessage(order); - return; - } + order.paid = PaymentStatus.Done; + LOG.info("Order " + order.id + ": Payment successful, transaction Id: " + + transactionId); + if (!finalSiteMsgShown) { + LOG.info("Payment made successfully, thank you for shopping with us!!"); + finalSiteMsgShown = true; + } + sendSuccessMessage(order); + return; + } }; - Retry.HandleErrorIssue handleError = (o,err) -> { + Retry.HandleErrorIssue handleError = (o, err) -> { if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) { if (!finalSiteMsgShown) { - LOG.info("There was an error in payment. Your account/card details may have been incorrect. " + LOG.info("There was an error in payment. Your account/card details " + + "may have been incorrect. " + "Meanwhile, your order has been converted to COD and will be shipped."); finalSiteMsgShown = true; } @@ -213,15 +218,16 @@ public void run() { LOG.warn("Order " + order.id + ": Payment error, going to queue.."); sendPaymentPossibleErrorMsg(o); } - if (o.paid.equals(PaymentStatus.Trying) && System.currentTimeMillis() - o.createdTime < paymentTime) { - QueueTask qt = new QueueTask(o, TaskType.Payment,-1); + if (o.paid.equals(PaymentStatus.Trying) && System + .currentTimeMillis() - o.createdTime < paymentTime) { + QueueTask qt = new QueueTask(o, TaskType.Payment, -1); updateQueue(qt); - } + } } catch (InterruptedException e1) { e1.printStackTrace(); - } - } - return; + } + } + return; }; Retry r = new Retry(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); @@ -229,7 +235,7 @@ public void run() { r.perform(list, order); } catch (Exception e1) { e1.printStackTrace(); - } + } } }); t.start(); @@ -237,17 +243,18 @@ public void run() { private void updateQueue(QueueTask qt) throws InterruptedException { if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) { - //since payment time is lesser than queuetime it would have already failed..additional check not needed + // since payment time is lesser than queuetime it would have already failed.. + // additional check not needed LOG.trace("Order " + qt.order.id + ": Queue time for order over, failed.."); return; } else if (qt.taskType.equals(TaskType.Payment) && !qt.order.paid.equals(PaymentStatus.Trying) || qt.taskType.equals(TaskType.Messaging) && (qt.messageType == 1 && !qt.order.messageSent.equals(MessageSent.NoneSent) - || qt.order.messageSent.equals(MessageSent.PaymentFail) + || qt.order.messageSent.equals(MessageSent.PaymentFail) || qt.order.messageSent.equals(MessageSent.PaymentSuccessful)) || qt.taskType.equals(TaskType.EmployeeDb) && qt.order.addedToEmployeeHandle) { LOG.trace("Order " + qt.order.id + ": Not queueing task since task already done.."); - return; + return; } ArrayList list = queue.exceptionsList; Thread t = new Thread(new Runnable() { @@ -256,24 +263,25 @@ public void run() { Retry.Operation op = (list) -> { if (!list.isEmpty()) { LOG.warn("Order " + qt.order.id + ": Error in connecting to queue db, trying again.."); - throw list.remove(0); - } - queue.add(qt); - queueItems++; + throw list.remove(0); + } + queue.add(qt); + queueItems++; LOG.info("Order " + qt.order.id + ": " + qt.getType() + " task enqueued.."); tryDoingTasksInQueue(); - return; + return; }; - Retry.HandleErrorIssue handleError = (qt,err) -> { + Retry.HandleErrorIssue handleError = (qt, err) -> { if (qt.taskType.equals(TaskType.Payment)) { - qt.order.paid = PaymentStatus.NotDone; - sendPaymentFailureMessage(qt.order); - LOG.error("Order " + qt.order.id + ": Unable to enqueue payment task, payment failed.."); + qt.order.paid = PaymentStatus.NotDone; + sendPaymentFailureMessage(qt.order); + LOG.error("Order " + qt.order.id + ": Unable to enqueue payment task," + + " payment failed.."); } - LOG.error("Order " + qt.order.id + ": Unable to enqueue task of type " + qt.getType() + LOG.error("Order " + qt.order.id + ": Unable to enqueue task of type " + qt.getType() + ", trying to add to employee handle.."); employeeHandleIssue(qt.order); - return; + return; }; Retry r = new Retry(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); @@ -281,8 +289,8 @@ public void run() { r.perform(list, qt); } catch (Exception e1) { e1.printStackTrace(); - } - } + } + } }); t.start(); } @@ -295,13 +303,13 @@ public void run() { Retry.Operation op = (list) -> { if (!list.isEmpty()) { LOG.warn("Error in accessing queue db to do tasks, trying again.."); - throw list.remove(0); + throw list.remove(0); } doTasksInQueue(); - return; + return; }; - Retry.HandleErrorIssue handleError = (o,err) -> { - return; + Retry.HandleErrorIssue handleError = (o, err) -> { + return; }; Retry r = new Retry(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); @@ -309,8 +317,8 @@ public void run() { r.perform(list, null); } catch (Exception e1) { e1.printStackTrace(); - } - } + } + } }); t2.start(); } @@ -323,14 +331,14 @@ public void run() { Retry.Operation op = (list) -> { if (!list.isEmpty()) { LOG.warn("Error in accessing queue db to dequeue task, trying again.."); - throw list.remove(0); - } - queue.dequeue(); - queueItems--; + throw list.remove(0); + } + queue.dequeue(); + queueItems--; return; }; - Retry.HandleErrorIssue handleError = (o,err) -> { - return; + Retry.HandleErrorIssue handleError = (o, err) -> { + return; }; Retry r = new Retry(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); @@ -338,12 +346,12 @@ public void run() { r.perform(list, null); } catch (Exception e1) { e1.printStackTrace(); - } + } } }); t3.start(); } - + private void sendSuccessMessage(Order order) { if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { LOG.trace("Order " + order.id + ": Message time for order over, returning.."); @@ -359,32 +367,35 @@ public void run() { LOG.debug("Order " + order.id + ": Error in connecting to messaging service " + "(Payment Success msg), trying again.."); } else { - LOG.debug("Order " + order.id + ": Error in creating Payment Success messaging request.."); + LOG.debug("Order " + order.id + ": Error in creating Payment Success" + + " messaging request.."); } - throw l.remove(0); - } - if (!order.messageSent.equals(MessageSent.PaymentFail) + throw l.remove(0); + } + if (!order.messageSent.equals(MessageSent.PaymentFail) && !order.messageSent.equals(MessageSent.PaymentSuccessful)) { - String requestId = messagingService.receiveRequest(2); + String requestId = messagingService.receiveRequest(2); order.messageSent = MessageSent.PaymentSuccessful; - LOG.info("Order " + order.id + ": Payment Success message sent, request Id: " + requestId); - } - return; + LOG.info("Order " + order.id + ": Payment Success message sent," + + " request Id: " + requestId); + } + return; }; - Retry.HandleErrorIssue handleError = (o,err) -> { + Retry.HandleErrorIssue handleError = (o, err) -> { try { - if ((o.messageSent.equals(MessageSent.NoneSent) || o.messageSent.equals(MessageSent.PaymentTrying)) + if ((o.messageSent.equals(MessageSent.NoneSent) || o.messageSent + .equals(MessageSent.PaymentTrying)) && System.currentTimeMillis() - o.createdTime < messageTime) { - QueueTask qt = new QueueTask(order, TaskType.Messaging,2); + QueueTask qt = new QueueTask(order, TaskType.Messaging, 2); updateQueue(qt); - LOG.info("Order " + order.id + ": Error in sending Payment Success message, trying to " - + "queue task and add to employee handle.."); + LOG.info("Order " + order.id + ": Error in sending Payment Success message, trying to" + + " queue task and add to employee handle.."); employeeHandleIssue(order); } } catch (InterruptedException e1) { e1.printStackTrace(); - } - return; + } + return; }; Retry r = new Retry(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); @@ -392,8 +403,8 @@ public void run() { r.perform(list, order); } catch (Exception e1) { e1.printStackTrace(); - } - } + } + } }); t.start(); } @@ -413,32 +424,35 @@ public void run() { LOG.debug("Order " + order.id + ": Error in connecting to messaging service " + "(Payment Failure msg), trying again.."); } else { - LOG.debug("Order " + order.id + ": Error in creating Payment Failure message request.."); + LOG.debug("Order " + order.id + ": Error in creating Payment Failure" + + " message request.."); } - throw l.remove(0); - } - if (!order.messageSent.equals(MessageSent.PaymentFail) - && !order.messageSent.equals(MessageSent.PaymentSuccessful)) { - String requestId = messagingService.receiveRequest(0); + throw l.remove(0); + } + if (!order.messageSent.equals(MessageSent.PaymentFail) + && !order.messageSent.equals(MessageSent.PaymentSuccessful)) { + String requestId = messagingService.receiveRequest(0); order.messageSent = MessageSent.PaymentFail; - LOG.info("Order " + order.id + ": Payment Failure message sent successfully, request Id: " + requestId); - } - return; + LOG.info("Order " + order.id + ": Payment Failure message sent successfully," + + " request Id: " + requestId); + } + return; }; - Retry.HandleErrorIssue handleError = (o,err) -> { - if ((o.messageSent.equals(MessageSent.NoneSent) || o.messageSent.equals(MessageSent.PaymentTrying)) + Retry.HandleErrorIssue handleError = (o, err) -> { + if ((o.messageSent.equals(MessageSent.NoneSent) || o.messageSent + .equals(MessageSent.PaymentTrying)) && System.currentTimeMillis() - o.createdTime < messageTime) { try { - QueueTask qt = new QueueTask(order, TaskType.Messaging,0); + QueueTask qt = new QueueTask(order, TaskType.Messaging, 0); updateQueue(qt); LOG.warn("Order " + order.id + ": Error in sending Payment Failure message, " + "trying to queue task and add to employee handle.."); employeeHandleIssue(o); } catch (InterruptedException e1) { e1.printStackTrace(); - } - return; - } + } + return; + } }; Retry r = new Retry(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); @@ -446,8 +460,8 @@ public void run() { r.perform(list, order); } catch (Exception e1) { e1.printStackTrace(); - } - } + } + } }); t.start(); } @@ -467,31 +481,35 @@ public void run() { LOG.debug("Order " + order.id + ": Error in connecting to messaging service " + "(Payment Error msg), trying again.."); } else { - LOG.debug("Order " + order.id + ": Error in creating Payment Error messaging request.."); + LOG.debug("Order " + order.id + ": Error in creating Payment Error" + + " messaging request.."); } - throw l.remove(0); + throw l.remove(0); + } + if (order.paid.equals(PaymentStatus.Trying) && order.messageSent + .equals(MessageSent.NoneSent)) { + String requestId = messagingService.receiveRequest(1); + order.messageSent = MessageSent.PaymentTrying; + LOG.info("Order " + order.id + ": Payment Error message sent successfully," + + " request Id: " + requestId); } - if (order.paid.equals(PaymentStatus.Trying) && order.messageSent.equals(MessageSent.NoneSent)) { - String requestId = messagingService.receiveRequest(1); - order.messageSent = MessageSent.PaymentTrying; - LOG.info("Order " + order.id + ": Payment Error message sent successfully, request Id: " + requestId); - } - return; + return; }; - Retry.HandleErrorIssue handleError = (o,err) -> { + Retry.HandleErrorIssue handleError = (o, err) -> { try { - if (o.messageSent.equals(MessageSent.NoneSent) && order.paid.equals(PaymentStatus.Trying) + if (o.messageSent.equals(MessageSent.NoneSent) && order.paid + .equals(PaymentStatus.Trying) && System.currentTimeMillis() - o.createdTime < messageTime) { - QueueTask qt = new QueueTask(order,TaskType.Messaging,1); + QueueTask qt = new QueueTask(order, TaskType.Messaging, 1); updateQueue(qt); LOG.warn("Order " + order.id + ": Error in sending Payment Error message, " + "trying to queue task and add to employee handle.."); employeeHandleIssue(o); - } + } } catch (InterruptedException e1) { e1.printStackTrace(); - } - return; + } + return; }; Retry r = new Retry(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); @@ -516,28 +534,31 @@ private void employeeHandleIssue(Order order) { public void run() { Retry.Operation op = (l) -> { if (!l.isEmpty()) { - LOG.warn("Order " + order.id + ": Error in connecting to employee handle, trying again.."); - throw l.remove(0); - } + LOG.warn("Order " + order.id + ": Error in connecting to employee handle," + + " trying again.."); + throw l.remove(0); + } if (!order.addedToEmployeeHandle) { - employeeDb.receiveRequest(order); + employeeDb.receiveRequest(order); order.addedToEmployeeHandle = true; LOG.info("Order " + order.id + ": Added order to employee database"); } - return; + return; }; - Retry.HandleErrorIssue handleError = (o,err) -> { + Retry.HandleErrorIssue handleError = (o, err) -> { try { - if (!o.addedToEmployeeHandle && System.currentTimeMillis() - order.createdTime < employeeTime) { - QueueTask qt = new QueueTask(order, TaskType.EmployeeDb,-1); + if (!o.addedToEmployeeHandle && System + .currentTimeMillis() - order.createdTime < employeeTime) { + QueueTask qt = new QueueTask(order, TaskType.EmployeeDb, -1); updateQueue(qt); - LOG.warn("Order " + order.id + ": Error in adding to employee db, trying to queue task.."); + LOG.warn("Order " + order.id + ": Error in adding to employee db," + + " trying to queue task.."); return; - } + } } catch (InterruptedException e1) { e1.printStackTrace(); } - return; + return; }; Retry r = new Retry(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); @@ -558,7 +579,7 @@ private void doTasksInQueue() throws Exception { LOG.trace("Order " + qt.order.id + ": Started doing task of type " + qt.getType()); if (qt.firstAttemptTime == -1) { qt.firstAttemptTime = System.currentTimeMillis(); - } + } if (System.currentTimeMillis() - qt.firstAttemptTime >= queueTaskTime) { tryDequeue(); LOG.trace("Order " + qt.order.id + ": This queue task of type " + qt.getType() @@ -573,14 +594,15 @@ private void doTasksInQueue() throws Exception { LOG.debug("Order " + qt.order.id + ": Trying to connect to payment service.."); } } else if (qt.taskType.equals(TaskType.Messaging)) { - if (qt.order.messageSent.equals(MessageSent.PaymentFail) + if (qt.order.messageSent.equals(MessageSent.PaymentFail) || qt.order.messageSent.equals(MessageSent.PaymentSuccessful)) { tryDequeue(); LOG.trace("Order " + qt.order.id + ": This messaging task already done, dequeue.."); } else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NoneSent) || !qt.order.paid.equals(PaymentStatus.Trying))) { tryDequeue(); - LOG.trace("Order " + qt.order.id + ": This messaging task does not need to be done, dequeue.."); + LOG.trace("Order " + qt.order.id + ": This messaging task does not need to be done," + + " dequeue.."); } else if (qt.messageType == 0) { sendPaymentFailureMessage(qt.order); LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service.."); @@ -594,7 +616,8 @@ private void doTasksInQueue() throws Exception { } else if (qt.taskType.equals(TaskType.EmployeeDb)) { if (qt.order.addedToEmployeeHandle) { tryDequeue(); - LOG.trace("Order " + qt.order.id + ": This employee handle task already done, dequeue.."); + LOG.trace("Order " + qt.order.id + ": This employee handle task already done," + + " dequeue.."); } else { employeeHandleIssue(qt.order); LOG.debug("Order " + qt.order.id + ": Trying to connect to employee handle.."); diff --git a/commander/src/main/java/com/iluwatar/commander/Database.java b/commander/src/main/java/com/iluwatar/commander/Database.java index 3f850f90a8c2..ebd333e021c7 100644 --- a/commander/src/main/java/com/iluwatar/commander/Database.java +++ b/commander/src/main/java/com/iluwatar/commander/Database.java @@ -26,12 +26,14 @@ import com.iluwatar.commander.exceptions.DatabaseUnavailableException; /** - * Database abstract class is extended by all databases in our example. The add and get - * methods are used by the respective service to add to database or get from database. + * Database abstract class is extended by all databases in our example. The add and get methods are + * used by the respective service to add to database or get from database. + * * @param T is the type of object being held by database. */ public abstract class Database { public abstract T add(T obj) throws DatabaseUnavailableException; - public abstract T get(String tId) throws DatabaseUnavailableException; + + public abstract T get(String id) throws DatabaseUnavailableException; } diff --git a/commander/src/main/java/com/iluwatar/commander/Order.java b/commander/src/main/java/com/iluwatar/commander/Order.java index 20002e1b9cca..0293c478ced5 100644 --- a/commander/src/main/java/com/iluwatar/commander/Order.java +++ b/commander/src/main/java/com/iluwatar/commander/Order.java @@ -34,11 +34,15 @@ public class Order { //can store all transactions ids also enum PaymentStatus { NotDone, Trying, Done - }; - + } + + ; + enum MessageSent { NoneSent, PaymentFail, PaymentTrying, PaymentSuccessful - }; + } + + ; final User user; final String item; @@ -78,5 +82,5 @@ String createUniqueId() { } return random.toString(); } - + } diff --git a/commander/src/main/java/com/iluwatar/commander/Retry.java b/commander/src/main/java/com/iluwatar/commander/Retry.java index 7b9d06d2df75..65c92d3ef90f 100644 --- a/commander/src/main/java/com/iluwatar/commander/Retry.java +++ b/commander/src/main/java/com/iluwatar/commander/Retry.java @@ -30,29 +30,31 @@ import java.util.function.Predicate; /** - * Retry pattern + * Retry pattern. + * * @param is the type of object passed into HandleErrorIssue as a parameter. */ public class Retry { - /** - * Operation Interface will define method to be implemented. - */ + /** + * Operation Interface will define method to be implemented. + */ public interface Operation { - void operation(ArrayList list) throws Exception; + void operation(ArrayList list) throws Exception; } - /** - * HandleErrorIssue defines how to handle errors. - * @param is the type of object to be passed into the method as parameter. - */ - + /** + * HandleErrorIssue defines how to handle errors. + * + * @param is the type of object to be passed into the method as parameter. + */ + public interface HandleErrorIssue { void handleIssue(T obj, Exception e); } - + private static final Random RANDOM = new Random(); private final Operation op; @@ -64,7 +66,7 @@ public interface HandleErrorIssue { private final ArrayList errors; Retry(Operation op, HandleErrorIssue handleError, int maxAttempts, - long maxDelay, Predicate... ignoreTests) { + long maxDelay, Predicate... ignoreTests) { this.op = op; this.handleError = handleError; this.maxAttempts = maxAttempts; @@ -76,10 +78,11 @@ public interface HandleErrorIssue { /** * Performing the operation with retries. + * * @param list is the exception list - * @param obj is the parameter to be passed into handleIsuue method + * @param obj is the parameter to be passed into handleIsuue method */ - + public void perform(ArrayList list, T obj) throws Exception { do { try { @@ -92,15 +95,15 @@ public void perform(ArrayList list, T obj) throws Exception { return; //return here...dont go further } try { - long testDelay = (long) Math.pow(2, this.attempts.intValue()) * 1000 + RANDOM.nextInt(1000); + long testDelay = + (long) Math.pow(2, this.attempts.intValue()) * 1000 + RANDOM.nextInt(1000); long delay = testDelay < this.maxDelay ? testDelay : maxDelay; Thread.sleep(delay); } catch (InterruptedException f) { //ignore } } - } - while (true); + } while (true); } } diff --git a/commander/src/main/java/com/iluwatar/commander/Service.java b/commander/src/main/java/com/iluwatar/commander/Service.java index 64af79053459..ddcc2d5bf4e9 100644 --- a/commander/src/main/java/com/iluwatar/commander/Service.java +++ b/commander/src/main/java/com/iluwatar/commander/Service.java @@ -23,35 +23,37 @@ package com.iluwatar.commander; -import java.util.*; - import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; +import java.util.Random; /** - * Service class is an abstract class extended by all services in this example. They - * all have a public receiveRequest method to receive requests, which could also contain - * details of the user other than the implementation details (though we are not doing - * that here) and updateDb method which adds to their respective databases. There is a - * method to generate transaction/request id for the transactions/requests, which are - * then sent back. These could be stored by the {@link Commander} class in a separate - * database for reference (though we are not doing that here). + * Service class is an abstract class extended by all services in this example. They all have a + * public receiveRequest method to receive requests, which could also contain details of the user + * other than the implementation details (though we are not doing that here) and updateDb method + * which adds to their respective databases. There is a method to generate transaction/request id + * for the transactions/requests, which are then sent back. These could be stored by the {@link + * Commander} class in a separate database for reference (though we are not doing that here). */ public abstract class Service { - + protected final Database database; public ArrayList exceptionsList; private static final Random RANDOM = new Random(); private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; private static final Hashtable USED_IDS = new Hashtable<>(); - protected Service(Database db, Exception...exc) { + protected Service(Database db, Exception... exc) { this.database = db; this.exceptionsList = new ArrayList<>(List.of(exc)); } - public abstract String receiveRequest(Object...parameters) throws DatabaseUnavailableException; - protected abstract String updateDb(Object...parameters) throws DatabaseUnavailableException; + public abstract String receiveRequest(Object... parameters) throws DatabaseUnavailableException; + + protected abstract String updateDb(Object... parameters) throws DatabaseUnavailableException; protected String generateId() { StringBuilder random = new StringBuilder(); diff --git a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java index 0626e5ce0983..3f5b7bcc0c2c 100644 --- a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java @@ -23,10 +23,10 @@ package com.iluwatar.commander.employeehandle; -import java.util.Hashtable; import com.iluwatar.commander.Database; import com.iluwatar.commander.Order; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import java.util.Hashtable; /** * The Employee Database is where orders which have encountered some issue(s) are added. @@ -41,11 +41,11 @@ public EmployeeDatabase() { @Override public Order add(Order o) throws DatabaseUnavailableException { - return data.put(o.id,o); + return data.put(o.id, o); } @Override - public Order get(String oId) throws DatabaseUnavailableException { - return data.get(oId); + public Order get(String orderId) throws DatabaseUnavailableException { + return data.get(orderId); } } diff --git a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java index ed3e36d7c24c..9f4d8fb483a8 100644 --- a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java +++ b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java @@ -28,21 +28,21 @@ import com.iluwatar.commander.exceptions.DatabaseUnavailableException; /** - * The EmployeeHandle class is the middle-man between {@link Commander} and - * {@link EmployeeDatabase}. + * The EmployeeHandle class is the middle-man between {@link Commander} and {@link + * EmployeeDatabase}. */ public class EmployeeHandle extends Service { - public EmployeeHandle(EmployeeDatabase db, Exception...exc) { + public EmployeeHandle(EmployeeDatabase db, Exception... exc) { super(db, exc); } - public String receiveRequest(Object...parameters) throws DatabaseUnavailableException { - return updateDb((Order)parameters[0]); + public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { + return updateDb((Order) parameters[0]); } - protected String updateDb(Object...parameters) throws DatabaseUnavailableException { + protected String updateDb(Object... parameters) throws DatabaseUnavailableException { Order o = (Order) parameters[0]; if (database.get(o.id) == null) { database.add(o); diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java index 71254fb317c1..8997b1a10a2d 100644 --- a/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java @@ -24,8 +24,8 @@ package com.iluwatar.commander.exceptions; /** - * DatabaseUnavailableException is thrown when database is unavailable and nothing - * can be added or retrieved. + * DatabaseUnavailableException is thrown when database is unavailable and nothing can be added or + * retrieved. */ public class DatabaseUnavailableException extends Exception { diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java index 306cf4c18bda..eb7c0fb3fd35 100644 --- a/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java @@ -24,8 +24,8 @@ package com.iluwatar.commander.exceptions; /** - * PaymentDetailsErrorException is thrown when the details entered are incorrect or - * payment cannot be made with the details given. + * PaymentDetailsErrorException is thrown when the details entered are incorrect or payment cannot + * be made with the details given. */ public class PaymentDetailsErrorException extends Exception { diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java index 8c2b5334121b..b374f2a7d65c 100644 --- a/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java @@ -24,8 +24,8 @@ package com.iluwatar.commander.exceptions; /** - * ShippingNotPossibleException is thrown when the address entered cannot be shipped to - * by service currently for some reason. + * ShippingNotPossibleException is thrown when the address entered cannot be shipped to by service + * currently for some reason. */ public class ShippingNotPossibleException extends Exception { diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java index 7078726bee2a..45bd1e23a9f3 100644 --- a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java @@ -23,10 +23,10 @@ package com.iluwatar.commander.messagingservice; -import java.util.Hashtable; import com.iluwatar.commander.Database; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.messagingservice.MessagingService.MessageRequest; +import java.util.Hashtable; /** * The MessagingDatabase is where the MessageRequest is added. @@ -45,8 +45,8 @@ public MessageRequest add(MessageRequest r) throws DatabaseUnavailableException } @Override - public MessageRequest get(String rId) throws DatabaseUnavailableException { - return data.get(rId); + public MessageRequest get(String requestId) throws DatabaseUnavailableException { + return data.get(requestId); } } diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java index 2742dfd5d9e7..1dcdac926de3 100644 --- a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java +++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java @@ -29,9 +29,9 @@ import org.slf4j.LoggerFactory; /** - * The MessagingService is used to send messages to user regarding their order and - * payment status. In case an error is encountered in payment and this service is - * found to be unavailable, the order is added to the {@link EmployeeDatabase}. + * The MessagingService is used to send messages to user regarding their order and payment status. + * In case an error is encountered in payment and this service is found to be unavailable, the order + * is added to the {@link EmployeeDatabase}. */ public class MessagingService extends Service { @@ -39,7 +39,9 @@ public class MessagingService extends Service { enum MessageToSend { PaymentFail, PaymentTrying, PaymentSuccessful - }; + } + + ; class MessageRequest { String reqId; @@ -51,17 +53,16 @@ class MessageRequest { } } - public MessagingService(MessagingDatabase db, Exception...exc) { + public MessagingService(MessagingDatabase db, Exception... exc) { super(db, exc); } /** * Public method which will receive request from {@link Commander}. */ - - public String receiveRequest(Object...parameters) throws DatabaseUnavailableException { + public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { int messageToSend = (int) parameters[0]; - String rId = generateId(); + String id = generateId(); MessageToSend msg = null; if (messageToSend == 0) { msg = MessageToSend.PaymentFail; @@ -70,11 +71,11 @@ public String receiveRequest(Object...parameters) throws DatabaseUnavailableExce } else { //messageToSend == 2 msg = MessageToSend.PaymentSuccessful; } - MessageRequest req = new MessageRequest(rId, msg); + MessageRequest req = new MessageRequest(id, msg); return updateDb(req); } - protected String updateDb(Object...parameters) throws DatabaseUnavailableException { + protected String updateDb(Object... parameters) throws DatabaseUnavailableException { MessageRequest req = (MessageRequest) parameters[0]; if (this.database.get(req.reqId) == null) { //idempotence, in case db fails here database.add(req); //if successful: @@ -86,13 +87,17 @@ protected String updateDb(Object...parameters) throws DatabaseUnavailableExcepti String sendMessage(MessageToSend m) { if (m.equals(MessageToSend.PaymentSuccessful)) { - return "Msg: Your order has been placed and paid for successfully! Thank you for shopping with us!"; + return "Msg: Your order has been placed and paid for successfully!" + + " Thank you for shopping with us!"; } else if (m.equals(MessageToSend.PaymentTrying)) { - return "Msg: There was an error in your payment process, we are working on it and will return back to you" - + " shortly. Meanwhile, your order has been placed and will be shipped."; + return "Msg: There was an error in your payment process," + + " we are working on it and will return back to you shortly." + + " Meanwhile, your order has been placed and will be shipped."; } else { - return "Msg: There was an error in your payment process. Your order is placed and has been converted to COD." - + " Please reach us on CUSTOMER-CARE-NUBER in case of any queries. Thank you for shopping with us!"; + return "Msg: There was an error in your payment process." + + " Your order is placed and has been converted to COD." + + " Please reach us on CUSTOMER-CARE-NUBER in case of any queries." + + " Thank you for shopping with us!"; } } } diff --git a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java index b597abe68af5..ed308dbfbd03 100644 --- a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java @@ -23,11 +23,10 @@ package com.iluwatar.commander.paymentservice; -import java.util.Hashtable; - import com.iluwatar.commander.Database; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.paymentservice.PaymentService.PaymentRequest; +import java.util.Hashtable; /** * PaymentDatabase is where the PaymentRequest is added, along with details. @@ -48,8 +47,8 @@ public PaymentRequest add(PaymentRequest r) throws DatabaseUnavailableException } @Override - public PaymentRequest get(String tId) throws DatabaseUnavailableException { - return data.get(tId); + public PaymentRequest get(String requestId) throws DatabaseUnavailableException { + return data.get(requestId); } } diff --git a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java index 9abb15db2253..95ca92a65ea0 100644 --- a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java +++ b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java @@ -27,8 +27,8 @@ import com.iluwatar.commander.exceptions.DatabaseUnavailableException; /** - * The PaymentService class receives request from the {@link Commander} and adds - * to the {@link PaymentDatabase}. + * The PaymentService class receives request from the {@link Commander} and adds to the {@link + * PaymentDatabase}. */ public class PaymentService extends Service { @@ -45,22 +45,22 @@ class PaymentRequest { } } - public PaymentService(PaymentDatabase db, Exception...exc) { + public PaymentService(PaymentDatabase db, Exception... exc) { super(db, exc); } /** * Public method which will receive request from {@link Commander}. */ - - public String receiveRequest(Object...parameters) throws DatabaseUnavailableException { + + public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { //it could also be sending a userid, payment details here or something, not added here - String tId = generateId(); - PaymentRequest req = new PaymentRequest(tId, (float)parameters[0]); + String id = generateId(); + PaymentRequest req = new PaymentRequest(id, (float) parameters[0]); return updateDb(req); } - protected String updateDb(Object...parameters) throws DatabaseUnavailableException { + protected String updateDb(Object... parameters) throws DatabaseUnavailableException { PaymentRequest req = (PaymentRequest) parameters[0]; if (database.get(req.transactionId) == null || !req.paid) { database.add(req); diff --git a/commander/src/main/java/com/iluwatar/commander/queue/Queue.java b/commander/src/main/java/com/iluwatar/commander/queue/Queue.java index 16fdaa88323e..1770e6c0546f 100644 --- a/commander/src/main/java/com/iluwatar/commander/queue/Queue.java +++ b/commander/src/main/java/com/iluwatar/commander/queue/Queue.java @@ -27,6 +27,7 @@ /** * Queue data structure implementation. + * * @param is the type of object the queue will hold. */ @@ -47,15 +48,14 @@ class Node { } /** - * Queue constructor + * Queue constructor. */ - Queue() { front = null; rear = null; size = 0; } - + boolean isEmpty() { if (size == 0) { return true; @@ -63,7 +63,7 @@ boolean isEmpty() { return false; } } - + void enqueue(T obj) { if (front == null) { front = new Node(obj, null); @@ -75,7 +75,7 @@ void enqueue(T obj) { } size++; } - + T dequeue() throws IsEmptyException { if (isEmpty()) { throw new IsEmptyException(); @@ -86,12 +86,12 @@ T dequeue() throws IsEmptyException { return (T) temp.value; } } - + T peek() throws IsEmptyException { if (isEmpty()) { throw new IsEmptyException(); } else { - return (T)front.value; + return (T) front.value; } } } diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java index 6b9007b9fd36..3874cc27da70 100644 --- a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java @@ -26,7 +26,6 @@ import com.iluwatar.commander.Database; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.exceptions.IsEmptyException; - import java.util.ArrayList; import java.util.List; @@ -39,7 +38,7 @@ public class QueueDatabase extends Database { private Queue data; public ArrayList exceptionsList; - public QueueDatabase(Exception...exc) { + public QueueDatabase(Exception... exc) { this.data = new Queue<>(); this.exceptionsList = new ArrayList<>(List.of(exc)); } @@ -52,31 +51,33 @@ public QueueTask add(QueueTask t) throws DatabaseUnavailableException { } /** - * peek method returns object at front without removing it from queue + * peek method returns object at front without removing it from queue. + * * @return object at front of queue - * @throws IsEmptyException if queue is empty + * @throws IsEmptyException if queue is empty * @throws DatabaseUnavailableException if queue db is unavailable */ - + public QueueTask peek() throws IsEmptyException, DatabaseUnavailableException { QueueTask qt = this.data.peek(); return qt; } /** - * dequeue method removes the object at front and returns it + * dequeue method removes the object at front and returns it. + * * @return object at front of queue - * @throws IsEmptyException if queue is empty + * @throws IsEmptyException if queue is empty * @throws DatabaseUnavailableException if queue db is unavailable */ - + public QueueTask dequeue() throws IsEmptyException, DatabaseUnavailableException { QueueTask qt = this.data.dequeue(); return qt; } @Override - public QueueTask get(String tId) throws DatabaseUnavailableException { + public QueueTask get(String taskId) throws DatabaseUnavailableException { return null; } diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java index 206b2daf1416..f8ba09fc1ad6 100644 --- a/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java +++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java @@ -31,13 +31,15 @@ public class QueueTask { -/** - * TaskType is the type of task to be done. - */ + /** + * TaskType is the type of task to be done. + */ public enum TaskType { Messaging, Payment, EmployeeDb - }; + } + + ; public Order order; public TaskType taskType; @@ -46,26 +48,28 @@ public enum TaskType { but keeping it simple here*/ public long firstAttemptTime; //when first time attempt made to do task -/** - * QueueTask constructor - * @param o is the order for which the queuetask is being created - * @param t is the type of task to be done - * @param messageType if it is a message, which type of message - this could have instead been object varargs, - * and contained all additional details related to tasktype. - */ - + /** + * QueueTask constructor. + * + * @param o is the order for which the queuetask is being created + * @param t is the type of task to be done + * @param messageType if it is a message, which type of message - this could have instead been + * object varargs, and contained all additional details related to tasktype. + */ + public QueueTask(Order o, TaskType t, int messageType) { this.order = o; this.taskType = t; this.messageType = messageType; this.firstAttemptTime = -1; } - + /** - * getType method + * getType method. + * * @return String representing type of task */ - + public String getType() { if (!this.taskType.equals(TaskType.Messaging)) { return this.taskType.toString(); diff --git a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java index fd2bf79968e2..a45dd00e16d5 100644 --- a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java @@ -23,17 +23,17 @@ package com.iluwatar.commander.shippingservice; -import java.util.Hashtable; import com.iluwatar.commander.Database; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.shippingservice.ShippingService.ShippingRequest; +import java.util.Hashtable; /** * ShippingDatabase is where the ShippingRequest objects are added. */ public class ShippingDatabase extends Database { - + private Hashtable data; public ShippingDatabase() { @@ -45,8 +45,8 @@ public ShippingRequest add(ShippingRequest r) throws DatabaseUnavailableExceptio return data.put(r.transactionId, r); } - public ShippingRequest get(String transactionId) throws DatabaseUnavailableException { - return data.get(transactionId); + public ShippingRequest get(String trasnactionId) throws DatabaseUnavailableException { + return data.get(trasnactionId); } } diff --git a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java index a14690306fcd..6539316b1e12 100644 --- a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java +++ b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java @@ -27,8 +27,8 @@ import com.iluwatar.commander.exceptions.DatabaseUnavailableException; /** - * ShippingService class receives request from {@link Commander} class and adds it - * to the {@link ShippingDatabase}. + * ShippingService class receives request from {@link Commander} class and adds it to the {@link + * ShippingDatabase}. */ public class ShippingService extends Service { @@ -45,21 +45,22 @@ class ShippingRequest { } } - public ShippingService(ShippingDatabase db, Exception...exc) { + public ShippingService(ShippingDatabase db, Exception... exc) { super(db, exc); } /** * Public method which will receive request from {@link Commander}. */ - - public String receiveRequest(Object...parameters) throws DatabaseUnavailableException { - String tId = generateId(); - ShippingRequest req = new ShippingRequest(tId, (String) parameters[0] /*item*/, (String) parameters[1]/*address*/); + + public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { + String id = generateId(); + ShippingRequest req = + new ShippingRequest(id, (String) parameters[0] /*item*/, (String) parameters[1]/*address*/); return updateDb(req); } - protected String updateDb(Object...parameters) throws DatabaseUnavailableException { + protected String updateDb(Object... parameters) throws DatabaseUnavailableException { ShippingRequest req = (ShippingRequest) parameters[0]; if (this.database.get(req.transactionId) == null) { database.add(req); From 4f9ee0189c614085841668540b5350b66a85a927 Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 22:09:27 +0530 Subject: [PATCH 06/32] Resolves checkstyle errors for converter, cqrs (#1063) * Reduces checkstyle errors in converter * Reduces checkstyle errors in cqrs --- .../main/java/com/iluwatar/converter/App.java | 7 ++- .../com/iluwatar/converter/Converter.java | 31 ++++++++---- .../java/com/iluwatar/converter/User.java | 19 ++++--- .../com/iluwatar/converter/UserConverter.java | 4 +- .../java/com/iluwatar/converter/UserDto.java | 18 ++++--- .../main/java/com/iluwatar/cqrs/app/App.java | 50 +++++++++---------- .../cqrs/commandes/CommandServiceImpl.java | 11 ++-- .../cqrs/commandes/ICommandService.java | 3 +- .../iluwatar/cqrs/constants/AppConstants.java | 4 +- .../iluwatar/cqrs/domain/model/Author.java | 13 ++--- .../com/iluwatar/cqrs/domain/model/Book.java | 14 +++--- .../java/com/iluwatar/cqrs/dto/Author.java | 19 +++---- .../main/java/com/iluwatar/cqrs/dto/Book.java | 13 ++--- .../iluwatar/cqrs/queries/IQueryService.java | 9 ++-- .../cqrs/queries/QueryServiceImpl.java | 34 ++++++------- .../com/iluwatar/cqrs/util/HibernateUtil.java | 7 +-- 16 files changed, 129 insertions(+), 127 deletions(-) diff --git a/converter/src/main/java/com/iluwatar/converter/App.java b/converter/src/main/java/com/iluwatar/converter/App.java index fab472328afd..935fc4f19943 100644 --- a/converter/src/main/java/com/iluwatar/converter/App.java +++ b/converter/src/main/java/com/iluwatar/converter/App.java @@ -23,12 +23,10 @@ package com.iluwatar.converter; - +import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; - /** * The Converter pattern is a behavioral design pattern which allows a common way of bidirectional * conversion between corresponding types (e.g. DTO and domain representations of the logically @@ -38,8 +36,9 @@ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** - * Program entry point + * Program entry point. * * @param args command line args */ diff --git a/converter/src/main/java/com/iluwatar/converter/Converter.java b/converter/src/main/java/com/iluwatar/converter/Converter.java index 256acec24942..10425e1ca907 100644 --- a/converter/src/main/java/com/iluwatar/converter/Converter.java +++ b/converter/src/main/java/com/iluwatar/converter/Converter.java @@ -30,8 +30,9 @@ /** * Generic converter, thanks to Java8 features not only provides a way of generic bidirectional - * conversion between corresponding types, but also a common way of converting a collection of objects - * of the same type, reducing boilerplate code to the absolute minimum. + * conversion between corresponding types, but also a common way of converting a collection of + * objects of the same type, reducing boilerplate code to the absolute minimum. + * * @param DTO representation's type * @param Domain representation's type */ @@ -41,7 +42,9 @@ public class Converter { private final Function fromEntity; /** - * @param fromDto Function that converts given dto entity into the domain entity. + * Constructor. + * + * @param fromDto Function that converts given dto entity into the domain entity. * @param fromEntity Function that converts given domain entity into the dto entity. */ public Converter(final Function fromDto, final Function fromEntity) { @@ -50,34 +53,44 @@ public Converter(final Function fromDto, final Function fromEntity) } /** + * Converts DTO to Entity. + * * @param dto DTO entity - * @return The domain representation - the result of the converting function application on dto entity. + * @return The domain representation - the result of the converting function application on dto + * entity. */ public final U convertFromDto(final T dto) { return fromDto.apply(dto); } /** + * Converts Entity to DTO. + * * @param entity domain entity - * @return The DTO representation - the result of the converting function application on domain entity. + * @return The DTO representation - the result of the converting function application on domain + * entity. */ public final T convertFromEntity(final U entity) { return fromEntity.apply(entity); } /** + * Converts list of DTOs to list of Entities. + * * @param dtos collection of DTO entities - * @return List of domain representation of provided entities retrieved by - * mapping each of them with the conversion function + * @return List of domain representation of provided entities retrieved by mapping each of them + * with the conversion function */ public final List createFromDtos(final Collection dtos) { return dtos.stream().map(this::convertFromDto).collect(Collectors.toList()); } /** + * Converts list of Entities to list of DTOs. + * * @param entities collection of domain entities - * @return List of domain representation of provided entities retrieved by - * mapping each of them with the conversion function + * @return List of domain representation of provided entities retrieved by mapping each of them + * with the conversion function */ public final List createFromEntities(final Collection entities) { return entities.stream().map(this::convertFromEntity).collect(Collectors.toList()); diff --git a/converter/src/main/java/com/iluwatar/converter/User.java b/converter/src/main/java/com/iluwatar/converter/User.java index 05d7313e000a..ae5e89f7c9a1 100644 --- a/converter/src/main/java/com/iluwatar/converter/User.java +++ b/converter/src/main/java/com/iluwatar/converter/User.java @@ -26,7 +26,7 @@ import java.util.Objects; /** - * User class + * User class. */ public class User { private String firstName; @@ -35,10 +35,12 @@ public class User { private String userId; /** + * Constructor. + * * @param firstName user's first name * @param lastName user's last name * @param isActive flag indicating whether the user is active - * @param userId user's identificator + * @param userId user's identificator */ public User(String firstName, String lastName, boolean isActive, String userId) { this.firstName = firstName; @@ -63,7 +65,8 @@ public String getUserId() { return userId; } - @Override public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if (this == o) { return true; } @@ -72,15 +75,17 @@ public String getUserId() { } User user = (User) o; return isActive == user.isActive && Objects.equals(firstName, user.firstName) && Objects - .equals(lastName, user.lastName) && Objects.equals(userId, user.userId); + .equals(lastName, user.lastName) && Objects.equals(userId, user.userId); } - @Override public int hashCode() { + @Override + public int hashCode() { return Objects.hash(firstName, lastName, isActive, userId); } - @Override public String toString() { + @Override + public String toString() { return "User{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' - + ", isActive=" + isActive + ", userId='" + userId + '\'' + '}'; + + ", isActive=" + isActive + ", userId='" + userId + '\'' + '}'; } } diff --git a/converter/src/main/java/com/iluwatar/converter/UserConverter.java b/converter/src/main/java/com/iluwatar/converter/UserConverter.java index d26703cc2c63..8637c042d48f 100644 --- a/converter/src/main/java/com/iluwatar/converter/UserConverter.java +++ b/converter/src/main/java/com/iluwatar/converter/UserConverter.java @@ -33,8 +33,8 @@ public class UserConverter extends Converter { */ public UserConverter() { super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), - userDto.getEmail()), + userDto.getEmail()), user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), - user.getUserId())); + user.getUserId())); } } diff --git a/converter/src/main/java/com/iluwatar/converter/UserDto.java b/converter/src/main/java/com/iluwatar/converter/UserDto.java index 11413d2cb61b..eae77e90130e 100644 --- a/converter/src/main/java/com/iluwatar/converter/UserDto.java +++ b/converter/src/main/java/com/iluwatar/converter/UserDto.java @@ -23,11 +23,10 @@ package com.iluwatar.converter; - import java.util.Objects; /** - * User DTO class + * User DTO class. */ public class UserDto { @@ -37,6 +36,8 @@ public class UserDto { private String email; /** + * Constructor. + * * @param firstName user's first name * @param lastName user's last name * @param isActive flag indicating whether the user is active @@ -65,7 +66,8 @@ public String getEmail() { return email; } - @Override public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if (this == o) { return true; } @@ -74,15 +76,17 @@ public String getEmail() { } UserDto userDto = (UserDto) o; return isActive == userDto.isActive && Objects.equals(firstName, userDto.firstName) && Objects - .equals(lastName, userDto.lastName) && Objects.equals(email, userDto.email); + .equals(lastName, userDto.lastName) && Objects.equals(email, userDto.email); } - @Override public int hashCode() { + @Override + public int hashCode() { return Objects.hash(firstName, lastName, isActive, email); } - @Override public String toString() { + @Override + public String toString() { return "UserDto{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' - + ", isActive=" + isActive + ", email='" + email + '\'' + '}'; + + ", isActive=" + isActive + ", email='" + email + '\'' + '}'; } } diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java b/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java index 0a805679f2b8..b1b0ddeac9ea 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java @@ -23,12 +23,6 @@ package com.iluwatar.cqrs.app; -import java.math.BigInteger; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.iluwatar.cqrs.commandes.CommandServiceImpl; import com.iluwatar.cqrs.commandes.ICommandService; import com.iluwatar.cqrs.constants.AppConstants; @@ -37,32 +31,35 @@ import com.iluwatar.cqrs.queries.IQueryService; import com.iluwatar.cqrs.queries.QueryServiceImpl; import com.iluwatar.cqrs.util.HibernateUtil; +import java.math.BigInteger; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * CQRS : Command Query Responsibility Segregation. A pattern used to separate query services from commands or writes - * services. The pattern is very simple but it has many consequences. For example, it can be used to tackle down a - * complex domain, or to use other architectures that were hard to implement with the classical way. - * - * This implementation is an example of managing books and authors in a library. The persistence of books and authors is - * done according to the CQRS architecture. A command side that deals with a data model to persist(insert,update,delete) - * objects to a database. And a query side that uses native queries to get data from the database and return objects as - * DTOs (Data transfer Objects). + * CQRS : Command Query Responsibility Segregation. A pattern used to separate query services from + * commands or writes services. The pattern is very simple but it has many consequences. For + * example, it can be used to tackle down a complex domain, or to use other architectures that were + * hard to implement with the classical way. * + *

This implementation is an example of managing books and authors in a library. The persistence + * of books and authors is done according to the CQRS architecture. A command side that deals with a + * data model to persist(insert,update,delete) objects to a database. And a query side that uses + * native queries to get data from the database and return objects as DTOs (Data transfer Objects). */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * - * @param args - * command line args + * Program entry point. + * + * @param args command line args */ public static void main(String[] args) { ICommandService commands = new CommandServiceImpl(); // Create Authors and Books using CommandService - commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "eEvans@email.com"); + commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "evans@email.com"); commands.authorCreated(AppConstants.J_BLOCH, "Joshua Bloch", "jBloch@email.com"); commands.authorCreated(AppConstants.M_FOWLER, "Martin Fowler", "mFowler@email.com"); @@ -70,7 +67,8 @@ public static void main(String[] args) { commands.bookAddedToAuthor("Effective Java", 40.54, AppConstants.J_BLOCH); commands.bookAddedToAuthor("Java Puzzlers", 39.99, AppConstants.J_BLOCH); commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, AppConstants.J_BLOCH); - commands.bookAddedToAuthor("Patterns of Enterprise Application Architecture", 54.01, AppConstants.M_FOWLER); + commands.bookAddedToAuthor("Patterns of Enterprise" + + " Application Architecture", 54.01, AppConstants.M_FOWLER); commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER); commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans"); @@ -78,18 +76,18 @@ public static void main(String[] args) { // Query the database using QueryService Author nullAuthor = queries.getAuthorByUsername("username"); - Author eEvans = queries.getAuthorByUsername(AppConstants.E_EVANS); - BigInteger jBlochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH); + Author evans = queries.getAuthorByUsername(AppConstants.E_EVANS); + BigInteger blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH); BigInteger authorsCount = queries.getAuthorsCount(); Book dddBook = queries.getBook("Domain-Driven Design"); - List jBlochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH); + List blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH); LOGGER.info("Author username : {}", nullAuthor); - LOGGER.info("Author eEvans : {}", eEvans); - LOGGER.info("jBloch number of books : {}", jBlochBooksCount); + LOGGER.info("Author evans : {}", evans); + LOGGER.info("jBloch number of books : {}", blochBooksCount); LOGGER.info("Number of authors : {}", authorsCount); LOGGER.info("DDD book : {}", dddBook); - LOGGER.info("jBloch books : {}", jBlochBooks); + LOGGER.info("jBloch books : {}", blochBooks); HibernateUtil.getSessionFactory().close(); } diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java index e491e8990a7a..c8146845e33b 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java @@ -23,17 +23,16 @@ package com.iluwatar.cqrs.commandes; -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; - import com.iluwatar.cqrs.domain.model.Author; import com.iluwatar.cqrs.domain.model.Book; import com.iluwatar.cqrs.util.HibernateUtil; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; /** - * This class is an implementation of {@link ICommandService} interface. It uses Hibernate as an api for persistence. - * + * This class is an implementation of {@link ICommandService} interface. It uses Hibernate as an api + * for persistence. */ public class CommandServiceImpl implements ICommandService { diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java index 7e0a47bc3150..b81d24c7c580 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java @@ -24,8 +24,7 @@ package com.iluwatar.cqrs.commandes; /** - * This interface represents the commands of the CQRS pattern - * + * This interface represents the commands of the CQRS pattern. */ public interface ICommandService { diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java b/cqrs/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java index c52a71401205..0a8971729ef5 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java @@ -24,9 +24,7 @@ package com.iluwatar.cqrs.constants; /** - * - * Class to define the constants - * + * Class to define the constants. */ public class AppConstants { diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java index 0c0d4b65b285..9f2b73e486fd 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java @@ -30,7 +30,6 @@ /** * This is an Author entity. It is used by Hibernate for persistence. - * */ @Entity public class Author { @@ -42,13 +41,11 @@ public class Author { private String email; /** - * - * @param username - * username of the author - * @param name - * name of the author - * @param email - * email of the author + * Constructor. + * + * @param username username of the author + * @param name name of the author + * @param email email of the author */ public Author(String username, String name, String email) { this.username = username; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java index 0524991f80a6..8b87bdbf4301 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java @@ -30,8 +30,8 @@ import javax.persistence.ManyToOne; /** - * This is a Book entity. It is used by Hibernate for persistence. Many books can be written by one {@link Author} - * + * This is a Book entity. It is used by Hibernate for persistence. Many books can be written by one + * {@link Author} */ @Entity public class Book { @@ -44,13 +44,11 @@ public class Book { private Author author; /** + * Constructor. * - * @param title - * title of the book - * @param price - * price of the book - * @param author - * author of the book + * @param title title of the book + * @param price price of the book + * @param author author of the book */ public Book(String title, double price, Author author) { this.title = title; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java index f20627ba9dea..8318c4a951f3 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java @@ -26,9 +26,7 @@ import java.util.Objects; /** - * - * This is a DTO (Data Transfer Object) author, contains only useful information to be returned - * + * This is a DTO (Data Transfer Object) author, contains only useful information to be returned. */ public class Author { @@ -37,13 +35,11 @@ public class Author { private String username; /** - * - * @param name - * name of the author - * @param email - * email of the author - * @param username - * username of the author + * Constructor. + * + * @param name name of the author + * @param email email of the author + * @param username username of the author */ public Author(String name, String email, String username) { this.name = name; @@ -85,7 +81,8 @@ public boolean equals(Object obj) { return false; } Author other = (Author) obj; - return username.equals(other.getUsername()) && email.equals(other.getEmail()) && name.equals(other.getName()); + return username.equals(other.getUsername()) && email.equals(other.getEmail()) && name + .equals(other.getName()); } diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java index 47ee03581020..c859b0c769dd 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java @@ -26,9 +26,7 @@ import java.util.Objects; /** - * - * This is a DTO (Data Transfer Object) book, contains only useful information to be returned - * + * This is a DTO (Data Transfer Object) book, contains only useful information to be returned. */ public class Book { @@ -36,11 +34,10 @@ public class Book { private double price; /** - * - * @param title - * title of the book - * @param price - * price of the book + * Constructor. + * + * @param title title of the book + * @param price price of the book */ public Book(String title, double price) { this.title = title; diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java b/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java index 303b69e7c322..e67371bc723a 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java @@ -23,16 +23,13 @@ package com.iluwatar.cqrs.queries; -import java.math.BigInteger; -import java.util.List; - import com.iluwatar.cqrs.dto.Author; import com.iluwatar.cqrs.dto.Book; +import java.math.BigInteger; +import java.util.List; /** - * - * This interface represents the query methods of the CQRS pattern - * + * This interface represents the query methods of the CQRS pattern. */ public interface IQueryService { diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java b/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java index 57895c945436..24532515d412 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java @@ -23,23 +23,20 @@ package com.iluwatar.cqrs.queries; +import com.iluwatar.cqrs.constants.AppConstants; +import com.iluwatar.cqrs.dto.Author; +import com.iluwatar.cqrs.dto.Book; +import com.iluwatar.cqrs.util.HibernateUtil; import java.math.BigInteger; import java.util.List; - import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.transform.Transformers; -import com.iluwatar.cqrs.constants.AppConstants; -import com.iluwatar.cqrs.dto.Author; -import com.iluwatar.cqrs.dto.Book; -import com.iluwatar.cqrs.util.HibernateUtil; - /** - * This class is an implementation of {@link IQueryService}. It uses Hibernate native queries to return DTOs from the - * database. - * + * This class is an implementation of {@link IQueryService}. It uses Hibernate native queries to + * return DTOs from the database. */ public class QueryServiceImpl implements IQueryService { @@ -49,11 +46,12 @@ public class QueryServiceImpl implements IQueryService { public Author getAuthorByUsername(String username) { Author authorDTo = null; try (Session session = sessionFactory.openSession()) { - SQLQuery sqlQuery = session - .createSQLQuery("SELECT a.username as \"username\", a.name as \"name\", a.email as \"email\"" - + "FROM Author a where a.username=:username"); + SQLQuery sqlQuery = session.createSQLQuery("SELECT a.username as \"username\"," + + " a.name as \"name\", a.email as \"email\"" + + "FROM Author a where a.username=:username"); sqlQuery.setParameter(AppConstants.USER_NAME, username); - authorDTo = (Author) sqlQuery.setResultTransformer(Transformers.aliasToBean(Author.class)).uniqueResult(); + authorDTo = (Author) sqlQuery.setResultTransformer(Transformers.aliasToBean(Author.class)) + .uniqueResult(); } return authorDTo; } @@ -62,10 +60,11 @@ public Author getAuthorByUsername(String username) { public Book getBook(String title) { Book bookDTo = null; try (Session session = sessionFactory.openSession()) { - SQLQuery sqlQuery = session - .createSQLQuery("SELECT b.title as \"title\", b.price as \"price\"" + " FROM Book b where b.title=:title"); + SQLQuery sqlQuery = session.createSQLQuery("SELECT b.title as \"title\"," + + " b.price as \"price\"" + " FROM Book b where b.title=:title"); sqlQuery.setParameter("title", title); - bookDTo = (Book) sqlQuery.setResultTransformer(Transformers.aliasToBean(Book.class)).uniqueResult(); + bookDTo = + (Book) sqlQuery.setResultTransformer(Transformers.aliasToBean(Book.class)).uniqueResult(); } return bookDTo; } @@ -87,7 +86,8 @@ public BigInteger getAuthorBooksCount(String username) { BigInteger bookcount = null; try (Session session = sessionFactory.openSession()) { SQLQuery sqlQuery = session.createSQLQuery( - "SELECT count(b.title)" + " FROM Book b, Author a where b.author_id = a.id and a.username=:username"); + "SELECT count(b.title)" + " FROM Book b, Author a" + + " where b.author_id = a.id and a.username=:username"); sqlQuery.setParameter(AppConstants.USER_NAME, username); bookcount = (BigInteger) sqlQuery.uniqueResult(); } diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java b/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java index 7737ded33e9d..6d9788a5efe0 100644 --- a/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java +++ b/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java @@ -31,8 +31,8 @@ import org.slf4j.LoggerFactory; /** - * This class simply returns one instance of {@link SessionFactory} initialized when the application is started - * + * This class simply returns one instance of {@link SessionFactory} initialized when the application + * is started. */ public class HibernateUtil { @@ -42,7 +42,8 @@ public class HibernateUtil { private static SessionFactory buildSessionFactory() { // configures settings from hibernate.cfg.xml - final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build(); + final StandardServiceRegistry registry = + new StandardServiceRegistryBuilder().configure().build(); try { return new MetadataSources(registry).buildMetadata().buildSessionFactory(); } catch (Exception ex) { From dda09535e657ef6b4e2fde8f0c72e1f93b1429ac Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 22:31:32 +0530 Subject: [PATCH 07/32] Resolves checkstyle errors for guarded-suspension, half-sync-half-async, hexagonal (#1064) * Reduces checkstyle errors in guarded-suspension * Reduces checkstyle errors in half-sync-half-async * Reduces checkstyle errors in hexagonal --- .../com/iluwatar/guarded/suspension/App.java | 25 +++-- .../guarded/suspension/GuardedQueue.java | 16 ++- .../com/iluwatar/halfsynchalfasync/App.java | 64 +++++------ .../iluwatar/halfsynchalfasync/AsyncTask.java | 4 +- .../AsynchronousService.java | 20 ++-- .../main/java/com/iluwatar/hexagonal/App.java | 57 +++++----- .../administration/ConsoleAdministration.java | 10 +- .../ConsoleAdministrationSrv.java | 8 +- .../ConsoleAdministrationSrvImpl.java | 7 +- .../hexagonal/banking/InMemoryBank.java | 22 ++-- .../iluwatar/hexagonal/banking/MongoBank.java | 30 ++--- .../hexagonal/banking/WireTransfers.java | 10 +- .../database/InMemoryTicketRepository.java | 9 +- .../database/LotteryTicketRepository.java | 17 ++- .../database/MongoTicketRepository.java | 22 ++-- .../domain/LotteryAdministration.java | 22 ++-- .../hexagonal/domain/LotteryConstants.java | 6 +- .../hexagonal/domain/LotteryNumbers.java | 32 +++--- .../hexagonal/domain/LotteryService.java | 16 +-- .../hexagonal/domain/LotteryTicket.java | 12 +- .../domain/LotteryTicketCheckResult.java | 14 ++- .../hexagonal/domain/LotteryTicketId.java | 6 +- .../hexagonal/domain/LotteryUtils.java | 19 ++-- .../hexagonal/domain/PlayerDetails.java | 12 +- .../hexagonal/eventlog/LotteryEventLog.java | 14 +-- .../hexagonal/eventlog/MongoEventLog.java | 29 +++-- .../hexagonal/eventlog/StdOutEventLog.java | 17 +-- .../hexagonal/module/LotteryModule.java | 2 +- .../module/LotteryTestingModule.java | 2 +- .../MongoConnectionPropertiesLoader.java | 5 +- .../hexagonal/sampledata/SampleData.java | 83 +++++++------- .../hexagonal/service/ConsoleLottery.java | 9 +- .../service/LotteryConsoleService.java | 15 ++- .../service/LotteryConsoleServiceImpl.java | 105 ++++++++++-------- 34 files changed, 382 insertions(+), 359 deletions(-) diff --git a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java index 922e366029a6..7c9bc1429c4b 100644 --- a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java +++ b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java @@ -21,15 +21,6 @@ * THE SOFTWARE. */ -/** - * Guarded-suspension is a concurrent design pattern for handling situation when to execute some action we need - * condition to be satisfied. - *

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

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

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

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

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

- * INTENT
+ * + *

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

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

- * IMPLEMENTATION
+ * + *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

The secondary ports that application core uses are{@link + * com.iluwatar.hexagonal.banking.WireTransfers} which is a banking service, {@link + * com.iluwatar.hexagonal.eventlog.LotteryEventLog} that delivers eventlog as lottery events occur + * and {@link com.iluwatar.hexagonal.database.LotteryTicketRepository} that is the storage for the + * lottery tickets. */ public class App { /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { @@ -73,11 +68,11 @@ public static void main(String[] args) { // start new lottery round LotteryAdministration administration = injector.getInstance(LotteryAdministration.class); administration.resetLottery(); - + // submit some lottery tickets LotteryService service = injector.getInstance(LotteryService.class); SampleData.submitTickets(service, 20); - + // perform lottery administration.performLottery(); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java index 5db49263697d..ca61b7649c5b 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java @@ -30,20 +30,19 @@ import com.iluwatar.hexagonal.module.LotteryModule; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; import com.iluwatar.hexagonal.sampledata.SampleData; +import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Scanner; - /** - * Console interface for lottery administration + * Console interface for lottery administration. */ public class ConsoleAdministration { private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleAdministration.class); /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); @@ -51,7 +50,8 @@ public static void main(String[] args) { LotteryAdministration administration = injector.getInstance(LotteryAdministration.class); LotteryService service = injector.getInstance(LotteryService.class); SampleData.submitTickets(service, 20); - ConsoleAdministrationSrv consoleAdministration = new ConsoleAdministrationSrvImpl(administration, LOGGER); + ConsoleAdministrationSrv consoleAdministration = + new ConsoleAdministrationSrvImpl(administration, LOGGER); try (Scanner scanner = new Scanner(System.in)) { boolean exit = false; while (!exit) { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java index 70f24739f79c..ec6f815c307a 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java @@ -24,22 +24,22 @@ package com.iluwatar.hexagonal.administration; /** - * Console interface for lottery administration + * Console interface for lottery administration. */ public interface ConsoleAdministrationSrv { /** - * Get all submitted tickets + * Get all submitted tickets. */ void getAllSubmittedTickets(); /** - * Draw lottery numbers + * Draw lottery numbers. */ void performLottery(); /** - * Begin new lottery round + * Begin new lottery round. */ void resetLottery(); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java index d4c154797b8e..fbd00aa1f829 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java @@ -28,14 +28,14 @@ import org.slf4j.Logger; /** - * Console implementation for lottery administration + * Console implementation for lottery administration. */ public class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv { private final LotteryAdministration administration; private final Logger logger; /** - * Constructor + * Constructor. */ public ConsoleAdministrationSrvImpl(LotteryAdministration administration, Logger logger) { this.administration = administration; @@ -44,7 +44,8 @@ public ConsoleAdministrationSrvImpl(LotteryAdministration administration, Logger @Override public void getAllSubmittedTickets() { - administration.getAllSubmittedTickets().forEach((k, v) -> logger.info("Key: {}, Value: {}", k, v)); + administration.getAllSubmittedTickets() + .forEach((k, v) -> logger.info("Key: {}, Value: {}", k, v)); } @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java index 94ad542ff2bd..1a0fdb6b0b9f 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java @@ -23,24 +23,22 @@ package com.iluwatar.hexagonal.banking; +import com.iluwatar.hexagonal.domain.LotteryConstants; import java.util.HashMap; import java.util.Map; -import com.iluwatar.hexagonal.domain.LotteryConstants; - /** - * - * Banking implementation - * + * Banking implementation. */ public class InMemoryBank implements WireTransfers { private static Map accounts = new HashMap<>(); - + static { - accounts.put(LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE); + accounts + .put(LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE); } - + @Override public void setFunds(String bankAccount, int amount) { accounts.put(bankAccount, amount); @@ -52,10 +50,10 @@ public int getFunds(String bankAccount) { } @Override - public boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount) { - if (accounts.getOrDefault(sourceBackAccount, 0) >= amount) { - accounts.put(sourceBackAccount, accounts.get(sourceBackAccount) - amount); - accounts.put(destinationBankAccount, accounts.get(destinationBankAccount) + amount); + public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) { + if (accounts.getOrDefault(sourceAccount, 0) >= amount) { + accounts.put(sourceAccount, accounts.get(sourceAccount) - amount); + accounts.put(destinationAccount, accounts.get(destinationAccount) + amount); return true; } else { return false; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java index 4cdb431f357c..e1c720c115e5 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java @@ -27,13 +27,12 @@ import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; -import org.bson.Document; - import java.util.ArrayList; import java.util.List; +import org.bson.Document; /** - * Mongo based banking adapter + * Mongo based banking adapter. */ public class MongoBank implements WireTransfers { @@ -45,28 +44,28 @@ public class MongoBank implements WireTransfers { private MongoCollection accountsCollection; /** - * Constructor + * Constructor. */ public MongoBank() { connect(); } /** - * Constructor accepting parameters + * Constructor accepting parameters. */ public MongoBank(String dbName, String accountsCollectionName) { connect(dbName, accountsCollectionName); } /** - * Connect to database with default parameters + * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_ACCOUNTS_COLLECTION); } /** - * Connect to database with given parameters + * Connect to database with given parameters. */ public void connect(String dbName, String accountsCollectionName) { if (mongoClient != null) { @@ -79,6 +78,8 @@ public void connect(String dbName, String accountsCollectionName) { } /** + * Get mongo client. + * * @return mongo client */ public MongoClient getMongoClient() { @@ -86,6 +87,7 @@ public MongoClient getMongoClient() { } /** + * Get mongo database. * * @return mongo database */ @@ -94,6 +96,7 @@ public MongoDatabase getMongoDatabase() { } /** + * Get accounts collection. * * @return accounts collection */ @@ -106,7 +109,8 @@ public MongoCollection getAccountsCollection() { public void setFunds(String bankAccount, int amount) { Document search = new Document("_id", bankAccount); Document update = new Document("_id", bankAccount).append("funds", amount); - accountsCollection.updateOne(search, new Document("$set", update), new UpdateOptions().upsert(true)); + accountsCollection + .updateOne(search, new Document("$set", update), new UpdateOptions().upsert(true)); } @Override @@ -121,14 +125,14 @@ public int getFunds(String bankAccount) { } @Override - public boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount) { - int sourceFunds = getFunds(sourceBackAccount); + public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) { + int sourceFunds = getFunds(sourceAccount); if (sourceFunds < amount) { return false; } else { - int destFunds = getFunds(destinationBankAccount); - setFunds(sourceBackAccount, sourceFunds - amount); - setFunds(destinationBankAccount, destFunds + amount); + int destFunds = getFunds(destinationAccount); + setFunds(sourceAccount, sourceFunds - amount); + setFunds(destinationAccount, destFunds + amount); return true; } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java index 4283c6ef27e3..fad455b9b93b 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java @@ -24,25 +24,23 @@ package com.iluwatar.hexagonal.banking; /** - * * Interface to bank accounts. - * */ public interface WireTransfers { /** - * Set amount of funds for bank account + * Set amount of funds for bank account. */ void setFunds(String bankAccount, int amount); /** - * Get amount of funds for bank account + * Get amount of funds for bank account. */ int getFunds(String bankAccount); /** - * Transfer funds from one bank account to another + * Transfer funds from one bank account to another. */ boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount); - + } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java index b5cd526f3b64..a580a7cf51bb 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java @@ -23,20 +23,17 @@ package com.iluwatar.hexagonal.database; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; import java.util.HashMap; import java.util.Map; import java.util.Optional; -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketId; - /** - * * Mock database for lottery tickets. - * */ public class InMemoryTicketRepository implements LotteryTicketRepository { - + private static Map tickets = new HashMap<>(); @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java index 1beef3cd7ce2..e307004ed345 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java @@ -23,37 +23,34 @@ package com.iluwatar.hexagonal.database; -import java.util.Map; -import java.util.Optional; - import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; +import java.util.Map; +import java.util.Optional; /** - * * Interface for accessing lottery tickets in database. - * */ public interface LotteryTicketRepository { /** - * Find lottery ticket by id + * Find lottery ticket by id. */ Optional findById(LotteryTicketId id); /** - * Save lottery ticket + * Save lottery ticket. */ Optional save(LotteryTicket ticket); /** - * Get all lottery tickets + * Get all lottery tickets. */ Map findAll(); /** - * Delete all lottery tickets + * Delete all lottery tickets. */ void deleteAll(); - + } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java index 91cf0c2a8eaf..794cd363fdb6 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java @@ -30,8 +30,6 @@ import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; -import org.bson.Document; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -40,9 +38,10 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import org.bson.Document; /** - * Mongo lottery ticket database + * Mongo lottery ticket database. */ public class MongoTicketRepository implements LotteryTicketRepository { @@ -56,14 +55,14 @@ public class MongoTicketRepository implements LotteryTicketRepository { private MongoCollection countersCollection; /** - * Constructor + * Constructor. */ public MongoTicketRepository() { connect(); } /** - * Constructor accepting parameters + * Constructor accepting parameters. */ public MongoTicketRepository(String dbName, String ticketsCollectionName, String countersCollectionName) { @@ -71,14 +70,14 @@ public MongoTicketRepository(String dbName, String ticketsCollectionName, } /** - * Connect to database with default parameters + * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_TICKETS_COLLECTION, DEFAULT_COUNTERS_COLLECTION); } /** - * Connect to database with given parameters + * Connect to database with given parameters. */ public void connect(String dbName, String ticketsCollectionName, String countersCollectionName) { @@ -101,6 +100,8 @@ private void initCounters() { } /** + * Get next ticket id. + * * @return next ticket id */ public int getNextId() { @@ -112,6 +113,7 @@ public int getNextId() { } /** + * Get tickets collection. * * @return tickets collection */ @@ -120,6 +122,7 @@ public MongoCollection getTicketsCollection() { } /** + * Get counters collection. * * @return counters collection */ @@ -155,7 +158,7 @@ public Optional save(LotteryTicket ticket) { public Map findAll() { Map map = new HashMap<>(); List docs = ticketsCollection.find(new Document()).into(new ArrayList<>()); - for (Document doc: docs) { + for (Document doc : docs) { LotteryTicket lotteryTicket = docToTicket(doc); map.put(lotteryTicket.getId(), lotteryTicket); } @@ -174,6 +177,7 @@ private LotteryTicket docToTicket(Document doc) { .map(Integer::parseInt) .collect(Collectors.toSet()); LotteryNumbers lotteryNumbers = LotteryNumbers.create(numbers); - return new LotteryTicket(new LotteryTicketId(doc.getInteger("ticketId")), playerDetails, lotteryNumbers); + return new LotteryTicket(new LotteryTicketId(doc + .getInteger("ticketId")), playerDetails, lotteryNumbers); } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java index 965f1fc7229d..b9ebff446899 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java @@ -27,13 +27,10 @@ import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; - import java.util.Map; /** - * - * Lottery administration implementation - * + * Lottery administration implementation. */ public class LotteryAdministration { @@ -42,7 +39,7 @@ public class LotteryAdministration { private final WireTransfers wireTransfers; /** - * Constructor + * Constructor. */ @Inject public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications, @@ -53,14 +50,14 @@ public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog } /** - * Get all the lottery tickets submitted for lottery + * Get all the lottery tickets submitted for lottery. */ public Map getAllSubmittedTickets() { return repository.findAll(); } /** - * Draw lottery numbers + * Draw lottery numbers. */ public LotteryNumbers performLottery() { LotteryNumbers numbers = LotteryNumbers.createRandom(); @@ -69,11 +66,14 @@ public LotteryNumbers performLottery() { LotteryTicketCheckResult result = LotteryUtils.checkTicketForPrize(repository, id, numbers); if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { boolean transferred = wireTransfers.transferFunds(LotteryConstants.PRIZE_AMOUNT, - LotteryConstants.SERVICE_BANK_ACCOUNT, tickets.get(id).getPlayerDetails().getBankAccount()); + LotteryConstants.SERVICE_BANK_ACCOUNT, tickets.get(id).getPlayerDetails() + .getBankAccount()); if (transferred) { - notifications.ticketWon(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); + notifications + .ticketWon(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); } else { - notifications.prizeError(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); + notifications + .prizeError(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); } } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { notifications.ticketDidNotWin(tickets.get(id).getPlayerDetails()); @@ -83,7 +83,7 @@ public LotteryNumbers performLottery() { } /** - * Begin new lottery round + * Begin new lottery round. */ public void resetLottery() { repository.deleteAll(); diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java index f33aa9ad801c..06bf294eeb21 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java @@ -24,9 +24,7 @@ package com.iluwatar.hexagonal.domain; /** - * - * Lottery domain constants - * + * Lottery domain constants. */ public class LotteryConstants { @@ -38,5 +36,5 @@ private LotteryConstants() { public static final int TICKET_PRIZE = 3; public static final int SERVICE_BANK_ACCOUNT_BALANCE = 150000; public static final int PLAYER_MAX_BALANCE = 100; - + } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java index 32f39e4cf0df..9dc00ec7695b 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java @@ -24,7 +24,6 @@ package com.iluwatar.hexagonal.domain; import com.google.common.base.Joiner; - import java.util.Collections; import java.util.HashSet; import java.util.PrimitiveIterator; @@ -32,15 +31,13 @@ import java.util.Set; /** - * - * Value object representing lottery numbers. This lottery uses sets of 4 numbers. The numbers must be unique and - * between 1 and 20. - * + * Value object representing lottery numbers. This lottery uses sets of 4 numbers. The numbers must + * be unique and between 1 and 20. */ public class LotteryNumbers { private final Set numbers; - + public static final int MIN_NUMBER = 1; public static final int MAX_NUMBER = 20; public static final int NUM_NUMBERS = 4; @@ -62,6 +59,8 @@ private LotteryNumbers(Set givenNumbers) { } /** + * Creates a random lottery number. + * * @return random LotteryNumbers */ public static LotteryNumbers createRandom() { @@ -69,13 +68,17 @@ public static LotteryNumbers createRandom() { } /** + * Creates lottery number from given set of numbers. + * * @return given LotteryNumbers */ public static LotteryNumbers create(Set givenNumbers) { return new LotteryNumbers(givenNumbers); } - + /** + * Get numbers. + * * @return lottery numbers */ public Set getNumbers() { @@ -83,12 +86,14 @@ public Set getNumbers() { } /** + * Get numbers as string. + * * @return numbers as comma separated string */ public String getNumbersAsString() { return Joiner.on(',').join(numbers); } - + /** * Generates 4 unique random numbers between 1-20 into numbers set. */ @@ -107,17 +112,16 @@ public String toString() { } /** - * * Helper class for generating random numbers. - * */ private static class RandomNumberGenerator { private PrimitiveIterator.OfInt randomIterator; /** - * Initialize a new random number generator that generates random numbers in the range [min, max] - * + * Initialize a new random number generator that generates random numbers in the range [min, + * max]. + * * @param min the min value (inclusive) * @param max the max value (inclusive) */ @@ -126,13 +130,15 @@ public RandomNumberGenerator(int min, int max) { } /** + * Gets next random integer in [min, max] range. + * * @return a random number in the range (min, max) */ public int nextInt() { return randomIterator.nextInt(); } } - + @Override public int hashCode() { final int prime = 31; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java index 8839ccc969ba..212671d77740 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java @@ -27,13 +27,10 @@ import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; - import java.util.Optional; /** - * - * Implementation for lottery service - * + * Implementation for lottery service. */ public class LotteryService { @@ -42,7 +39,7 @@ public class LotteryService { private final WireTransfers wireTransfers; /** - * Constructor + * Constructor. */ @Inject public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications, @@ -53,7 +50,7 @@ public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifi } /** - * Submit lottery ticket to participate in the lottery + * Submit lottery ticket to participate in the lottery. */ public Optional submitTicket(LotteryTicket ticket) { boolean result = wireTransfers.transferFunds(LotteryConstants.TICKET_PRIZE, @@ -70,9 +67,12 @@ public Optional submitTicket(LotteryTicket ticket) { } /** - * Check if lottery ticket has won + * Check if lottery ticket has won. */ - public LotteryTicketCheckResult checkTicketForPrize(LotteryTicketId id, LotteryNumbers winningNumbers) { + public LotteryTicketCheckResult checkTicketForPrize( + LotteryTicketId id, + LotteryNumbers winningNumbers + ) { return LotteryUtils.checkTicketForPrize(repository, id, winningNumbers); } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java index fbac5bff3576..91c041273fbf 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java @@ -24,9 +24,7 @@ package com.iluwatar.hexagonal.domain; /** - * * Immutable value object representing lottery ticket. - * */ public class LotteryTicket { @@ -44,13 +42,17 @@ public LotteryTicket(LotteryTicketId id, PlayerDetails details, LotteryNumbers n } /** + * Get player details. + * * @return player details */ public PlayerDetails getPlayerDetails() { return playerDetails; } - + /** + * Get lottery numbers. + * * @return lottery numbers */ public LotteryNumbers getNumbers() { @@ -58,6 +60,8 @@ public LotteryNumbers getNumbers() { } /** + * Get ticket id. + * * @return id */ public LotteryTicketId getId() { @@ -65,7 +69,7 @@ public LotteryTicketId getId() { } /** - * set id + * Set ticket id. */ public void setId(LotteryTicketId id) { this.id = id; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java index e5c05301c5e1..c7f07c1df960 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java @@ -24,16 +24,18 @@ package com.iluwatar.hexagonal.domain; /** - * * Represents lottery ticket check result. - * */ public class LotteryTicketCheckResult { /** - * Enumeration of Type of Outcomes of a Lottery + * Enumeration of Type of Outcomes of a Lottery. */ - public enum CheckResult { WIN_PRIZE, NO_PRIZE, TICKET_NOT_SUBMITTED } + public enum CheckResult { + WIN_PRIZE, + NO_PRIZE, + TICKET_NOT_SUBMITTED + } private final CheckResult checkResult; private final int prizeAmount; @@ -55,6 +57,8 @@ public LotteryTicketCheckResult(CheckResult result, int amount) { } /** + * Get result. + * * @return check result */ public CheckResult getResult() { @@ -62,6 +66,8 @@ public CheckResult getResult() { } /** + * Get prize amount. + * * @return prize amount */ public int getPrizeAmount() { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java index 29fd6b14599d..d4c036ece127 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java @@ -26,13 +26,13 @@ import java.util.concurrent.atomic.AtomicInteger; /** - * Lottery ticked id + * Lottery ticked id. */ public class LotteryTicketId { private static AtomicInteger numAllocated = new AtomicInteger(0); private final int id; - + public LotteryTicketId() { this.id = numAllocated.incrementAndGet(); } @@ -40,7 +40,7 @@ public LotteryTicketId() { public LotteryTicketId(int id) { this.id = id; } - + public int getId() { return id; } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java index ec070429d198..84f9af9e8b3c 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java @@ -24,11 +24,11 @@ package com.iluwatar.hexagonal.domain; import com.iluwatar.hexagonal.database.LotteryTicketRepository; - +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; import java.util.Optional; /** - * Lottery utilities + * Lottery utilities. */ public class LotteryUtils { @@ -36,19 +36,22 @@ private LotteryUtils() { } /** - * Checks if lottery ticket has won + * Checks if lottery ticket has won. */ - public static LotteryTicketCheckResult checkTicketForPrize(LotteryTicketRepository repository, LotteryTicketId id, - LotteryNumbers winningNumbers) { + public static LotteryTicketCheckResult checkTicketForPrize( + LotteryTicketRepository repository, + LotteryTicketId id, + LotteryNumbers winningNumbers + ) { Optional optional = repository.findById(id); if (optional.isPresent()) { if (optional.get().getNumbers().equals(winningNumbers)) { - return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.WIN_PRIZE, 1000); + return new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 1000); } else { - return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.NO_PRIZE); + return new LotteryTicketCheckResult(CheckResult.NO_PRIZE); } } else { - return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.TICKET_NOT_SUBMITTED); + return new LotteryTicketCheckResult(CheckResult.TICKET_NOT_SUBMITTED); } } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java index 67b925e73cbf..f2c09744c178 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java @@ -24,9 +24,7 @@ package com.iluwatar.hexagonal.domain; /** - * * Immutable value object containing lottery player details. - * */ public class PlayerDetails { @@ -44,20 +42,26 @@ public PlayerDetails(String email, String bankAccount, String phone) { } /** + * Get email. + * * @return email */ public String getEmail() { return emailAddress; } - + /** + * Get back account number. + * * @return bank account number */ public String getBankAccount() { return bankAccountNumber; } - + /** + * Get phone number. + * * @return phone number */ public String getPhoneNumber() { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java index e13dbfab5ffa..993f2a344691 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java @@ -26,34 +26,32 @@ import com.iluwatar.hexagonal.domain.PlayerDetails; /** - * - * Event log for lottery events - * + * Event log for lottery events. */ public interface LotteryEventLog { /** - * lottery ticket submitted + * lottery ticket submitted. */ void ticketSubmitted(PlayerDetails details); /** - * error submitting lottery ticket + * error submitting lottery ticket. */ void ticketSubmitError(PlayerDetails details); /** - * lottery ticket did not win + * lottery ticket did not win. */ void ticketDidNotWin(PlayerDetails details); /** - * lottery ticket won + * lottery ticket won. */ void ticketWon(PlayerDetails details, int prizeAmount); /** - * error paying the prize + * error paying the prize. */ void prizeError(PlayerDetails details, int prizeAmount); diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java index 1eda775c0c68..f979506e4e3f 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java @@ -30,7 +30,7 @@ import org.bson.Document; /** - * Mongo based event log + * Mongo based event log. */ public class MongoEventLog implements LotteryEventLog { @@ -44,28 +44,28 @@ public class MongoEventLog implements LotteryEventLog { private StdOutEventLog stdOutEventLog = new StdOutEventLog(); /** - * Constructor + * Constructor. */ public MongoEventLog() { connect(); } /** - * Constructor accepting parameters + * Constructor accepting parameters. */ public MongoEventLog(String dbName, String eventsCollectionName) { connect(dbName, eventsCollectionName); } /** - * Connect to database with default parameters + * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_EVENTS_COLLECTION); } /** - * Connect to database with given parameters + * Connect to database with given parameters. */ public void connect(String dbName, String eventsCollectionName) { if (mongoClient != null) { @@ -78,6 +78,8 @@ public void connect(String dbName, String eventsCollectionName) { } /** + * Get mongo client. + * * @return mongo client */ public MongoClient getMongoClient() { @@ -85,6 +87,7 @@ public MongoClient getMongoClient() { } /** + * Get mongo database. * * @return mongo database */ @@ -93,8 +96,9 @@ public MongoDatabase getMongoDatabase() { } /** + * Get events collection. * - * @return accounts collection + * @return events collection */ public MongoCollection getEventsCollection() { return eventsCollection; @@ -106,7 +110,8 @@ public void ticketSubmitted(PlayerDetails details) { Document document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); - document.put("message", "Lottery ticket was submitted and bank account was charged for 3 credits."); + document + .put("message", "Lottery ticket was submitted and bank account was charged for 3 credits."); eventsCollection.insertOne(document); stdOutEventLog.ticketSubmitted(details); } @@ -136,8 +141,9 @@ public void ticketWon(PlayerDetails details, int prizeAmount) { Document document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); - document.put("message", String.format("Lottery ticket won! The bank account was deposited with %d credits.", - prizeAmount)); + document.put("message", String + .format("Lottery ticket won! The bank account was deposited with %d credits.", + prizeAmount)); eventsCollection.insertOne(document); stdOutEventLog.ticketWon(details, prizeAmount); } @@ -147,8 +153,9 @@ public void prizeError(PlayerDetails details, int prizeAmount) { Document document = new Document("email", details.getEmail()); document.put("phone", details.getPhoneNumber()); document.put("bank", details.getBankAccount()); - document.put("message", String.format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", - prizeAmount)); + document.put("message", String + .format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", + prizeAmount)); eventsCollection.insertOne(document); stdOutEventLog.prizeError(details, prizeAmount); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java index e236acf69762..284fc4d1cccd 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java @@ -28,7 +28,7 @@ import org.slf4j.LoggerFactory; /** - * Standard output event log + * Standard output event log. */ public class StdOutEventLog implements LotteryEventLog { @@ -42,24 +42,27 @@ 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 public void ticketWon(PlayerDetails details, int prizeAmount) { LOGGER.info("Lottery ticket for {} has won! The bank account {} was deposited with {} credits.", - details.getEmail(), details.getBankAccount(), prizeAmount); + details.getEmail(), details.getBankAccount(), prizeAmount); } @Override public void prizeError(PlayerDetails details, int prizeAmount) { - LOGGER.error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of {} failed.", - details.getEmail(), prizeAmount); + LOGGER + .error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of" + + " {} failed.", details.getEmail(), prizeAmount); } @Override public void ticketSubmitError(PlayerDetails details) { - LOGGER.error("Lottery ticket for {} could not be submitted because the credit transfer of 3 credits failed.", - details.getEmail()); + LOGGER.error("Lottery ticket for {} could not be submitted because the credit transfer" + + " of 3 credits failed.", details.getEmail()); } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java index a8a10b69cf6e..73cf16805524 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java @@ -32,7 +32,7 @@ import com.iluwatar.hexagonal.eventlog.MongoEventLog; /** - * Guice module for binding production dependencies + * Guice module for binding production dependencies. */ public class LotteryModule extends AbstractModule { @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java index 4fd8262de662..f416ffcc2af6 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java @@ -32,7 +32,7 @@ import com.iluwatar.hexagonal.eventlog.StdOutEventLog; /** - * Guice module for testing dependencies + * Guice module for testing dependencies. */ public class LotteryTestingModule extends AbstractModule { @Override diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java index f9edbad995d2..2d8463f7f50f 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java @@ -27,7 +27,7 @@ import java.util.Properties; /** - * Mongo connection properties loader + * Mongo connection properties loader. */ public class MongoConnectionPropertiesLoader { @@ -35,8 +35,7 @@ public class MongoConnectionPropertiesLoader { private static final int DEFAULT_PORT = 27017; /** - * Try to load connection properties from file. - * Fall back to default connection properties. + * Try to load connection properties from file. Fall back to default connection properties. */ public static void load() { String host = DEFAULT_HOST; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java index 8189303eb04a..ccda4a2086c0 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java @@ -30,12 +30,11 @@ import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; - import java.util.List; import java.util.Random; /** - * Utilities for creating sample lottery tickets + * Utilities for creating sample lottery tickets. */ public class SampleData { @@ -44,45 +43,45 @@ public class SampleData { static { PLAYERS = List.of( - new PlayerDetails("john@google.com", "312-342", "+3242434242"), - new PlayerDetails("mary@google.com", "234-987", "+23452346"), - new PlayerDetails("steve@google.com", "833-836", "+63457543"), - new PlayerDetails("wayne@google.com", "319-826", "+24626"), - new PlayerDetails("johnie@google.com", "983-322", "+3635635"), - new PlayerDetails("andy@google.com", "934-734", "+0898245"), - new PlayerDetails("richard@google.com", "536-738", "+09845325"), - new PlayerDetails("kevin@google.com", "453-936", "+2423532"), - new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), - new PlayerDetails("ian@google.com", "663-765", "+928394235"), - new PlayerDetails("robin@google.com", "334-763", "+35448"), - new PlayerDetails("ted@google.com", "735-964", "+98752345"), - new PlayerDetails("larry@google.com", "734-853", "+043842423"), - new PlayerDetails("calvin@google.com", "334-746", "+73294135"), - new PlayerDetails("jacob@google.com", "444-766", "+358042354"), - new PlayerDetails("edwin@google.com", "895-345", "+9752435"), - new PlayerDetails("mary@google.com", "760-009", "+34203542"), - new PlayerDetails("lolita@google.com", "425-907", "+9872342"), - new PlayerDetails("bruno@google.com", "023-638", "+673824122"), - new PlayerDetails("peter@google.com", "335-886", "+5432503945"), - new PlayerDetails("warren@google.com", "225-946", "+9872341324"), - new PlayerDetails("monica@google.com", "265-748", "+134124"), - new PlayerDetails("ollie@google.com", "190-045", "+34453452"), - new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), - new PlayerDetails("lars@google.com", "746-936", "+42345298345"), - new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), - new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), - new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), - new PlayerDetails("nadja@google.com", "000-346", "+498723"), - new PlayerDetails("wendy@google.com", "994-989", "+987324454"), - new PlayerDetails("luke@google.com", "546-634", "+987642435"), - new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), - new PlayerDetails("lisa@google.com", "024-653", "+980742154"), - new PlayerDetails("anton@google.com", "834-935", "+876423145"), - new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), - new PlayerDetails("ray@google.com", "843-073", "+678324123"), - new PlayerDetails("ron@google.com", "637-738", "+09842354"), - new PlayerDetails("xavier@google.com", "143-947", "+375245"), - new PlayerDetails("harriet@google.com", "842-404", "+131243252") + new PlayerDetails("john@google.com", "312-342", "+3242434242"), + new PlayerDetails("mary@google.com", "234-987", "+23452346"), + new PlayerDetails("steve@google.com", "833-836", "+63457543"), + new PlayerDetails("wayne@google.com", "319-826", "+24626"), + new PlayerDetails("johnie@google.com", "983-322", "+3635635"), + new PlayerDetails("andy@google.com", "934-734", "+0898245"), + new PlayerDetails("richard@google.com", "536-738", "+09845325"), + new PlayerDetails("kevin@google.com", "453-936", "+2423532"), + new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), + new PlayerDetails("ian@google.com", "663-765", "+928394235"), + new PlayerDetails("robin@google.com", "334-763", "+35448"), + new PlayerDetails("ted@google.com", "735-964", "+98752345"), + new PlayerDetails("larry@google.com", "734-853", "+043842423"), + new PlayerDetails("calvin@google.com", "334-746", "+73294135"), + new PlayerDetails("jacob@google.com", "444-766", "+358042354"), + new PlayerDetails("edwin@google.com", "895-345", "+9752435"), + new PlayerDetails("mary@google.com", "760-009", "+34203542"), + new PlayerDetails("lolita@google.com", "425-907", "+9872342"), + new PlayerDetails("bruno@google.com", "023-638", "+673824122"), + new PlayerDetails("peter@google.com", "335-886", "+5432503945"), + new PlayerDetails("warren@google.com", "225-946", "+9872341324"), + new PlayerDetails("monica@google.com", "265-748", "+134124"), + new PlayerDetails("ollie@google.com", "190-045", "+34453452"), + new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), + new PlayerDetails("lars@google.com", "746-936", "+42345298345"), + new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), + new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), + new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), + new PlayerDetails("nadja@google.com", "000-346", "+498723"), + new PlayerDetails("wendy@google.com", "994-989", "+987324454"), + new PlayerDetails("luke@google.com", "546-634", "+987642435"), + new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), + new PlayerDetails("lisa@google.com", "024-653", "+980742154"), + new PlayerDetails("anton@google.com", "834-935", "+876423145"), + new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), + new PlayerDetails("ray@google.com", "843-073", "+678324123"), + new PlayerDetails("ron@google.com", "637-738", "+09842354"), + new PlayerDetails("xavier@google.com", "143-947", "+375245"), + new PlayerDetails("harriet@google.com", "842-404", "+131243252") ); InMemoryBank wireTransfers = new InMemoryBank(); for (PlayerDetails player : PLAYERS) { @@ -92,7 +91,7 @@ public class SampleData { } /** - * Inserts lottery tickets into the database based on the sample data + * Inserts lottery tickets into the database based on the sample data. */ public static void submitTickets(LotteryService lotteryService, int numTickets) { for (int i = 0; i < numTickets; i++) { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java index b452a4f5dab8..dccbf68ebf4b 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java @@ -29,25 +29,24 @@ import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.module.LotteryModule; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Scanner; - /** - * Console interface for lottery players + * Console interface for lottery players. */ public class ConsoleLottery { private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleLottery.class); /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); Injector injector = Guice.createInjector(new LotteryModule()); - LotteryService service = injector.getInstance( LotteryService.class); + LotteryService service = injector.getInstance(LotteryService.class); WireTransfers bank = injector.getInstance(WireTransfers.class); try (Scanner scanner = new Scanner(System.in)) { boolean exit = false; diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java index dec414ee40fb..b5bd01a663cf 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java @@ -25,31 +25,30 @@ import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.domain.LotteryService; - import java.util.Scanner; /** - * Console interface for lottery service + * Console interface for lottery service. */ public interface LotteryConsoleService { void checkTicket(LotteryService service, Scanner scanner); /** - * Submit lottery ticket to participate in the lottery - */ + * Submit lottery ticket to participate in the lottery. + */ void submitTicket(LotteryService service, Scanner scanner); /** - * Add funds to lottery account - */ + * Add funds to lottery account. + */ void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner); /** - * Recovery funds from lottery account - */ + * Recovery funds from lottery account. + */ void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java index 3641b9a5c50c..d100dba03c83 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java @@ -24,22 +24,29 @@ package com.iluwatar.hexagonal.service; import com.iluwatar.hexagonal.banking.WireTransfers; -import com.iluwatar.hexagonal.domain.*; -import org.slf4j.Logger; - -import java.util.*; +import com.iluwatar.hexagonal.domain.LotteryNumbers; +import com.iluwatar.hexagonal.domain.LotteryService; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.domain.PlayerDetails; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Optional; +import java.util.Scanner; +import java.util.Set; import java.util.stream.Collectors; -import java.util.stream.IntStream; +import org.slf4j.Logger; /** - * Console implementation for lottery console service + * Console implementation for lottery console service. */ public class LotteryConsoleServiceImpl implements LotteryConsoleService { private final Logger logger; /** - * Constructor + * Constructor. */ public LotteryConsoleServiceImpl(Logger logger) { this.logger = logger; @@ -47,79 +54,81 @@ public 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 ); - logger.info( "Give the 4 comma separated winning numbers?" ); - String numbers = readString( scanner ); + logger.info("What is the ID of the lottery ticket?"); + String id = readString(scanner); + logger.info("Give the 4 comma separated winning numbers?"); + String numbers = readString(scanner); try { - String[] parts = numbers.split( "," ); + String[] parts = numbers.split(","); Set winningNumbers = new HashSet<>(); for (int i = 0; i < 4; i++) { - winningNumbers.add( Integer.parseInt( parts[i] ) ); + winningNumbers.add(Integer.parseInt(parts[i])); } - final LotteryTicketId lotteryTicketId = new LotteryTicketId( Integer.parseInt( id ) ); - final LotteryNumbers lotteryNumbers = LotteryNumbers.create( winningNumbers ); - LotteryTicketCheckResult result = service.checkTicketForPrize( lotteryTicketId, lotteryNumbers ); + final LotteryTicketId lotteryTicketId = new LotteryTicketId(Integer.parseInt(id)); + final LotteryNumbers lotteryNumbers = LotteryNumbers.create(winningNumbers); + LotteryTicketCheckResult result = + service.checkTicketForPrize(lotteryTicketId, lotteryNumbers); - if (result.getResult().equals( LotteryTicketCheckResult.CheckResult.WIN_PRIZE )) { - logger.info( "Congratulations! The lottery ticket has won!" ); - } else if (result.getResult().equals( LotteryTicketCheckResult.CheckResult.NO_PRIZE )) { - logger.info( "Unfortunately the lottery ticket did not win." ); + if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { + logger.info("Congratulations! The lottery ticket has won!"); + } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { + logger.info("Unfortunately the lottery ticket did not win."); } else { - logger.info( "Such lottery ticket has not been submitted." ); + logger.info("Such lottery ticket has not been submitted."); } } catch (Exception e) { - logger.info( "Failed checking the lottery ticket - please try again." ); + logger.info("Failed checking the lottery ticket - please try again."); } } @Override public void submitTicket(LotteryService service, Scanner scanner) { - logger.info( "What is your email address?" ); - String email = readString( scanner ); - logger.info( "What is your bank account number?" ); - String account = readString( scanner ); - logger.info( "What is your phone number?" ); - String phone = readString( scanner ); - PlayerDetails details = new PlayerDetails( email, account, phone ); - logger.info( "Give 4 comma separated lottery numbers?" ); - String numbers = readString( scanner ); + logger.info("What is your email address?"); + String email = readString(scanner); + logger.info("What is your bank account number?"); + String account = readString(scanner); + logger.info("What is your phone number?"); + String phone = readString(scanner); + PlayerDetails details = new PlayerDetails(email, account, phone); + logger.info("Give 4 comma separated lottery numbers?"); + String numbers = readString(scanner); try { - String[] parts = numbers.split( "," ); + String[] parts = numbers.split(","); Set chosen = Arrays.stream(parts).map(Integer::parseInt).collect(Collectors.toSet()); - LotteryNumbers lotteryNumbers = LotteryNumbers.create( chosen ); - LotteryTicket lotteryTicket = new LotteryTicket( new LotteryTicketId(), details, lotteryNumbers ); - Optional id = service.submitTicket( lotteryTicket ); + LotteryNumbers lotteryNumbers = LotteryNumbers.create(chosen); + LotteryTicket lotteryTicket = + new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); + Optional id = service.submitTicket(lotteryTicket); if (id.isPresent()) { - logger.info( "Submitted lottery ticket with id: {}", id.get() ); + logger.info("Submitted lottery ticket with id: {}", id.get()); } else { - logger.info( "Failed submitting lottery ticket - please try again." ); + logger.info("Failed submitting lottery ticket - please try again."); } } catch (Exception e) { - logger.info( "Failed submitting lottery ticket - please try again." ); + logger.info("Failed submitting lottery ticket - please try again."); } } @Override public void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) { - logger.info( "What is the account number?" ); - String account = readString( scanner ); - logger.info( "How many credits do you want to deposit?" ); - String amount = readString( scanner ); - bank.setFunds( account, Integer.parseInt( amount ) ); - logger.info( "The account {} now has {} credits.", account, bank.getFunds( account ) ); + logger.info("What is the account number?"); + String account = readString(scanner); + logger.info("How many credits do you want to deposit?"); + String amount = readString(scanner); + bank.setFunds(account, Integer.parseInt(amount)); + logger.info("The account {} now has {} credits.", account, bank.getFunds(account)); } @Override public void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner) { - logger.info( "What is the account number?" ); - String account = readString( scanner ); - logger.info( "The account {} has {} credits.", account, bank.getFunds( account ) ); + logger.info("What is the account number?"); + String account = readString(scanner); + logger.info("The account {} has {} credits.", account, bank.getFunds(account)); } private String readString(Scanner scanner) { - logger.info( "> " ); + logger.info("> "); return scanner.next(); } } From 7f06f3b78c9e6cb900606d2fb5bb3af2cac93978 Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 22:35:05 +0530 Subject: [PATCH 08/32] Resolves checkstyle errors for intercepting-filter, interpreter, iterator (#1065) * Reduces checkstyle errors in intercepting-filter * Reduces checkstyle errors in interpreter * Reduces checkstyle errors in iterator --- .../intercepting/filter/AbstractFilter.java | 4 +-- .../intercepting/filter/AddressFilter.java | 3 +- .../com/iluwatar/intercepting/filter/App.java | 29 +++++++++---------- .../iluwatar/intercepting/filter/Client.java | 24 ++++++++------- .../intercepting/filter/ContactFilter.java | 5 ++-- .../intercepting/filter/DepositFilter.java | 5 ++-- .../iluwatar/intercepting/filter/Filter.java | 3 +- .../intercepting/filter/FilterChain.java | 6 ++-- .../intercepting/filter/FilterManager.java | 3 +- .../intercepting/filter/NameFilter.java | 3 +- .../iluwatar/intercepting/filter/Order.java | 11 ++++--- .../intercepting/filter/OrderFilter.java | 3 +- .../iluwatar/intercepting/filter/Target.java | 18 ++++++------ .../java/com/iluwatar/interpreter/App.java | 23 ++++++--------- .../com/iluwatar/interpreter/Expression.java | 4 +-- .../iluwatar/interpreter/MinusExpression.java | 4 +-- .../interpreter/MultiplyExpression.java | 4 +-- .../interpreter/NumberExpression.java | 4 +-- .../iluwatar/interpreter/PlusExpression.java | 4 +-- .../main/java/com/iluwatar/iterator/App.java | 6 ++-- .../java/com/iluwatar/iterator/Iterator.java | 3 +- .../iluwatar/iterator/bst/BstIterator.java | 8 +++-- .../com/iluwatar/iterator/bst/TreeNode.java | 4 +-- .../java/com/iluwatar/iterator/list/Item.java | 4 +-- .../com/iluwatar/iterator/list/ItemType.java | 4 +-- .../iluwatar/iterator/list/TreasureChest.java | 26 ++++++++--------- .../list/TreasureChestItemIterator.java | 6 ++-- 27 files changed, 99 insertions(+), 122 deletions(-) diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java index a51bfba6fc50..aa20365f6ada 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java @@ -25,13 +25,13 @@ /** * Base class for order processing filters. Handles chain management. - * */ public abstract class AbstractFilter implements Filter { private Filter next; - public AbstractFilter() {} + public AbstractFilter() { + } public AbstractFilter(Filter next) { this.next = next; 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 791cb8ea6a47..6b9a15382b8e 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 @@ -26,9 +26,8 @@ /** * Concrete implementation of filter This filter is responsible for checking/filtering the input in * the address field. - * - * @author joshzambales * + * @author joshzambales */ public class AddressFilter extends AbstractFilter { 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 822fae13fc35..b81f1e229284 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 @@ -24,7 +24,6 @@ package com.iluwatar.intercepting.filter; /** - * * When a request enters a Web application, it often must pass several entrance tests prior to the * main processing stage. For example, - Has the client been authenticated? - Does the client have a * valid session? - Is the client's IP address from a trusted network? - Does the request path @@ -32,28 +31,26 @@ * the browser type of the client? Some of these checks are tests, resulting in a yes or no answer * that determines whether processing will continue. Other checks manipulate the incoming data * stream into a form suitable for processing. - *

- * The classic solution consists of a series of conditional checks, with any failed check aborting - * the request. Nested if/else statements are a standard strategy, but this solution leads to code - * fragility and a copy-and-paste style of programming, because the flow of the filtering and the - * action of the filters is compiled into the application. - *

- * The key to solving this problem in a flexible and unobtrusive manner is to have a simple + * + *

The classic solution consists of a series of conditional checks, with any failed check + * aborting the request. Nested if/else statements are a standard strategy, but this solution leads + * to code fragility and a copy-and-paste style of programming, because the flow of the filtering + * and the action of the filters is compiled into the application. + * + *

The key to solving this problem in a flexible and unobtrusive manner is to have a simple * mechanism for adding and removing processing components, in which each component completes a * specific filtering action. This is the Intercepting Filter pattern in action. - *

- * In this example we check whether the order request is valid through pre-processing done via - * {@link Filter}. Each field has its own corresponding {@link Filter} - *

- * - * @author joshzambales * + *

In this example we check whether the order request is valid through pre-processing done via + * {@link Filter}. Each field has its own corresponding {@link Filter}. + * + * @author joshzambales */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { 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 109f3ab02ed5..865dbbb381da 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 @@ -23,6 +23,9 @@ package com.iluwatar.intercepting.filter; +import java.awt.BorderLayout; +import java.awt.GridLayout; + import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; @@ -32,18 +35,15 @@ import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; -import java.awt.BorderLayout; -import java.awt.GridLayout; /** - * The Client class is responsible for handling the input and running them through filters inside the - * {@link FilterManager}. + * The Client class is responsible for handling the input and running them through filters inside + * the {@link FilterManager}. * - * This is where {@link Filter}s come to play as the client pre-processes the request before being displayed in the - * {@link Target}. - * - * @author joshzambales + *

This is where {@link Filter}s come to play as the client pre-processes the request before + * being displayed in the {@link Target}. * + * @author joshzambales */ public class Client extends JFrame { // NOSONAR @@ -57,7 +57,7 @@ public class Client extends JFrame { // NOSONAR private JButton processButton; /** - * Constructor + * Constructor. */ public Client() { super("Client System"); @@ -107,8 +107,10 @@ private void setup() { }); processButton.addActionListener(e -> { - Order order = new Order(jtFields[0].getText(), jtFields[1].getText(), jtAreas[0].getText(), jtFields[2].getText(), - jtAreas[1].getText()); + Order order = + new Order(jtFields[0].getText(), jtFields[1].getText(), jtAreas[0].getText(), jtFields[2] + .getText(), + jtAreas[1].getText()); 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 84425cd72b55..9acdec31966b 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 @@ -26,10 +26,9 @@ /** * Concrete implementation of filter This filter checks for the contact field in which it checks if * the input consist of numbers and it also checks if the input follows the length constraint (11 - * digits) - * - * @author joshzambales + * digits). * + * @author joshzambales */ public class ContactFilter extends AbstractFilter { 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 e2e68083bbff..e7457c9bec5b 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 @@ -24,10 +24,9 @@ package com.iluwatar.intercepting.filter; /** - * Concrete implementation of filter This checks for the deposit code - * - * @author joshzambales + * Concrete implementation of filter This checks for the deposit code. * + * @author joshzambales */ public class DepositFilter extends AbstractFilter { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java index 5c9fe325a758..76afdedbded3 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java @@ -26,9 +26,8 @@ /** * Filters perform certain tasks prior or after execution of request by request handler. In this * case, before the request is handled by the target, the request undergoes through each Filter - * - * @author joshzambales * + * @author joshzambales */ public interface Filter { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java index bfd88f61d78b..07429ca5f708 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java @@ -26,7 +26,7 @@ /** * Filter Chain carries multiple filters and help to execute them in defined order on target. - * + * * @author joshzambales */ public class FilterChain { @@ -35,7 +35,7 @@ public class FilterChain { /** - * Adds filter + * Adds filter. */ public void addFilter(Filter filter) { if (chain == null) { @@ -46,7 +46,7 @@ public void addFilter(Filter filter) { } /** - * Execute filter chain + * Execute filter chain. */ public String execute(Order order) { if (chain != null) { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java index cef868dcc4b8..e8f3b941faa1 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java @@ -25,9 +25,8 @@ /** * Filter Manager manages the filters and {@link FilterChain}. - * - * @author joshzambales * + * @author joshzambales */ public class FilterManager { 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 d06b24ca9892..95ef54fe1d82 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 @@ -26,9 +26,8 @@ /** * Concrete implementation of filter. This filter checks if the input in the Name field is valid. * (alphanumeric) - * - * @author joshzambales * + * @author joshzambales */ public class NameFilter extends AbstractFilter { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java index 988464aec41a..a75911578161 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java @@ -25,7 +25,6 @@ /** * Order class carries the order data. - * */ public class Order { @@ -35,12 +34,16 @@ public class Order { private String depositNumber; private String orderItem; - public Order() {} + public Order() { + } /** - * Constructor + * Constructor. */ - public Order(String name, String contactNumber, String address, String depositNumber, String order) { + public Order( + String name, String contactNumber, String address, + String depositNumber, String order + ) { this.name = name; this.contactNumber = contactNumber; this.address = address; 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 8669cd2e7d6c..de91386f3f57 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 @@ -25,9 +25,8 @@ /** * Concrete implementation of filter. This checks for the order field. - * - * @author joshzambales * + * @author joshzambales */ public class OrderFilter extends AbstractFilter { 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 415d3b2b645c..9ded355c757a 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 @@ -23,6 +23,11 @@ package com.iluwatar.intercepting.filter; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; @@ -32,16 +37,11 @@ import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; /** * This is where the requests are displayed after being validated by filters. - * - * @author mjoshzambales * + * @author mjoshzambales */ public class Target extends JFrame { //NOSONAR @@ -52,14 +52,14 @@ public class Target extends JFrame { //NOSONAR private JButton del; /** - * Constructor + * Constructor. */ public Target() { super("Order System"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(640, 480); dtm = - new DefaultTableModel(new Object[] {"Name", "Contact Number", "Address", "Deposit Number", + new DefaultTableModel(new Object[]{"Name", "Contact Number", "Address", "Deposit Number", "Order"}, 0); jt = new JTable(dtm); del = new JButton("Delete"); @@ -85,7 +85,7 @@ private void setup() { } public void execute(String[] request) { - dtm.addRow(new Object[] {request[0], request[1], request[2], request[3], request[4]}); + dtm.addRow(new Object[]{request[0], request[1], request[2], request[3], request[4]}); } class DListener implements ActionListener { diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/App.java b/interpreter/src/main/java/com/iluwatar/interpreter/App.java index 5dcd3b81d7b8..d63c78506014 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/App.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/App.java @@ -23,35 +23,30 @@ package com.iluwatar.interpreter; +import java.util.Stack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Stack; - /** - * * The Interpreter pattern is a design pattern that specifies how to evaluate sentences in a * language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a * specialized computer language. The syntax tree of a sentence in the language is an instance of * the composite pattern and is used to evaluate (interpret) the sentence for a client. - *

- * In this example we use the Interpreter pattern to break sentences into expressions ( - * {@link Expression}) that can be evaluated and as a whole form the result. - * + * + *

In this example we use the Interpreter pattern to break sentences into expressions ({@link + * Expression}) that can be evaluated and as a whole form the result. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * * Program entry point. - *

- * Expressions can be evaluated using prefix, infix or postfix notations This sample uses postfix, - * where operator comes after the operands - * + * + *

Expressions can be evaluated using prefix, infix or postfix notations This sample uses + * postfix, where operator comes after the operands. + * * @param args command line args - * */ public static void main(String[] args) { String tokenString = "4 3 2 - 1 + *"; @@ -84,7 +79,7 @@ public static boolean isOperator(String s) { } /** - * Get expression for string + * Get expression for string. */ public static Expression getOperatorInstance(String s, Expression left, Expression right) { switch (s) { diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java b/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java index dc9da1177211..dee43b57fb2e 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java @@ -24,9 +24,7 @@ package com.iluwatar.interpreter; /** - * - * Expression - * + * Expression. */ public abstract class Expression { diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java index 74ca47bf3610..24ef7914e569 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java @@ -24,9 +24,7 @@ package com.iluwatar.interpreter; /** - * - * MinusExpression - * + * MinusExpression. */ public class MinusExpression extends Expression { diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java index 4ff9d280500d..606937e0bb3a 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java @@ -24,9 +24,7 @@ package com.iluwatar.interpreter; /** - * - * MultiplyExpression - * + * MultiplyExpression. */ public class MultiplyExpression extends Expression { diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java index 035b8a70c406..6b957f6aa104 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java @@ -24,9 +24,7 @@ package com.iluwatar.interpreter; /** - * - * NumberExpression - * + * NumberExpression. */ public class NumberExpression extends Expression { diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java index d494a0d68b90..1ce0802599c2 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java @@ -24,9 +24,7 @@ package com.iluwatar.interpreter; /** - * - * PlusExpression - * + * PlusExpression. */ public class PlusExpression extends Expression { diff --git a/iterator/src/main/java/com/iluwatar/iterator/App.java b/iterator/src/main/java/com/iluwatar/iterator/App.java index 13f02f2d72b6..6e72b4ae991d 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/App.java +++ b/iterator/src/main/java/com/iluwatar/iterator/App.java @@ -39,8 +39,8 @@ /** * The Iterator pattern is a design pattern in which an iterator is used to traverse a container and * access the container's elements. The Iterator pattern decouples algorithms from containers. - *

- * In this example the Iterator ({@link Iterator}) adds abstraction layer on top of a collection + * + *

In this example the Iterator ({@link Iterator}) adds abstraction layer on top of a collection * ({@link TreasureChest}). This way the collection can change its internal implementation without * affecting its clients. */ @@ -85,7 +85,7 @@ private static TreeNode buildIntegerBst() { } /** - * Program entry point + * Program entry point. * * @param args command line args */ diff --git a/iterator/src/main/java/com/iluwatar/iterator/Iterator.java b/iterator/src/main/java/com/iluwatar/iterator/Iterator.java index 389d81e93acb..5f399c5b8f7c 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/Iterator.java +++ b/iterator/src/main/java/com/iluwatar/iterator/Iterator.java @@ -24,7 +24,8 @@ package com.iluwatar.iterator; /** - * Iterator interface to be implemented by iterators over various data structures + * Iterator interface to be implemented by iterators over various data structures. + * * @param generically typed for various objects */ public interface Iterator { 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 231c750c25c3..87511c7eaad3 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java +++ b/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java @@ -32,7 +32,7 @@ * expect to retrieve TreeNodes according to the Integer's natural ordering (1, 2, 3...) * * @param This Iterator has been implemented with generic typing to allow for TreeNodes of - * different value types + * different value types */ public class BstIterator> implements Iterator> { @@ -46,7 +46,7 @@ public BstIterator(TreeNode root) { /** * This BstIterator manages to use O(h) extra space, where h is the height of the tree It achieves * this by maintaining a stack of the nodes to handle (pushing all left nodes first), before - * handling self or right node + * handling self or right node. * * @param node TreeNode that acts as root of the subtree we're interested in. */ @@ -58,6 +58,8 @@ private void pushPathToNextSmallest(TreeNode node) { } /** + * Checks if there exists next element. + * * @return true if this iterator has a "next" element */ @Override @@ -66,6 +68,8 @@ public boolean hasNext() { } /** + * Gets the next element. + * * @return TreeNode next. The next element according to our in-order traversal of the given BST * @throws NoSuchElementException if this iterator does not have a next element */ 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 87e9fee0b5aa..9d03fdf86743 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java +++ b/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java @@ -36,7 +36,7 @@ public class TreeNode> { private TreeNode right; /** - * Creates a TreeNode with a given value, and null children + * Creates a TreeNode with a given value, and null children. * * @param val The value of the given node */ @@ -67,7 +67,7 @@ private void setRight(TreeNode right) { } /** - * Inserts new TreeNode based on a given value into the subtree represented by self + * Inserts new TreeNode based on a given value into the subtree represented by self. * * @param valToInsert The value to insert as a new TreeNode */ diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/Item.java b/iterator/src/main/java/com/iluwatar/iterator/list/Item.java index bd934e9f85fc..82e66eb30115 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/Item.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/Item.java @@ -24,9 +24,7 @@ package com.iluwatar.iterator.list; /** - * - * Item - * + * Item. */ public class Item { diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java b/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java index abb8e0fbb109..fc38046f79ec 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java @@ -24,9 +24,7 @@ package com.iluwatar.iterator.list; /** - * - * ItemType enumeration - * + * ItemType enumeration. */ public enum ItemType { diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java index 3fb93f5af804..f390c760f356 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java @@ -28,29 +28,27 @@ import java.util.List; /** - * * TreasureChest, the collection class. - * */ public class TreasureChest { private List items; /** - * Constructor + * Constructor. */ public TreasureChest() { items = List.of( - new Item(ItemType.POTION, "Potion of courage"), - new Item(ItemType.RING, "Ring of shadows"), - new Item(ItemType.POTION, "Potion of wisdom"), - new Item(ItemType.POTION, "Potion of blood"), - new Item(ItemType.WEAPON, "Sword of silver +1"), - new Item(ItemType.POTION, "Potion of rust"), - new Item(ItemType.POTION, "Potion of healing"), - new Item(ItemType.RING, "Ring of armor"), - new Item(ItemType.WEAPON, "Steel halberd"), - new Item(ItemType.WEAPON, "Dagger of poison")); + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); } public Iterator iterator(ItemType itemType) { @@ -58,7 +56,7 @@ public Iterator iterator(ItemType itemType) { } /** - * Get all items + * Get all items. */ public List getItems() { return new ArrayList<>(items); 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 9ae31e4274c1..43dbc82fa3b0 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java @@ -27,9 +27,7 @@ import java.util.List; /** - * - * TreasureChestItemIterator - * + * TreasureChestItemIterator. */ public class TreasureChestItemIterator implements Iterator { @@ -38,7 +36,7 @@ public class TreasureChestItemIterator implements Iterator { private ItemType type; /** - * Constructor + * Constructor. */ public TreasureChestItemIterator(TreasureChest chest, ItemType type) { this.chest = chest; From eae09fc07eb96e66b8227a23b9a09b3382943c95 Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 22:43:40 +0530 Subject: [PATCH 09/32] Resolves checkstyle errors for api-gateway, lazy-loading, leader-election (#1066) * Reduces checkstyle errors in lazy-loading * Reduces checkstyle errors in leader-election * Reduces checkstyle errors in api-gateway --- .../com/iluwatar/api/gateway/ApiGateway.java | 9 ++-- .../java/com/iluwatar/api/gateway/App.java | 47 ++++++++--------- .../iluwatar/api/gateway/DesktopProduct.java | 4 +- .../com/iluwatar/api/gateway/ImageClient.java | 2 +- .../iluwatar/api/gateway/ImageClientImpl.java | 10 ++-- .../iluwatar/api/gateway/MobileProduct.java | 2 +- .../com/iluwatar/api/gateway/PriceClient.java | 2 +- .../iluwatar/api/gateway/PriceClientImpl.java | 10 ++-- .../src/main/resources/application.properties | 1 - .../image/microservice/ImageApplication.java | 10 ++-- .../image/microservice/ImageController.java | 5 +- .../price/microservice/PriceApplication.java | 10 ++-- .../price/microservice/PriceController.java | 5 +- .../java/com/iluwatar/lazy/loading/App.java | 14 +++-- .../java/com/iluwatar/lazy/loading/Heavy.java | 4 +- .../iluwatar/lazy/loading/HolderNaive.java | 6 +-- .../lazy/loading/HolderThreadSafe.java | 6 +-- .../iluwatar/lazy/loading/Java8Holder.java | 7 ++- .../leaderelection/AbstractInstance.java | 16 +++--- .../AbstractMessageManager.java | 11 ++-- .../com/iluwatar/leaderelection/Instance.java | 5 +- .../com/iluwatar/leaderelection/Message.java | 5 +- .../leaderelection/MessageManager.java | 10 ++-- .../iluwatar/leaderelection/MessageType.java | 2 +- .../leaderelection/bully/BullyApp.java | 17 +++---- .../leaderelection/bully/BullyInstance.java | 34 +++++++------ .../bully/BullyMessageManager.java | 26 ++++++---- .../iluwatar/leaderelection/ring/RingApp.java | 17 +++---- .../leaderelection/ring/RingInstance.java | 51 ++++++++++--------- .../ring/RingMessageManager.java | 12 +++-- 30 files changed, 188 insertions(+), 172 deletions(-) diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java index 25c201521578..18a071c09f8a 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java @@ -23,12 +23,11 @@ package com.iluwatar.api.gateway; +import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.annotation.Resource; - /** * The ApiGateway aggregates calls to microservices based on the needs of the individual clients. */ @@ -42,7 +41,8 @@ public class ApiGateway { private PriceClient priceClient; /** - * Retrieves product information that desktop clients need + * Retrieves product information that desktop clients need. + * * @return Product information for clients on a desktop */ @RequestMapping(path = "/desktop", method = RequestMethod.GET) @@ -54,7 +54,8 @@ public DesktopProduct getProductDesktop() { } /** - * Retrieves product information that mobile clients need + * Retrieves product information that mobile clients need. + * * @return Product information for clients on a mobile device */ @RequestMapping(path = "/mobile", method = RequestMethod.GET) diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java index b92e3a7d0d36..1d72aaaece37 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java @@ -27,39 +27,36 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; /** - * With the Microservices pattern, a client may need data from multiple different microservices. - * If the client called each microservice directly, that could contribute to longer load times, - * since the client would have to make a network request for each microservice called. Moreover, - * having the client call each microservice directly ties the client to that microservice - if the - * internal implementations of the microservices change (for example, if two microservices are - * combined sometime in the future) or if the location (host and port) of a microservice changes, - * then every client that makes use of those microservices must be updated. + * With the Microservices pattern, a client may need data from multiple different microservices. If + * the client called each microservice directly, that could contribute to longer load times, since + * the client would have to make a network request for each microservice called. Moreover, having + * the client call each microservice directly ties the client to that microservice - if the internal + * implementations of the microservices change (for example, if two microservices are combined + * sometime in the future) or if the location (host and port) of a microservice changes, then every + * client that makes use of those microservices must be updated. * - *

- * The intent of the API Gateway pattern is to alleviate some of these issues. In the API Gateway - * pattern, an additional entity (the API Gateway) is placed between the client and the - * microservices. The job of the API Gateway is to aggregate the calls to the microservices. - * Rather than the client calling each microservice individually, the client calls the API Gateway - * a single time. The API Gateway then calls each of the microservices that the client needs. + *

The intent of the API Gateway pattern is to alleviate some of these issues. In the API + * Gateway pattern, an additional entity (the API Gateway) is placed between the client and the + * microservices. The job of the API Gateway is to aggregate the calls to the microservices. Rather + * than the client calling each microservice individually, the client calls the API Gateway a single + * time. The API Gateway then calls each of the microservices that the client needs. * - *

- * This implementation shows what the API Gateway pattern could look like for an e-commerce site. - * The {@link ApiGateway} makes calls to the Image and Price microservices using the - * {@link ImageClientImpl} and {@link PriceClientImpl} respectively. Customers viewing the site on a - * desktop device can see both price information and an image of a product, so the {@link ApiGateway} - * calls both of the microservices and aggregates the data in the {@link DesktopProduct} model. - * However, mobile users only see price information; they do not see a product image. For mobile - * users, the {@link ApiGateway} only retrieves price information, which it uses to populate the - * {@link MobileProduct}. + *

This implementation shows what the API Gateway pattern could look like for an e-commerce + * site. The {@link ApiGateway} makes calls to the Image and Price microservices using the {@link + * ImageClientImpl} and {@link PriceClientImpl} respectively. Customers viewing the site on a + * desktop device can see both price information and an image of a product, so the {@link + * ApiGateway} calls both of the microservices and aggregates the data in the {@link DesktopProduct} + * model. However, mobile users only see price information; they do not see a product image. For + * mobile users, the {@link ApiGateway} only retrieves price information, which it uses to populate + * the {@link MobileProduct}. */ @SpringBootApplication public class App { /** - * Program entry point + * Program entry point. * - * @param args - * command line args + * @param args command line args */ public static void main(String[] args) { SpringApplication.run(App.class, args); diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java index 06b9e949533d..2f790bef5d07 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java @@ -28,12 +28,12 @@ */ public class DesktopProduct { /** - * The price of the product + * The price of the product. */ private String price; /** - * The path to the image of the product + * The path to the image of the product. */ private String imagePath; diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java index 9c8c341ccd84..33e212b07050 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java @@ -24,7 +24,7 @@ package com.iluwatar.api.gateway; /** - * An interface used to communicate with the Image microservice + * An interface used to communicate with the Image microservice. */ public interface ImageClient { String getImagePath(); diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java index d2f80858cc49..6aa9698ef6d7 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java @@ -29,17 +29,16 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; - import org.springframework.stereotype.Component; /** - * An adapter to communicate with the Image microservice + * An adapter to communicate with the Image microservice. */ @Component public class ImageClientImpl implements ImageClient { /** - * Makes a simple HTTP Get request to the Image microservice - * + * Makes a simple HTTP Get request to the Image microservice. + * * @return The path to the image */ @Override @@ -47,7 +46,8 @@ public String getImagePath() { String response = null; HttpClient httpClient = HttpClient.newHttpClient(); - HttpRequest httpGet = HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50005/image-path")).build(); + HttpRequest httpGet = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50005/image-path")).build(); try { HttpResponse httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java index b7edb1047275..45fa4e4863e4 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java @@ -28,7 +28,7 @@ */ public class MobileProduct { /** - * The price of the product + * The price of the product. */ private String price; diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java index 74c564132939..ebe5150ba85a 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java @@ -24,7 +24,7 @@ package com.iluwatar.api.gateway; /** - * An interface used to communicate with the Price microservice + * An interface used to communicate with the Price microservice. */ public interface PriceClient { String getPrice(); diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java index 0a43c4b1fcfe..0c63e57f4789 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java @@ -29,17 +29,16 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; - import org.springframework.stereotype.Component; /** - * An adapter to communicate with the Price microservice + * An adapter to communicate with the Price microservice. */ @Component public class PriceClientImpl implements PriceClient { /** - * Makes a simple HTTP Get request to the Price microservice - * + * Makes a simple HTTP Get request to the Price microservice. + * * @return The price of the product */ @Override @@ -48,7 +47,8 @@ public String getPrice() { String response = null; HttpClient httpClient = HttpClient.newHttpClient(); - HttpRequest httpGet = HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50006/price")).build(); + HttpRequest httpGet = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50006/price")).build(); try { HttpResponse httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); diff --git a/api-gateway/api-gateway-service/src/main/resources/application.properties b/api-gateway/api-gateway-service/src/main/resources/application.properties index 35bbf3471cc2..f9e29f5a7234 100644 --- a/api-gateway/api-gateway-service/src/main/resources/application.properties +++ b/api-gateway/api-gateway-service/src/main/resources/application.properties @@ -20,5 +20,4 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # - server.port=50004 \ No newline at end of file diff --git a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java b/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java index bb551ac31ecb..12c00197605d 100644 --- a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java +++ b/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java @@ -27,16 +27,16 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; /** - * ImageApplication starts up Spring Boot, exposing endpoints for the Image microservice through - * the {@link ImageController}. + * ImageApplication starts up Spring Boot, exposing endpoints for the Image microservice through the + * {@link ImageController}. */ @SpringBootApplication public class ImageApplication { /** - * Microservice entry point - * @param args - * command line args + * Microservice entry point. + * + * @param args command line args */ public static void main(String[] args) { SpringApplication.run(ImageApplication.class, args); diff --git a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java b/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java index 9781dbc011aa..b1f6dd3f7eb6 100644 --- a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java +++ b/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java @@ -28,13 +28,14 @@ import org.springframework.web.bind.annotation.RestController; /** - * Exposes the Image microservice's endpoints + * Exposes the Image microservice's endpoints. */ @RestController public class ImageController { /** - * An endpoint for a user to retrieve an image path + * An endpoint for a user to retrieve an image path. + * * @return An image path */ @RequestMapping(value = "/image-path", method = RequestMethod.GET) diff --git a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java b/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java index 1a29e53c9e98..5fc6a0f96cc2 100644 --- a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java +++ b/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java @@ -27,16 +27,16 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; /** - * PriceApplication starts up Spring Boot, exposing endpoints for the Price microservice through - * the {@link PriceController}. + * PriceApplication starts up Spring Boot, exposing endpoints for the Price microservice through the + * {@link PriceController}. */ @SpringBootApplication public class PriceApplication { /** - * Microservice entry point - * @param args - * command line args + * Microservice entry point. + * + * @param args command line args */ public static void main(String[] args) { SpringApplication.run(PriceApplication.class, args); diff --git a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java b/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java index efb982253417..cf2f5eb4f83b 100644 --- a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java +++ b/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java @@ -28,13 +28,14 @@ import org.springframework.web.bind.annotation.RestController; /** - * Exposes the Price microservice's endpoints + * Exposes the Price microservice's endpoints. */ @RestController public class PriceController { /** - * An endpoint for a user to retrieve a product's price + * An endpoint for a user to retrieve a product's price. + * * @return A product's price */ @RequestMapping(value = "/price", method = RequestMethod.GET) diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java index ec795b40fe5d..ace157154082 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java @@ -27,22 +27,20 @@ import org.slf4j.LoggerFactory; /** - * * Lazy loading idiom defers object creation until needed. - *

- * This example shows different implementations of the pattern with increasing sophistication. - *

- * Additional information and lazy loading flavours are described in - * http://martinfowler.com/eaaCatalog/lazyLoad.html * + *

This example shows different implementations of the pattern with increasing sophistication. + * + *

Additional information and lazy loading flavours are described in + * http://martinfowler.com/eaaCatalog/lazyLoad.html */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java index 1e2dd8ae7fec..dea2d6341c22 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java @@ -27,16 +27,14 @@ import org.slf4j.LoggerFactory; /** - * * Heavy objects are expensive to create. - * */ public class Heavy { private static final Logger LOGGER = LoggerFactory.getLogger(Heavy.class); /** - * Constructor + * Constructor. */ public Heavy() { LOGGER.info("Creating Heavy ..."); diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java index a23f70fb7321..c18ced6d492f 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * Simple implementation of the lazy loading idiom. However, this is not thread safe. - * */ public class HolderNaive { @@ -38,14 +36,14 @@ public class HolderNaive { private Heavy heavy; /** - * Constructor + * Constructor. */ public HolderNaive() { LOGGER.info("HolderNaive created"); } /** - * Get heavy object + * Get heavy object. */ public Heavy getHeavy() { if (heavy == null) { diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java index b7c72e14c10c..ef6d5e663311 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java @@ -27,10 +27,8 @@ import org.slf4j.LoggerFactory; /** - * * Same as HolderNaive but with added synchronization. This implementation is thread safe, but each * {@link #getHeavy()} call costs additional synchronization overhead. - * */ public class HolderThreadSafe { @@ -39,14 +37,14 @@ public class HolderThreadSafe { private Heavy heavy; /** - * Constructor + * Constructor. */ public HolderThreadSafe() { LOGGER.info("HolderThreadSafe created"); } /** - * Get heavy object + * Get heavy object. */ public synchronized Heavy getHeavy() { if (heavy == null) { diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java index 5066b54792e7..2854a78228a3 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java @@ -23,16 +23,13 @@ package com.iluwatar.lazy.loading; +import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.function.Supplier; - /** - * * This lazy loader is thread safe and more efficient than {@link HolderThreadSafe}. It utilizes * Java 8 functional interface {@link Supplier} as {@link Heavy} factory. - * */ public class Java8Holder { @@ -57,9 +54,11 @@ public Heavy get() { return heavyInstance; } } + if (!HeavyFactory.class.isInstance(heavy)) { heavy = new HeavyFactory(); } + return heavy.get(); } } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java index d69a1f134bc1..f30610597b18 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java @@ -23,11 +23,10 @@ package com.iluwatar.leaderelection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Abstract class of all the instance implementation classes. @@ -69,7 +68,9 @@ public void run() { } /** - * Once messages are sent to the certain instance, it will firstly be added to the queue and wait to be executed. + * Once messages are sent to the certain instance, it will firstly be added to the queue and wait + * to be executed. + * * @param message Message sent by other instances */ @Override @@ -79,6 +80,7 @@ public void onMessage(Message message) { /** * Check if the instance is alive or not. + * * @return {@code true} if the instance is alive. */ @Override @@ -88,6 +90,7 @@ public boolean isAlive() { /** * Set the health status of the certain instance. + * * @param alive {@code true} for alive. */ @Override @@ -97,6 +100,7 @@ public void setAlive(boolean alive) { /** * Process the message according to its type. + * * @param message Message polled from queue. */ private void processMessage(Message message) { @@ -131,8 +135,8 @@ private void processMessage(Message message) { } /** - * Abstract methods to handle different types of message. These methods need to be implemented in concrete instance - * class to implement corresponding leader-selection pattern. + * Abstract methods to handle different types of message. These methods need to be implemented in + * concrete instance class to implement corresponding leader-selection pattern. */ protected abstract void handleElectionMessage(Message message); diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java index c7e4fa598cb6..ae2c2f380108 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java @@ -38,7 +38,7 @@ public abstract class AbstractMessageManager implements MessageManager { protected Map instanceMap; /** - * Construtor of AbstractMessageManager + * Construtor of AbstractMessageManager. */ public AbstractMessageManager(Map instanceMap) { this.instanceMap = instanceMap; @@ -46,15 +46,16 @@ public AbstractMessageManager(Map instanceMap) { /** * Find the next instance with smallest ID. + * * @return The next instance. */ protected Instance findNextInstance(int currentId) { Instance result = null; List candidateList = instanceMap.keySet() - .stream() - .filter((i) -> i > currentId && instanceMap.get(i).isAlive()) - .sorted() - .collect(Collectors.toList()); + .stream() + .filter((i) -> i > currentId && instanceMap.get(i).isAlive()) + .sorted() + .collect(Collectors.toList()); if (candidateList.isEmpty()) { int index = instanceMap.keySet() .stream() diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java index 1b39dff834f5..3ea57c04b0dc 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java @@ -24,24 +24,27 @@ package com.iluwatar.leaderelection; /** - * Instance interface + * Instance interface. */ public interface Instance { /** * Check if the instance is alive or not. + * * @return {@code true} if the instance is alive. */ boolean isAlive(); /** * Set the health status of the certain instance. + * * @param alive {@code true} for alive. */ void setAlive(boolean alive); /** * Consume messages from other instances. + * * @param message Message sent by other instances */ void onMessage(Message message); diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java b/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java index 1302d558857d..21f021aff900 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java @@ -26,7 +26,7 @@ import java.util.Objects; /** - * Message used to transport data between instances. + * Message used to transport data between instances. */ public class Message { @@ -34,7 +34,8 @@ public class Message { private String content; - public Message() {} + public Message() { + } public Message(MessageType type, String content) { this.type = type; diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java index fbd41cac970c..9f10de22e55c 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java @@ -24,12 +24,13 @@ package com.iluwatar.leaderelection; /** - * MessageManager interface + * MessageManager interface. */ public interface MessageManager { /** * Send heartbeat message to leader instance to check whether the leader instance is alive. + * * @param leaderId Instance ID of leader instance. * @return {@code true} if leader instance is alive, or {@code false} if not. */ @@ -37,22 +38,25 @@ public interface MessageManager { /** * Send election message to other instances. + * * @param currentId Instance ID of which sends this message. - * @param content Election message content. + * @param content Election message content. * @return {@code true} if the message is accepted by the target instances. */ boolean sendElectionMessage(int currentId, String content); /** * Send new leader notification message to other instances. + * * @param currentId Instance ID of which sends this message. - * @param leaderId Leader message content. + * @param leaderId Leader message content. * @return {@code true} if the message is accepted by the target instances. */ boolean sendLeaderMessage(int currentId, int leaderId); /** * Send heartbeat invoke message. This will invoke heartbeat task in the target instance. + * * @param currentId Instance ID of which sends this message. */ void sendHeartbeatInvokeMessage(int currentId); diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java index 1749ca15c66f..a82bfa38f15d 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java @@ -24,7 +24,7 @@ package com.iluwatar.leaderelection; /** - * Message Type enum + * Message Type enum. */ public enum MessageType { diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java index c111f442e7ad..34231b3d5a66 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java @@ -27,19 +27,18 @@ import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageManager; import com.iluwatar.leaderelection.MessageType; - import java.util.HashMap; import java.util.Map; /** * Example of how to use bully leader election. Initially 5 instances is created in the clould - * system, and the instance with ID 1 is set as leader. After the system is started stop the - * leader instance, and the new leader will be elected. + * system, and the instance with ID 1 is set as leader. After the system is started stop the leader + * instance, and the new leader will be elected. */ public class BullyApp { /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { @@ -60,11 +59,11 @@ public static void main(String[] args) { instance4.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); - Thread thread1 = new Thread(instance1); - Thread thread2 = new Thread(instance2); - Thread thread3 = new Thread(instance3); - Thread thread4 = new Thread(instance4); - Thread thread5 = new Thread(instance5); + final Thread thread1 = new Thread(instance1); + final Thread thread2 = new Thread(instance2); + final Thread thread3 = new Thread(instance3); + final Thread thread4 = new Thread(instance4); + final Thread thread5 = new Thread(instance5); thread1.start(); thread2.start(); diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java index c2c497339536..92cb18ab40b7 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java @@ -32,11 +32,11 @@ /** * Impelemetation with bully algorithm. Each instance should have a sequential id and is able to * communicate with other instances in the system. Initially the instance with smallest (or largest) - * ID is selected to be the leader. All the other instances send heartbeat message to leader periodically - * to check its health. If one certain instance finds the server done, it will send an election message - * to all the instances of which the ID is larger. If the target instance is alive, it will return an - * alive message (in this sample return true) and then send election message with its ID. If not, - * the original instance will send leader message to all the other instances. + * ID is selected to be the leader. All the other instances send heartbeat message to leader + * periodically to check its health. If one certain instance finds the server done, it will send an + * election message to all the instances of which the ID is larger. If the target instance is alive, + * it will return an alive message (in this sample return true) and then send election message with + * its ID. If not, the original instance will send leader message to all the other instances. */ public class BullyInstance extends AbstractInstance { @@ -50,9 +50,9 @@ public BullyInstance(MessageManager messageManager, int localId, int leaderId) { } /** - * Process the heartbeat invoke message. After receiving the message, the instance will send a heartbeat - * to leader to check its health. If alive, it will inform the next instance to do the heartbeat. If not, - * it will start the election process. + * Process the heartbeat invoke message. After receiving the message, the instance will send a + * heartbeat to leader to check its health. If alive, it will inform the next instance to do the + * heartbeat. If not, it will start the election process. */ @Override protected void handleHeartbeatInvokeMessage() { @@ -64,7 +64,8 @@ protected void handleHeartbeatInvokeMessage() { messageManager.sendHeartbeatInvokeMessage(localId); } else { LOGGER.info("Instance " + localId + "- Leader is not alive. Start election."); - boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); + boolean electionResult = + messageManager.sendElectionMessage(localId, String.valueOf(localId)); if (electionResult) { LOGGER.info("Instance " + localId + "- Succeed in election. Start leader notification."); messageManager.sendLeaderMessage(localId, localId); @@ -76,9 +77,9 @@ protected void handleHeartbeatInvokeMessage() { } /** - * Process election invoke message. Send election message to all the instances with smaller ID. If any - * one of them is alive, do nothing. If no instance alive, send leader message to all the alive instance - * and restart heartbeat. + * Process election invoke message. Send election message to all the instances with smaller ID. If + * any one of them is alive, do nothing. If no instance alive, send leader message to all the + * alive instance and restart heartbeat. */ @Override protected void handleElectionInvokeMessage() { @@ -111,11 +112,14 @@ private boolean isLeader() { * Not used in Bully instance. */ @Override - protected void handleLeaderInvokeMessage() {} + protected void handleLeaderInvokeMessage() { + } @Override - protected void handleHeartbeatMessage(Message message) {} + protected void handleHeartbeatMessage(Message message) { + } @Override - protected void handleElectionMessage(Message message) {} + protected void handleElectionMessage(Message message) { + } } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java index 907098f6b379..d1e4c7db13e8 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java @@ -27,13 +27,12 @@ import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; - import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** - * Implementation of BullyMessageManager + * Implementation of BullyMessageManager. */ public class BullyMessageManager extends AbstractMessageManager { @@ -46,6 +45,7 @@ public BullyMessageManager(Map instanceMap) { /** * Send heartbeat message to current leader instance to check the health. + * * @param leaderId leaderID * @return {@code true} if the leader is alive. */ @@ -58,8 +58,9 @@ public boolean sendHeartbeatMessage(int leaderId) { /** * Send election message to all the instances with smaller ID. + * * @param currentId Instance ID of which sends this message. - * @param content Election message content. + * @param content Election message content. * @return {@code true} if no alive instance has smaller ID, so that the election is accepted. */ @Override @@ -70,29 +71,31 @@ public boolean sendElectionMessage(int currentId, String content) { } else { Message electionMessage = new Message(MessageType.ELECTION_INVOKE, ""); candidateList.stream() - .forEach((i) -> instanceMap.get(i).onMessage(electionMessage)); + .forEach((i) -> instanceMap.get(i).onMessage(electionMessage)); return false; } } /** * Send leader message to all the instances to notify the new leader. + * * @param currentId Instance ID of which sends this message. - * @param leaderId Leader message content. + * @param leaderId Leader message content. * @return {@code true} if the message is accepted. */ @Override public boolean sendLeaderMessage(int currentId, int leaderId) { Message leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); instanceMap.keySet() - .stream() - .filter((i) -> i != currentId) - .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage)); + .stream() + .filter((i) -> i != currentId) + .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage)); return false; } /** * Send heartbeat invoke message to the next instance. + * * @param currentId Instance ID of which sends this message. */ @Override @@ -104,14 +107,15 @@ public void sendHeartbeatInvokeMessage(int currentId) { /** * Find all the alive instances with smaller ID than current instance. + * * @param currentId ID of current instance. * @return ID list of all the candidate instance. */ private List findElectionCandidateInstanceList(int currentId) { return instanceMap.keySet() - .stream() - .filter((i) -> i < currentId && instanceMap.get(i).isAlive()) - .collect(Collectors.toList()); + .stream() + .filter((i) -> i < currentId && instanceMap.get(i).isAlive()) + .collect(Collectors.toList()); } } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java index a8a6271eae15..096beb56641b 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java @@ -27,19 +27,18 @@ import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageManager; import com.iluwatar.leaderelection.MessageType; - import java.util.HashMap; import java.util.Map; /** * Example of how to use ring leader election. Initially 5 instances is created in the clould - * system, and the instance with ID 1 is set as leader. After the system is started stop the - * leader instance, and the new leader will be elected. + * system, and the instance with ID 1 is set as leader. After the system is started stop the leader + * instance, and the new leader will be elected. */ public class RingApp { /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { @@ -60,11 +59,11 @@ public static void main(String[] args) { instance2.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); - Thread thread1 = new Thread(instance1); - Thread thread2 = new Thread(instance2); - Thread thread3 = new Thread(instance3); - Thread thread4 = new Thread(instance4); - Thread thread5 = new Thread(instance5); + final Thread thread1 = new Thread(instance1); + final Thread thread2 = new Thread(instance2); + final Thread thread3 = new Thread(instance3); + final Thread thread4 = new Thread(instance4); + final Thread thread5 = new Thread(instance5); thread1.start(); thread2.start(); diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java index 4cdbb57090d8..903ac15ce4b1 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java @@ -26,23 +26,22 @@ import com.iluwatar.leaderelection.AbstractInstance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Implementation with token ring algorithm. The instances in the system are organized as a ring. * Each instance should have a sequential id and the instance with smallest (or largest) id should - * be the initial leader. All the other instances send heartbeat message to leader periodically - * to check its health. If one certain instance finds the server done, it will send an election - * message to the next alive instance in the ring, which contains its own ID. Then the next instance - * add its ID into the message and pass it to the next. After all the alive instances' ID are add - * to the message, the message is send back to the first instance and it will choose the instance - * with smallest ID to be the new leader, and then send a leader message to other instances to - * inform the result. + * be the initial leader. All the other instances send heartbeat message to leader periodically to + * check its health. If one certain instance finds the server done, it will send an election message + * to the next alive instance in the ring, which contains its own ID. Then the next instance add its + * ID into the message and pass it to the next. After all the alive instances' ID are add to the + * message, the message is send back to the first instance and it will choose the instance with + * smallest ID to be the new leader, and then send a leader message to other instances to inform the + * result. */ public class RingInstance extends AbstractInstance { @@ -56,9 +55,9 @@ public RingInstance(MessageManager messageManager, int localId, int leaderId) { } /** - * Process the heartbeat invoke message. After receiving the message, the instance will send a heartbeat - * to leader to check its health. If alive, it will inform the next instance to do the heartbeat. If not, - * it will start the election process. + * Process the heartbeat invoke message. After receiving the message, the instance will send a + * heartbeat to leader to check its health. If alive, it will inform the next instance to do the + * heartbeat. If not, it will start the election process. */ @Override protected void handleHeartbeatInvokeMessage() { @@ -78,9 +77,10 @@ protected void handleHeartbeatInvokeMessage() { } /** - * Process election message. If the local ID is contained in the ID list, the instance will select the - * alive instance with smallest ID to be the new leader, and send the leader inform message. If not, - * it will add its local ID to the list and send the message to the next instance in the ring. + * Process election message. If the local ID is contained in the ID list, the instance will select + * the alive instance with smallest ID to be the new leader, and send the leader inform message. + * If not, it will add its local ID to the list and send the message to the next instance in the + * ring. */ @Override protected void handleElectionMessage(Message message) { @@ -88,9 +88,9 @@ protected void handleElectionMessage(Message message) { LOGGER.info("Instance " + localId + " - Election Message: " + content); List candidateList = Arrays.stream(content.trim().split(",")) - .map(Integer::valueOf) - .sorted() - .collect(Collectors.toList()); + .map(Integer::valueOf) + .sorted() + .collect(Collectors.toList()); if (candidateList.contains(localId)) { int newLeaderId = candidateList.get(0); LOGGER.info("Instance " + localId + " - New leader should be " + newLeaderId + "."); @@ -102,8 +102,8 @@ protected void handleElectionMessage(Message message) { } /** - * Process leader Message. The instance will set the leader ID to be the new one and send the message to - * the next instance until all the alive instance in the ring is informed. + * Process leader Message. The instance will set the leader ID to be the new one and send the + * message to the next instance until all the alive instance in the ring is informed. */ @Override protected void handleLeaderMessage(Message message) { @@ -122,12 +122,15 @@ protected void handleLeaderMessage(Message message) { * Not used in Ring instance. */ @Override - protected void handleLeaderInvokeMessage() {} + protected void handleLeaderInvokeMessage() { + } @Override - protected void handleHeartbeatMessage(Message message) {} + protected void handleHeartbeatMessage(Message message) { + } @Override - protected void handleElectionInvokeMessage() {} + protected void handleElectionInvokeMessage() { + } } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java index 34496363372f..6cbadf184a2c 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java @@ -27,11 +27,10 @@ import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; - import java.util.Map; /** - * Implementation of RingMessageManager + * Implementation of RingMessageManager. */ public class RingMessageManager extends AbstractMessageManager { @@ -44,6 +43,7 @@ public RingMessageManager(Map instanceMap) { /** * Send heartbeat message to current leader instance to check the health. + * * @param leaderId leaderID * @return {@code true} if the leader is alive. */ @@ -56,8 +56,10 @@ public boolean sendHeartbeatMessage(int leaderId) { /** * Send election message to the next instance. + * * @param currentId currentID - * @param content list contains all the IDs of instances which have received this election message. + * @param content list contains all the IDs of instances which have received this election + * message. * @return {@code true} if the election message is accepted by the target instance. */ @Override @@ -70,8 +72,9 @@ public boolean sendElectionMessage(int currentId, String content) { /** * Send leader message to the next instance. + * * @param currentId Instance ID of which sends this message. - * @param leaderId Leader message content. + * @param leaderId Leader message content. * @return {@code true} if the leader message is accepted by the target instance. */ @Override @@ -84,6 +87,7 @@ public boolean sendLeaderMessage(int currentId, int leaderId) { /** * Send heartbeat invoke message to the next instance. + * * @param currentId Instance ID of which sends this message. */ @Override From 01e489c77bbe992a29455c50d898272ac65dfa5b Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 22:57:09 +0530 Subject: [PATCH 10/32] Resolves checkstyle errors for dao data-bus data-locality data-mapper data-transfer-object decorator (#1067) * Reduces checkstyle errors in dao * Reduces checkstyle errors in data-bus * Reduces checkstyle errors in data-locality * Reduces checkstyle errors in data-mapper * Reduces checkstyle errors in data-transfer-object * Reduces checkstyle errors in decorator --- dao/src/main/java/com/iluwatar/dao/App.java | 23 ++++----- .../com/iluwatar/dao/CustomException.java | 9 ++-- .../main/java/com/iluwatar/dao/Customer.java | 1 - .../java/com/iluwatar/dao/CustomerDao.java | 38 +++++++++------ .../com/iluwatar/dao/CustomerSchemaSql.java | 10 ++-- .../java/com/iluwatar/dao/DbCustomerDao.java | 47 ++++++++++--------- .../com/iluwatar/dao/InMemoryCustomerDao.java | 6 +-- .../main/java/com/iluwatar/databus/App.java | 46 +++++++++--------- .../iluwatar/databus/data/StartingData.java | 1 - .../iluwatar/databus/data/StoppingData.java | 1 - .../members/MessageCollectorMember.java | 1 - .../databus/members/StatusMember.java | 1 - .../iluwatar/data/locality/Application.java | 15 +++--- .../data/locality/game/GameEntity.java | 18 +++---- .../locality/game/component/AiComponent.java | 6 +-- .../locality/game/component/Component.java | 2 +- .../game/component/PhysicsComponent.java | 5 +- .../game/component/RenderComponent.java | 4 +- .../component/manager/AiComponentManager.java | 6 +-- .../manager/PhysicsComponentManager.java | 4 +- .../manager/RenderComponentManager.java | 6 +-- .../java/com/iluwatar/datamapper/App.java | 15 +++--- .../datamapper/DataMapperException.java | 5 +- .../java/com/iluwatar/datamapper/Student.java | 42 ++--------------- .../datamapper/StudentDataMapper.java | 2 +- .../datamapper/StudentDataMapperImpl.java | 5 +- .../datatransfer/CustomerClientApp.java | 21 ++++----- .../iluwatar/datatransfer/CustomerDto.java | 10 ++-- .../datatransfer/CustomerResource.java | 12 ++++- .../main/java/com/iluwatar/decorator/App.java | 14 +++--- .../com/iluwatar/decorator/ClubbedTroll.java | 2 +- .../com/iluwatar/decorator/SimpleTroll.java | 2 - .../java/com/iluwatar/decorator/Troll.java | 4 +- 33 files changed, 176 insertions(+), 208 deletions(-) diff --git a/dao/src/main/java/com/iluwatar/dao/App.java b/dao/src/main/java/com/iluwatar/dao/App.java index 78406208a77e..9faa8577a9ba 100644 --- a/dao/src/main/java/com/iluwatar/dao/App.java +++ b/dao/src/main/java/com/iluwatar/dao/App.java @@ -26,12 +26,9 @@ import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; -import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; - import javax.sql.DataSource; - import org.h2.jdbcx.JdbcDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,27 +41,25 @@ * application needs, in terms of domain-specific objects and data types (the public interface of * the DAO), from how these needs can be satisfied with a specific DBMS. * - *

With the DAO pattern, we can use various method calls to retrieve/add/delete/update data - * without directly interacting with the data source. The below example demonstrates basic CRUD + *

With the DAO pattern, we can use various method calls to retrieve/add/delete/update data + * without directly interacting with the data source. The below example demonstrates basic CRUD * operations: select, add, update, and delete. - * - * */ public class App { private static final String DB_URL = "jdbc:h2:~/dao"; private static Logger log = LoggerFactory.getLogger(App.class); private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): "; - + /** * Program entry point. - * + * * @param args command line args. - * @throws Exception if any error occurs. + * @throws Exception if any error occurs. */ public static void main(final String[] args) throws Exception { final CustomerDao inMemoryDao = new InMemoryCustomerDao(); performOperationsUsing(inMemoryDao); - + final DataSource dataSource = createDataSource(); createSchema(dataSource); final CustomerDao dbDao = new DbCustomerDao(dataSource); @@ -74,14 +69,14 @@ public static void main(final String[] args) throws Exception { private static void deleteSchema(DataSource dataSource) throws SQLException { try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { + Statement statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws SQLException { try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { + Statement statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); } } @@ -121,7 +116,7 @@ private static void addCustomers(CustomerDao customerDao) throws Exception { /** * Generate customers. - * + * * @return list of customers. */ public static List generateSampleCustomers() { diff --git a/dao/src/main/java/com/iluwatar/dao/CustomException.java b/dao/src/main/java/com/iluwatar/dao/CustomException.java index 3c1ec7373869..3da6ab20e7a1 100644 --- a/dao/src/main/java/com/iluwatar/dao/CustomException.java +++ b/dao/src/main/java/com/iluwatar/dao/CustomException.java @@ -24,20 +24,19 @@ package com.iluwatar.dao; /** - * - * Custom exception - * + * Custom exception. */ public class CustomException extends Exception { private static final long serialVersionUID = 1L; - public CustomException() {} + public CustomException() { + } public CustomException(String message) { super(message); } - + public CustomException(String message, Throwable cause) { super(message, cause); } diff --git a/dao/src/main/java/com/iluwatar/dao/Customer.java b/dao/src/main/java/com/iluwatar/dao/Customer.java index 593aacaf359c..dd84426eb19e 100644 --- a/dao/src/main/java/com/iluwatar/dao/Customer.java +++ b/dao/src/main/java/com/iluwatar/dao/Customer.java @@ -25,7 +25,6 @@ /** * A customer POJO that represents the data that will be read from the data source. - * */ public class Customer { diff --git a/dao/src/main/java/com/iluwatar/dao/CustomerDao.java b/dao/src/main/java/com/iluwatar/dao/CustomerDao.java index 7ff9a8e4e9cd..f5dc573ba008 100644 --- a/dao/src/main/java/com/iluwatar/dao/CustomerDao.java +++ b/dao/src/main/java/com/iluwatar/dao/CustomerDao.java @@ -28,37 +28,43 @@ /** * In an application the Data Access Object (DAO) is a part of Data access layer. It is an object - * that provides an interface to some type of persistence mechanism. By mapping application calls - * to the persistence layer, DAO provides some specific data operations without exposing details - * of the database. This isolation supports the Single responsibility principle. It separates what - * data accesses the application needs, in terms of domain-specific objects and data types - * (the public interface of the DAO), from how these needs can be satisfied with a specific DBMS, - * database schema, etc. - * - *

Any change in the way data is stored and retrieved will not change the client code as the + * that provides an interface to some type of persistence mechanism. By mapping application calls to + * the persistence layer, DAO provides some specific data operations without exposing details of the + * database. This isolation supports the Single responsibility principle. It separates what data + * accesses the application needs, in terms of domain-specific objects and data types (the public + * interface of the DAO), from how these needs can be satisfied with a specific DBMS, database + * schema, etc. + * + *

Any change in the way data is stored and retrieved will not change the client code as the * client will be using interface and need not worry about exact source. - * + * * @see InMemoryCustomerDao * @see DbCustomerDao */ public interface CustomerDao { /** - * @return all the customers as a stream. The stream may be lazily or eagerly evaluated based - * on the implementation. The stream must be closed after use. + * Get all customers. + * + * @return all the customers as a stream. The stream may be lazily or eagerly evaluated based on + * the implementation. The stream must be closed after use. * @throws Exception if any error occurs. */ Stream getAll() throws Exception; - + /** + * Get customer as Optional by id. + * * @param id unique identifier of the customer. - * @return an optional with customer if a customer with unique identifier id - * exists, empty optional otherwise. + * @return an optional with customer if a customer with unique identifier id exists, + * empty optional otherwise. * @throws Exception if any error occurs. */ Optional getById(int id) throws Exception; /** + * Add a customer. + * * @param customer the customer to be added. * @return true if customer is successfully added, false if customer already exists. * @throws Exception if any error occurs. @@ -66,6 +72,8 @@ public interface CustomerDao { boolean add(Customer customer) throws Exception; /** + * Update a customer. + * * @param customer the customer to be updated. * @return true if customer exists and is successfully updated, false otherwise. * @throws Exception if any error occurs. @@ -73,6 +81,8 @@ public interface CustomerDao { boolean update(Customer customer) throws Exception; /** + * Delete a customer. + * * @param customer the customer to be deleted. * @return true if customer exists and is successfully deleted, false otherwise. * @throws Exception if any error occurs. diff --git a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java b/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java index f05b9de217f7..633a65860ab7 100644 --- a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java +++ b/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java @@ -24,14 +24,16 @@ package com.iluwatar.dao; /** - * Customer Schema SQL Class + * Customer Schema SQL Class. */ public final class CustomerSchemaSql { - private CustomerSchemaSql() {} + private CustomerSchemaSql() { + } - public static final String CREATE_SCHEMA_SQL = "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), " - + "LNAME VARCHAR(100))"; + public static final String CREATE_SCHEMA_SQL = + "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), " + + "LNAME VARCHAR(100))"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE CUSTOMERS"; diff --git a/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java b/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java index 12e3acb20ac4..689a889fda76 100644 --- a/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java +++ b/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java @@ -23,9 +23,6 @@ package com.iluwatar.dao; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -36,12 +33,12 @@ import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; - import javax.sql.DataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * An implementation of {@link CustomerDao} that persists customers in RDBMS. - * */ public class DbCustomerDao implements CustomerDao { @@ -50,9 +47,9 @@ public class DbCustomerDao implements CustomerDao { private final DataSource dataSource; /** - * Creates an instance of {@link DbCustomerDao} which uses provided dataSource - * to store and retrieve customer information. - * + * Creates an instance of {@link DbCustomerDao} which uses provided dataSource to + * store and retrieve customer information. + * * @param dataSource a non-null dataSource. */ public DbCustomerDao(DataSource dataSource) { @@ -60,9 +57,11 @@ public DbCustomerDao(DataSource dataSource) { } /** - * @return a lazily populated stream of customers. Note the stream returned must be closed to - * free all the acquired resources. The stream keeps an open connection to the database till - * it is complete or is closed manually. + * Get all customers as Java Stream. + * + * @return a lazily populated stream of customers. Note the stream returned must be closed to free + * all the acquired resources. The stream keeps an open connection to the database till it is + * complete or is closed manually. */ @Override public Stream getAll() throws Exception { @@ -70,9 +69,10 @@ public Stream getAll() throws Exception { Connection connection; try { connection = getConnection(); - PreparedStatement statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR + PreparedStatement statement = + connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR ResultSet resultSet = statement.executeQuery(); // NOSONAR - return StreamSupport.stream(new Spliterators.AbstractSpliterator(Long.MAX_VALUE, + return StreamSupport.stream(new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { @Override @@ -108,8 +108,8 @@ private void mutedClose(Connection connection, PreparedStatement statement, Resu } private Customer createCustomer(ResultSet resultSet) throws SQLException { - return new Customer(resultSet.getInt("ID"), - resultSet.getString("FNAME"), + return new Customer(resultSet.getInt("ID"), + resultSet.getString("FNAME"), resultSet.getString("LNAME")); } @@ -122,8 +122,8 @@ public Optional getById(int id) throws Exception { ResultSet resultSet = null; try (Connection connection = getConnection(); - PreparedStatement statement = - connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) { + PreparedStatement statement = + connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) { statement.setInt(1, id); resultSet = statement.executeQuery(); @@ -151,8 +151,8 @@ public boolean add(Customer customer) throws Exception { } try (Connection connection = getConnection(); - PreparedStatement statement = - connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) { + PreparedStatement statement = + connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) { statement.setInt(1, customer.getId()); statement.setString(2, customer.getFirstName()); statement.setString(3, customer.getLastName()); @@ -169,8 +169,9 @@ public boolean add(Customer customer) throws Exception { @Override public boolean update(Customer customer) throws Exception { try (Connection connection = getConnection(); - PreparedStatement statement = - connection.prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) { + PreparedStatement statement = + connection + .prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) { statement.setString(1, customer.getFirstName()); statement.setString(2, customer.getLastName()); statement.setInt(3, customer.getId()); @@ -186,8 +187,8 @@ public boolean update(Customer customer) throws Exception { @Override public boolean delete(Customer customer) throws Exception { try (Connection connection = getConnection(); - PreparedStatement statement = - connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) { + PreparedStatement statement = + connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) { statement.setInt(1, customer.getId()); return statement.executeUpdate() > 0; } catch (SQLException ex) { diff --git a/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java b/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java index b6621ba392da..6dbfa367a9fe 100644 --- a/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java +++ b/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java @@ -29,8 +29,8 @@ import java.util.stream.Stream; /** - * An in memory implementation of {@link CustomerDao}, which stores the customers in JVM memory - * and data is lost when the application exits. + * An in memory implementation of {@link CustomerDao}, which stores the customers in JVM memory and + * data is lost when the application exits. *
* This implementation is useful as temporary database or for testing. */ @@ -56,7 +56,7 @@ public boolean add(final Customer customer) { if (getById(customer.getId()).isPresent()) { return false; } - + idToCustomer.put(customer.getId(), customer); return true; } diff --git a/data-bus/src/main/java/com/iluwatar/databus/App.java b/data-bus/src/main/java/com/iluwatar/databus/App.java index b645dbd34888..da4c6f07e726 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/App.java +++ b/data-bus/src/main/java/com/iluwatar/databus/App.java @@ -28,35 +28,33 @@ import com.iluwatar.databus.data.StoppingData; import com.iluwatar.databus.members.MessageCollectorMember; import com.iluwatar.databus.members.StatusMember; - import java.time.LocalDateTime; /** - * The Data Bus pattern - *

- * @see http://wiki.c2.com/?DataBusPattern - *

The Data-Bus pattern provides a method where different parts of an application may - * pass messages between each other without needing to be aware of the other's existence.

- *

Similar to the {@code ObserverPattern}, members register themselves with the {@link DataBus} - * and may then receive each piece of data that is published to the Data-Bus. The member - * may react to any given message or not.

- *

It allows for Many-to-Many distribution of data, as there may be any number of - * publishers to a Data-Bus, and any number of members receiving the data. All members - * will receive the same data, the order each receives a given piece of data, is an - * implementation detail.

- *

Members may unsubscribe from the Data-Bus to stop receiving data.

- *

This example of the pattern implements a Synchronous Data-Bus, meaning that - * when data is published to the Data-Bus, the publish method will not return until - * all members have received the data and returned.

- *

The {@link DataBus} class is a Singleton.

- *

Members of the Data-Bus must implement the {@link Member} interface.

- *

Data to be published via the Data-Bus must implement the {@link DataType} interface.

- *

The {@code data} package contains example {@link DataType} implementations.

- *

The {@code members} package contains example {@link Member} implementations.

- *

The {@link StatusMember} demonstrates using the DataBus to publish a message - * to the Data-Bus when it receives a message.

+ * The Data Bus pattern. * * @author Paul Campbell (pcampbell@kemitix.net) + * @see http://wiki.c2.com/?DataBusPattern + *

The Data-Bus pattern provides a method where different parts of an application may + * pass messages between each other without needing to be aware of the other's existence.

+ *

Similar to the {@code ObserverPattern}, members register themselves with the {@link + * DataBus} and may then receive each piece of data that is published to the Data-Bus. The + * member may react to any given message or not.

+ *

It allows for Many-to-Many distribution of data, as there may be any number of + * publishers to a Data-Bus, and any number of members receiving the data. All members will + * receive the same data, the order each receives a given piece of data, is an implementation + * detail.

+ *

Members may unsubscribe from the Data-Bus to stop receiving data.

+ *

This example of the pattern implements a Synchronous Data-Bus, meaning that + * when data is published to the Data-Bus, the publish method will not return until all members + * have received the data and returned.

+ *

The {@link DataBus} class is a Singleton.

+ *

Members of the Data-Bus must implement the {@link Member} interface.

+ *

Data to be published via the Data-Bus must implement the {@link DataType} interface.

+ *

The {@code data} package contains example {@link DataType} implementations.

+ *

The {@code members} package contains example {@link Member} implementations.

+ *

The {@link StatusMember} demonstrates using the DataBus to publish a message + * to the Data-Bus when it receives a message.

*/ class App { diff --git a/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java b/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java index 52de8b1f2d61..bd1f4c20f3d2 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java +++ b/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java @@ -25,7 +25,6 @@ import com.iluwatar.databus.AbstractDataType; import com.iluwatar.databus.DataType; - import java.time.LocalDateTime; /** diff --git a/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java b/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java index 5ca66743bbb1..41bb67482ce7 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java +++ b/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java @@ -25,7 +25,6 @@ import com.iluwatar.databus.AbstractDataType; import com.iluwatar.databus.DataType; - import java.time.LocalDateTime; /** diff --git a/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java b/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java index d242eedb81e0..332f6f935508 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java +++ b/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java @@ -26,7 +26,6 @@ import com.iluwatar.databus.DataType; import com.iluwatar.databus.Member; import com.iluwatar.databus.data.MessageData; - import java.util.ArrayList; import java.util.Collections; import java.util.List; diff --git a/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java b/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java index cc0f6851b7db..fffcde9c685f 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java +++ b/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java @@ -28,7 +28,6 @@ import com.iluwatar.databus.data.MessageData; import com.iluwatar.databus.data.StartingData; import com.iluwatar.databus.data.StoppingData; - import java.time.LocalDateTime; import java.util.logging.Logger; diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/Application.java b/data-locality/src/main/java/com/iluwatar/data/locality/Application.java index 53abb0f4b5bb..064465fc7d00 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/Application.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/Application.java @@ -28,22 +28,21 @@ import org.slf4j.LoggerFactory; /** - * Use the Data Locality pattern is when you have a performance problem. - * Take advantage of that to improve performance by increasing data locality — keeping data in - * contiguous memory in the order that you process it. - * - * Example: Game loop that processes a bunch of game entities. - * Those entities are decomposed into different domains  - * — AI, physics, and rendering — using the Component pattern. + * Use the Data Locality pattern is when you have a performance problem. Take advantage of that to + * improve performance by increasing data locality — keeping data in contiguous memory in the order + * that you process it. * + *

Example: Game loop that processes a bunch of game entities. Those entities are decomposed + * into different domains  — AI, physics, and rendering — using the Component pattern. */ public class Application { private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); private static final int NUM_ENTITIES = 5; + /** - * Start game loop with each component have NUM_ENTITIES instance + * Start game loop with each component have NUM_ENTITIES instance. */ public static void main(String[] args) { LOGGER.info("Start Game Application using Data-Locality pattern"); diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java index 33f139948522..337532175dc5 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java @@ -30,14 +30,14 @@ import org.slf4j.LoggerFactory; /** - * The game Entity maintains a big array of pointers . - * Each spin of the game loop, we need to run the following: + * The game Entity maintains a big array of pointers . Each spin of the game loop, we need to run + * the following: * - * Update the AI components . + *

Update the AI components. * - * Update the physics components for them. + *

Update the physics components for them. * - * Render them using their render components. + *

Render them using their render components. */ public class GameEntity { private static final Logger LOGGER = LoggerFactory.getLogger(GameEntity.class); @@ -47,7 +47,7 @@ public class GameEntity { private final RenderComponentManager renderComponentManager; /** - * Init components + * Init components. */ public GameEntity(int numEntities) { LOGGER.info("Init Game with #Entity : {}", numEntities); @@ -57,7 +57,7 @@ public GameEntity(int numEntities) { } /** - * start all component + * start all component. */ public void start() { LOGGER.info("Start Game"); @@ -67,7 +67,7 @@ public void start() { } /** - * update all component + * update all component. */ public void update() { LOGGER.info("Update Game Component"); @@ -80,5 +80,5 @@ public void update() { // Draw to screen. renderComponentManager.render(); } - + } diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java index c31f2ce662f2..5b1be9e35cc7 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java @@ -27,14 +27,14 @@ import org.slf4j.LoggerFactory; /** - * Implementation of AI component for Game + * Implementation of AI component for Game. */ public class AiComponent implements Component { - + private static final Logger LOGGER = LoggerFactory.getLogger(AiComponent.class); /** - * Update ai component + * Update ai component. */ @Override public void update() { diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java index c877fbe01e97..f159df4f651a 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java @@ -24,7 +24,7 @@ package com.iluwatar.data.locality.game.component; /** - * Implement different Game component update and render process + * Implement different Game component update and render process. */ public interface Component { diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java index 3c5f0950e37d..89c6f1503009 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java @@ -27,13 +27,14 @@ import org.slf4j.LoggerFactory; /** - * Implementation of Physics Component of Game + * Implementation of Physics Component of Game. */ public class PhysicsComponent implements Component { private static final Logger LOGGER = LoggerFactory.getLogger(PhysicsComponent.class); + /** - * update physics component of game + * update physics component of game. */ @Override public void update() { diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java index 0f3e0ca1ac40..0b49da056394 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java @@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory; /** - * Implementation of Render Component of Game + * Implementation of Render Component of Game. */ public class RenderComponent implements Component { @@ -39,7 +39,7 @@ public void update() { } /** - * render + * render. */ @Override public void render() { diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java index 1fc5419cc2d2..20fac010720a 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java @@ -29,7 +29,7 @@ import org.slf4j.LoggerFactory; /** - * AI component manager for Game + * AI component manager for Game. */ public class AiComponentManager { @@ -46,7 +46,7 @@ public AiComponentManager(int numEntities) { } /** - * start AI component of Game + * start AI component of Game. */ public void start() { LOGGER.info("Start AI Game Component"); @@ -56,7 +56,7 @@ public void start() { } /** - * Update AI component of Game + * Update AI component of Game. */ public void update() { LOGGER.info("Update AI Game Component"); diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java index 6ac6f5c095eb..36f762587984 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java @@ -46,7 +46,7 @@ public PhysicsComponentManager(int numEntities) { } /** - * Start physics component of Game + * Start physics component of Game. */ public void start() { LOGGER.info("Start Physics Game Component "); @@ -57,7 +57,7 @@ public void start() { /** - * Update physics component of Game + * Update physics component of Game. */ public void update() { LOGGER.info("Update Physics Game Component "); diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java index 7360f208b84d..fd6ef9640154 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java @@ -29,7 +29,7 @@ import org.slf4j.LoggerFactory; /** - * Render component manager for Game + * Render component manager for Game. */ public class RenderComponentManager { @@ -46,7 +46,7 @@ public RenderComponentManager(int numEntities) { } /** - * Start render component + * Start render component. */ public void start() { LOGGER.info("Start Render Game Component "); @@ -57,7 +57,7 @@ public void start() { /** - * render component + * render component. */ public void render() { LOGGER.info("Update Render Game Component "); diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/App.java b/data-mapper/src/main/java/com/iluwatar/datamapper/App.java index 50857729a49c..49d6c63d39df 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/App.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/App.java @@ -23,11 +23,10 @@ package com.iluwatar.datamapper; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Optional; - /** * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the * database. Its responsibility is to transfer data between the two and also to isolate them from @@ -35,19 +34,18 @@ * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , * Data Mapper itself is even unknown to the domain layer. - *

- * The below example demonstrates basic CRUD operations: Create, Read, Update, and Delete. - * + * + *

The below example demonstrates basic CRUD operations: Create, Read, Update, and Delete. */ public final class App { private static Logger log = LoggerFactory.getLogger(App.class); private static final String STUDENT_STRING = "App.main(), student : "; - + /** * Program entry point. - * + * * @param args command line args. */ public static void main(final String... args) { @@ -81,5 +79,6 @@ public static void main(final String... args) { mapper.delete(student); } - private App() {} + private App() { + } } diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java b/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java index 57aec04a85cc..4f354c7ebd10 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java @@ -26,9 +26,8 @@ /** * Using Runtime Exception for avoiding dependancy on implementation exceptions. This helps in * decoupling. - * - * @author amit.dixit * + * @author amit.dixit */ public final class DataMapperException extends RuntimeException { @@ -39,7 +38,7 @@ public final class DataMapperException extends RuntimeException { * initialized, and may subsequently be initialized by a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for later retrieval by the - * {@link #getMessage()} method. + * {@link #getMessage()} method. */ public DataMapperException(final String message) { super(message); diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java index e52d293ced99..5a368f9ce768 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java @@ -23,11 +23,10 @@ package com.iluwatar.datamapper; - import java.io.Serializable; /** - * Class defining Student + * Class defining Student. */ public final class Student implements Serializable { @@ -39,11 +38,11 @@ public final class Student implements Serializable { /** - * Use this constructor to create a Student with all details + * Use this constructor to create a Student with all details. * * @param studentId as unique student id - * @param name as student name - * @param grade as respective grade of student + * @param name as student name + * @param grade as respective grade of student */ public Student(final int studentId, final String name, final char grade) { this.studentId = studentId; @@ -51,57 +50,30 @@ public Student(final int studentId, final String name, final char grade) { this.grade = grade; } - /** - * - * @return the student id - */ public int getStudentId() { return studentId; } - /** - * - * @param studentId as unique student id - */ public void setStudentId(final int studentId) { this.studentId = studentId; } - /** - * - * @return name of student - */ public String getName() { return name; } - /** - * - * @param name as 'name' of student - */ public void setName(final String name) { this.name = name; } - /** - * - * @return grade of student - */ public char getGrade() { return grade; } - /** - * - * @param grade as 'grade of student' - */ public void setGrade(final char grade) { this.grade = grade; } - /** - * - */ @Override public boolean equals(final Object inputObject) { @@ -125,9 +97,6 @@ public boolean equals(final Object inputObject) { return isEqual; } - /** - * - */ @Override public int hashCode() { @@ -135,9 +104,6 @@ public int hashCode() { return this.getStudentId(); } - /** - * - */ @Override public String toString() { return "Student [studentId=" + studentId + ", name=" + name + ", grade=" + grade + "]"; diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java index 18ce1685c11e..3dfe4787fb9d 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java @@ -26,7 +26,7 @@ import java.util.Optional; /** - * Interface lists out the possible behaviour for all possible student mappers + * Interface lists out the possible behaviour for all possible student mappers. */ public interface StudentDataMapper { diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java index 117015f0020e..cc92ab81e7f9 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java @@ -28,7 +28,7 @@ import java.util.Optional; /** - * Implementation of Actions on Students Data + * Implementation of Actions on Students Data. */ public final class StudentDataMapperImpl implements StudentDataMapper { @@ -84,7 +84,8 @@ public void insert(Student studentToBeInserted) throws DataMapperException { } else { /* Throw user error after wrapping in a runtime exception */ - throw new DataMapperException("Student already [" + studentToBeInserted.getName() + "] exists"); + throw new DataMapperException("Student already [" + studentToBeInserted + .getName() + "] exists"); } } diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java index 7a660705a05f..860faf478da0 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java @@ -23,21 +23,20 @@ package com.iluwatar.datatransfer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * The Data Transfer Object pattern is a design pattern in which an data transfer object is used to serve related - * information together to avoid multiple call for each piece of information. - *

- * In this example, ({@link CustomerClientApp}) as as customer details consumer i.e. client to request for - * customer details to server. - *

- * CustomerResource ({@link CustomerResource}) act as server to serve customer information. - * And The CustomerDto ({@link CustomerDto} is data transfer object to share customer information. + * The Data Transfer Object pattern is a design pattern in which an data transfer object is used to + * serve related information together to avoid multiple call for each piece of information. + * + *

In this example, ({@link CustomerClientApp}) as as customer details consumer i.e. client to + * request for customer details to server. + * + *

CustomerResource ({@link CustomerResource}) act as server to serve customer information. And + * The CustomerDto ({@link CustomerDto} is data transfer object to share customer information. */ public class CustomerClientApp { diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerDto.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerDto.java index d05d970d29e8..a77eb8702774 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerDto.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerDto.java @@ -24,10 +24,10 @@ package com.iluwatar.datatransfer; /** - * {@link CustomerDto} is a data transfer object POJO. Instead of sending individual information to client - * We can send related information together in POJO. - *

- * Dto will not have any business logic in it. + * {@link CustomerDto} is a data transfer object POJO. Instead of sending individual information to + * client We can send related information together in POJO. + * + *

Dto will not have any business logic in it. */ public class CustomerDto { private final String id; @@ -35,6 +35,8 @@ public class CustomerDto { private final String lastName; /** + * Constructor. + * * @param id customer id * @param firstName customer first name * @param lastName customer last name diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java index 5dee3c8f8d5e..7e4b8340d1e5 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java @@ -26,13 +26,15 @@ import java.util.List; /** - * The resource class which serves customer information. - * This class act as server in the demo. Which has all customer details. + * The resource class which serves customer information. This class act as server in the demo. Which + * has all customer details. */ public class CustomerResource { private List customers; /** + * Initialise resource with existing customers. + * * @param customers initialize resource with existing customers. Act as database. */ public CustomerResource(List customers) { @@ -40,6 +42,8 @@ public CustomerResource(List customers) { } /** + * Get all customers. + * * @return : all customers in list. */ public List getAllCustomers() { @@ -47,6 +51,8 @@ public List getAllCustomers() { } /** + * Save new customer. + * * @param customer save new customer to list. */ public void save(CustomerDto customer) { @@ -54,6 +60,8 @@ public void save(CustomerDto customer) { } /** + * Delete customer with given id. + * * @param customerId delete customer with id {@code customerId} */ public void delete(String customerId) { diff --git a/decorator/src/main/java/com/iluwatar/decorator/App.java b/decorator/src/main/java/com/iluwatar/decorator/App.java index 82a44bc1158d..348e5623d4c3 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/App.java +++ b/decorator/src/main/java/com/iluwatar/decorator/App.java @@ -27,24 +27,22 @@ import org.slf4j.LoggerFactory; /** - * * The Decorator pattern is a more flexible alternative to subclassing. The Decorator class * implements the same interface as the target and uses aggregation to "decorate" calls to the * target. Using the Decorator pattern it is possible to change the behavior of the class during * runtime. - *

- * In this example we show how the simple {@link SimpleTroll} first attacks and then flees the battle. - * Then we decorate the {@link SimpleTroll} with a {@link ClubbedTroll} and perform the attack again. You - * can see how the behavior changes after the decoration. - * + * + *

In this example we show how the simple {@link SimpleTroll} first attacks and then flees the + * battle. Then we decorate the {@link SimpleTroll} with a {@link ClubbedTroll} and perform the + * attack again. You can see how the behavior changes after the decoration. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java index 90eb893a7ab5..70fd15489e30 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java @@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory; /** - * Decorator that adds a club for the troll + * Decorator that adds a club for the troll. */ public class ClubbedTroll implements Troll { diff --git a/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java b/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java index e2095a2adca9..08eed94fc5c4 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * SimpleTroll implements {@link Troll} interface directly. - * */ public class SimpleTroll implements Troll { diff --git a/decorator/src/main/java/com/iluwatar/decorator/Troll.java b/decorator/src/main/java/com/iluwatar/decorator/Troll.java index faeca11c93c9..43f9ac916072 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/Troll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/Troll.java @@ -24,9 +24,7 @@ package com.iluwatar.decorator; /** - * - * Interface for trolls - * + * Interface for trolls. */ public interface Troll { From f2c91eb8364655caf9f595e5ddde449107a6ea96 Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 23:01:20 +0530 Subject: [PATCH 11/32] Resolves checkstyle errors for delegation dependency-injection dirty-flag double-buffer double-checked-locking double-dispatch (#1068) * Reduces checkstyle errors in delegation * Reduces checkstyle errors in dependency-injection * Reduces checkstyle errors in dirty-flag * Reduces checkstyle errors in double-buffer * Reduces checkstyle errors in double-checked-locking * Reduces checkstyle errors in double-dispatch --- .../com/iluwatar/delegation/simple/App.java | 22 ++++---- .../iluwatar/delegation/simple/Printer.java | 3 +- .../delegation/simple/PrinterController.java | 16 +++--- .../simple/printers/CanonPrinter.java | 4 +- .../simple/printers/EpsonPrinter.java | 4 +- .../delegation/simple/printers/HpPrinter.java | 4 +- .../injection/AdvancedSorceress.java | 24 --------- .../dependency/injection/AdvancedWizard.java | 2 - .../iluwatar/dependency/injection/App.java | 25 ++++----- .../dependency/injection/GuiceWizard.java | 2 - .../dependency/injection/OldTobyTobacco.java | 4 +- .../injection/RivendellTobacco.java | 4 +- .../injection/SecondBreakfastTobacco.java | 4 +- .../dependency/injection/SimpleWizard.java | 2 - .../dependency/injection/Tobacco.java | 4 +- .../dependency/injection/TobaccoModule.java | 2 - .../iluwatar/dependency/injection/Wizard.java | 4 +- .../main/java/com/iluwatar/dirtyflag/App.java | 51 ++++++++++--------- .../com/iluwatar/dirtyflag/DataFetcher.java | 11 ++-- .../java/com/iluwatar/dirtyflag/World.java | 7 +-- .../java/com/iluwatar/doublebuffer/App.java | 19 ++++--- .../com/iluwatar/doublebuffer/Buffer.java | 3 ++ .../iluwatar/doublebuffer/FrameBuffer.java | 3 -- .../java/com/iluwatar/doublebuffer/Scene.java | 4 +- .../iluwatar/doublechecked/locking/App.java | 20 ++++---- .../doublechecked/locking/Inventory.java | 18 +++---- .../iluwatar/doublechecked/locking/Item.java | 4 +- .../java/com/iluwatar/doubledispatch/App.java | 49 +++++++++--------- .../doubledispatch/FlamingAsteroid.java | 4 +- .../iluwatar/doubledispatch/GameObject.java | 2 - .../iluwatar/doubledispatch/Meteoroid.java | 13 +++-- .../iluwatar/doubledispatch/Rectangle.java | 4 +- .../doubledispatch/SpaceStationIss.java | 4 +- .../doubledispatch/SpaceStationMir.java | 19 ++++--- .../constants/AppConstants.java | 4 +- 35 files changed, 154 insertions(+), 215 deletions(-) diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/App.java b/delegation/src/main/java/com/iluwatar/delegation/simple/App.java index af734bb41449..b568c836f668 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/App.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/App.java @@ -28,23 +28,25 @@ import com.iluwatar.delegation.simple.printers.HpPrinter; /** - * The delegate pattern provides a mechanism to abstract away the implementation and control of the desired action. - * The class being called in this case {@link PrinterController} is not responsible for the actual desired action, - * but is actually delegated to a helper class either {@link CanonPrinter}, {@link EpsonPrinter} or {@link HpPrinter}. - * The consumer does not have or require knowledge of the actual class carrying out the action, only the - * container on which they are calling. + * The delegate pattern provides a mechanism to abstract away the implementation and control of the + * desired action. The class being called in this case {@link PrinterController} is not responsible + * for the actual desired action, but is actually delegated to a helper class either {@link + * CanonPrinter}, {@link EpsonPrinter} or {@link HpPrinter}. The consumer does not have or require + * knowledge of the actual class carrying out the action, only the container on which they are + * calling. * - * In this example the delegates are {@link EpsonPrinter}, {@link HpPrinter} and {@link CanonPrinter} they all implement - * {@link Printer}. The {@link PrinterController} class also implements {@link Printer}. However neither provide the - * functionality of {@link Printer} by printing to the screen, they actually call upon the instance of {@link Printer} - * that they were instantiated with. Therefore delegating the behaviour to another class. + *

In this example the delegates are {@link EpsonPrinter}, {@link HpPrinter} and {@link + * CanonPrinter} they all implement {@link Printer}. The {@link PrinterController} class also + * implements {@link Printer}. However neither provide the functionality of {@link Printer} by + * printing to the screen, they actually call upon the instance of {@link Printer} that they were + * instantiated with. Therefore delegating the behaviour to another class. */ public class App { private static final String MESSAGE_TO_PRINT = "hello world"; /** - * Program entry point + * Program entry point. * * @param args command line args */ diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java b/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java index bc6f50879798..f3f434adb478 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java @@ -38,7 +38,8 @@ public interface Printer { /** * Method that takes a String to print to the screen. This will be implemented on both the - * controller and the delegate allowing the controller to call the same method on the delegate class. + * controller and the delegate allowing the controller to call the same method on the delegate + * class. * * @param message to be printed to the screen */ diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java b/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java index 315b6ee585a3..add1d71e6a11 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java @@ -24,10 +24,10 @@ package com.iluwatar.delegation.simple; /** - * Delegator Class to delegate the implementation of the Printer. - * This ensures two things: - * - when the actual implementation of the Printer class changes the delegation will still be operational - * - the actual benefit is observed when there are more than one implementors and they share a delegation control + * Delegator Class to delegate the implementation of the Printer. This ensures two things: - when + * the actual implementation of the Printer class changes the delegation will still be operational - + * the actual benefit is observed when there are more than one implementors and they share a + * delegation control */ public class PrinterController implements Printer { @@ -38,10 +38,10 @@ public PrinterController(Printer printer) { } /** - * This method is implemented from {@link Printer} however instead on providing an - * implementation, it instead calls upon the class passed through the constructor. This is the delegate, - * hence the pattern. Therefore meaning that the caller does not care of the implementing class only the owning - * controller. + * This method is implemented from {@link Printer} however instead on providing an implementation, + * it instead calls upon the class passed through the constructor. This is the delegate, hence the + * pattern. Therefore meaning that the caller does not care of the implementing class only the + * owning controller. * * @param message to be printed to the screen */ diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java index 9188fc988509..5d7c59c863c7 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java @@ -28,8 +28,8 @@ import org.slf4j.LoggerFactory; /** - * Specialised Implementation of {@link Printer} for a Canon Printer, in - * this case the message to be printed is appended to "Canon Printer : " + * Specialised Implementation of {@link Printer} for a Canon Printer, in this case the message to be + * printed is appended to "Canon Printer : ". * * @see Printer */ diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java index a29c0b224644..67bd00ac8881 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java @@ -28,8 +28,8 @@ import org.slf4j.LoggerFactory; /** - * Specialised Implementation of {@link Printer} for a Epson Printer, in - * this case the message to be printed is appended to "Epson Printer : " + * Specialised Implementation of {@link Printer} for a Epson Printer, in this case the message to be + * printed is appended to "Epson Printer : ". * * @see Printer */ diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java index cb0a8068d9ce..082e0054a2f1 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java @@ -28,8 +28,8 @@ import org.slf4j.LoggerFactory; /** - * Specialised Implementation of {@link Printer} for a HP Printer, in - * this case the message to be printed is appended to "HP Printer : " + * Specialised Implementation of {@link Printer} for a HP Printer, in this case the message to be + * printed is appended to "HP Printer : ". * * @see Printer */ diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java index 0009cfadccf8..31f4e78bfc29 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java @@ -23,30 +23,6 @@ package com.iluwatar.dependency.injection; -/** - * The MIT License - * Copyright (c) 2014-2017 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. - */ - - /** * AdvancedSorceress implements inversion of control. It depends on abstraction that can be injected * through its setter. diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java index e57222b1994f..e0c952186830 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java @@ -24,10 +24,8 @@ package com.iluwatar.dependency.injection; /** - * * AdvancedWizard implements inversion of control. It depends on abstraction that can be injected * through its constructor. - * */ public class AdvancedWizard implements Wizard { diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java index 0c829b98ba8b..79c6400b12f9 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java @@ -31,25 +31,26 @@ * implements so called inversion of control principle. Inversion of control has two specific rules: * - High-level modules should not depend on low-level modules. Both should depend on abstractions. * - Abstractions should not depend on details. Details should depend on abstractions. - *

- * In this example we show you three different wizards. The first one ({@link SimpleWizard}) is a - * naive implementation violating the inversion of control principle. It depends directly on a + * + *

In this example we show you three different wizards. The first one ({@link SimpleWizard}) is + * a naive implementation violating the inversion of control principle. It depends directly on a * concrete implementation which cannot be changed. - *

- * The second and third wizards({@link AdvancedWizard} and {@link AdvancedSorceress}) are more flexible. - * They do not depend on any concrete implementation but abstraction. They utilizes Dependency Injection - * pattern allowing their {@link Tobacco} dependency to be injected through constructor ({@link AdvancedWizard}) - * or setter ({@link AdvancedSorceress}). This way, handling the dependency is no longer the wizard's - * responsibility. It is resolved outside the wizard class. - *

- * The fourth example takes the pattern a step further. It uses Guice framework for Dependency + * + *

The second and third wizards({@link AdvancedWizard} and {@link AdvancedSorceress}) are more + * flexible. They do not depend on any concrete implementation but abstraction. They utilizes + * Dependency Injection pattern allowing their {@link Tobacco} dependency to be injected through + * constructor ({@link AdvancedWizard}) or setter ({@link AdvancedSorceress}). This way, handling + * the dependency is no longer the wizard's responsibility. It is resolved outside the wizard + * class. + * + *

The fourth example takes the pattern a step further. It uses Guice framework for Dependency * Injection. {@link TobaccoModule} binds a concrete implementation to abstraction. Injector is then * used to create {@link GuiceWizard} object with correct dependencies. */ public class App { /** - * Program entry point + * Program entry point. * * @param args command line args */ diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java index 33776ed1d61e..319a635eb41e 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java @@ -26,10 +26,8 @@ import javax.inject.Inject; /** - * * GuiceWizard implements inversion of control. Its dependencies are injected through its * constructor by Guice framework. - * */ public class GuiceWizard implements Wizard { diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java index b198a4c5013f..3f242ea60744 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java @@ -24,9 +24,7 @@ package com.iluwatar.dependency.injection; /** - * - * OldTobyTobacco concrete {@link Tobacco} implementation - * + * OldTobyTobacco concrete {@link Tobacco} implementation. */ public class OldTobyTobacco extends Tobacco { } diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java index 37c17fbfd19a..50ef5e2c5d86 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java @@ -24,9 +24,7 @@ package com.iluwatar.dependency.injection; /** - * - * RivendellTobacco concrete {@link Tobacco} implementation - * + * RivendellTobacco concrete {@link Tobacco} implementation. */ public class RivendellTobacco extends Tobacco { } diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java index 9845c0381b4c..622958615ae3 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java @@ -24,9 +24,7 @@ package com.iluwatar.dependency.injection; /** - * - * SecondBreakfastTobacco concrete {@link Tobacco} implementation - * + * SecondBreakfastTobacco concrete {@link Tobacco} implementation. */ public class SecondBreakfastTobacco extends Tobacco { } diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java index ef7dbd144f72..40bca0ffb65c 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java @@ -24,10 +24,8 @@ package com.iluwatar.dependency.injection; /** - * * Naive Wizard implementation violating the inversion of control principle. It should depend on * abstraction instead. - * */ public class SimpleWizard implements Wizard { diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java index c3549b6a09d9..aaef6ba2aa92 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * Tobacco abstraction - * + * Tobacco abstraction. */ public abstract class Tobacco { diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java index 78b43ffa9803..43cadc071fb9 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java @@ -26,9 +26,7 @@ import com.google.inject.AbstractModule; /** - * * Guice module for binding certain concrete {@link Tobacco} implementation. - * */ public class TobaccoModule extends AbstractModule { diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java index 6bdca74156e2..0575118a517b 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java @@ -24,9 +24,7 @@ package com.iluwatar.dependency.injection; /** - * - * Wizard interface - * + * Wizard interface. */ public interface Wizard { diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java index 7caaca5618ae..cc9a6940692a 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java @@ -23,45 +23,49 @@ package com.iluwatar.dirtyflag; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** + * This application demonstrates the Dirty Flag pattern. The dirty flag behavioral pattern + * allows you to avoid expensive operations that would just need to be done again anyway. This is a + * simple pattern that really just explains how to add a bool value to your class that you can set + * anytime a property changes. This will let your class know that any results it may have previously + * calculated will need to be calculated again when they’re requested. Once the results are + * re-calculated, then the bool value can be cleared. * - * This application demonstrates the Dirty Flag pattern. The dirty flag behavioral pattern allows you to avoid - * expensive operations that would just need to be done again anyway. This is a simple pattern that really just explains - * how to add a bool value to your class that you can set anytime a property changes. This will let your class know that - * any results it may have previously calculated will need to be calculated again when they’re requested. Once the - * results are re-calculated, then the bool value can be cleared. - * - * There are some points that need to be considered before diving into using this pattern:- there are some things you’ll - * need to consider:- (1) Do you need it? This design pattern works well when the results to be calculated are difficult - * or resource intensive to compute. You want to save them. You also don’t want to be calculating them several times in - * a row when only the last one counts. (2) When do you set the dirty flag? Make sure that you set the dirty flag within - * the class itself whenever an important property changes. This property should affect the result of the calculated - * result and by changing the property, that makes the last result invalid. (3) When do you clear the dirty flag? It - * might seem obvious that the dirty flag should be cleared whenever the result is calculated with up-to-date - * information but there are other times when you might want to clear the flag. + *

There are some points that need to be considered before diving into using this pattern:- + * there are some things you’ll need to consider:- (1) Do you need it? This design pattern works + * well when the results to be calculated are difficult or resource intensive to compute. You want + * to save them. You also don’t want to be calculating them several times in a row when only the + * last one counts. (2) When do you set the dirty flag? Make sure that you set the dirty flag within + * the class itself whenever an important property changes. This property should affect the result + * of the calculated result and by changing the property, that makes the last result invalid. (3) + * When do you clear the dirty flag? It might seem obvious that the dirty flag should be cleared + * whenever the result is calculated with up-to-date information but there are other times when you + * might want to clear the flag. * - * In this example, the {@link DataFetcher} holds the dirty flag. It fetches and re-fetches from world.txt - * when needed. {@link World} mainly serves the data to the front-end. + *

In this example, the {@link DataFetcher} holds the dirty flag. It fetches and + * re-fetches from world.txt when needed. {@link World} mainly serves the data to the + * front-end. */ public class App { - + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** - * Program execution point + * Program execution point. */ public void run() { final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleAtFixedRate(new Runnable() { final World world = new World(); + @Override public void run() { List countries = world.fetch(); @@ -74,10 +78,9 @@ public void run() { } /** - * Program entry point + * Program entry point. * - * @param args - * command line args + * @param args command line args */ public static void main(String[] args) { App app = new App(); diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java index d9b303b0bc4c..cc9f2aa83813 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java @@ -23,22 +23,19 @@ package com.iluwatar.dirtyflag; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.xml.crypto.Data; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * A mock database manager -- Fetches data from a raw file. - * - * @author swaisuan * + * @author swaisuan */ public class DataFetcher { @@ -61,7 +58,7 @@ private boolean isDirty(long fileLastModified) { /** * Fetches data/content from raw file. - * + * * @return List of strings */ public List fetch() { diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java index 56255a505cd5..189657703e42 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java @@ -27,11 +27,9 @@ import java.util.List; /** - * * A middle-layer app that calls/passes along data from the back-end. - * - * @author swaisuan * + * @author swaisuan */ public class World { @@ -44,9 +42,8 @@ public World() { } /** - * * Calls {@link DataFetcher} to fetch data from back-end. - * + * * @return List of strings */ public List fetch() { diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java index 2e69e6eb4e98..636da3eb1d26 100644 --- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java @@ -23,21 +23,19 @@ package com.iluwatar.doublebuffer; +import java.util.ArrayList; +import java.util.List; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.List; - /** - * Double buffering is a term used to describe a device that has two buffers. - * The usage of multiple buffers increases the overall throughput of a device - * and helps prevents bottlenecks. This example shows using double buffer pattern - * on graphics. It is used to show one image or frame while a separate frame - * is being buffered to be shown next. This method makes animations and games - * look more realistic than the same done in a single buffer mode. + * Double buffering is a term used to describe a device that has two buffers. The usage of multiple + * buffers increases the overall throughput of a device and helps prevents bottlenecks. This example + * shows using double buffer pattern on graphics. It is used to show one image or frame while a + * separate frame is being buffered to be shown next. This method makes animations and games look + * more realistic than the same done in a single buffer mode. */ public class App { @@ -45,10 +43,11 @@ public class App { /** * Program main entry point. + * * @param args runtime arguments */ public static void main(String[] args) { - var scene = new Scene(); + final var scene = new Scene(); List> drawPixels = new ArrayList<>(); Pair pixel1 = new MutablePair<>(1, 1); Pair pixel2 = new MutablePair<>(5, 6); diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java index b0c7d998b2b5..78877c3d9f32 100644 --- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java @@ -30,6 +30,7 @@ public interface Buffer { /** * Clear the pixel in (x, y). + * * @param x X coordinate * @param y Y coordinate */ @@ -37,6 +38,7 @@ public interface Buffer { /** * Draw the pixel in (x, y). + * * @param x X coordinate * @param y Y coordinate */ @@ -49,6 +51,7 @@ public interface Buffer { /** * Get all the pixels. + * * @return pixel list */ Pixel[] getPixels(); diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java index 95925808ba1e..aea4144dc4f7 100644 --- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java @@ -23,9 +23,6 @@ package com.iluwatar.doublebuffer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * FrameBuffer implementation class. */ diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java index fe4a63fbfade..412b63b0c9ae 100644 --- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java @@ -23,12 +23,11 @@ package com.iluwatar.doublebuffer; +import java.util.List; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; - /** * Scene class. Render the output frame. */ @@ -55,6 +54,7 @@ public Scene() { /** * Draw the next frame. + * * @param coordinateList list of pixels of which the color should be black */ public void draw(List> coordinateList) { diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java index 92186fc22da2..745654796abd 100644 --- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java +++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java @@ -23,32 +23,30 @@ package com.iluwatar.doublechecked.locking; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * * Double Checked Locking is a concurrency design pattern used to reduce the overhead of acquiring a * lock by first testing the locking criterion (the "lock hint") without actually acquiring the * lock. Only if the locking criterion check indicates that locking is required does the actual * locking logic proceed. - *

- * In {@link Inventory} we store the items with a given size. However, we do not store more items - * than the inventory size. To address concurrent access problems we use double checked locking to - * add item to inventory. In this method, the thread which gets the lock first adds the item. - * + * + *

In {@link Inventory} we store the items with a given size. However, we do not store more + * items than the inventory size. To address concurrent access problems we use double checked + * locking to add item to inventory. In this method, the thread which gets the lock first adds the + * item. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java index c13908b193fd..17b47fa430d5 100644 --- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java +++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java @@ -23,19 +23,16 @@ package com.iluwatar.doublechecked.locking; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * - * Inventory - * + * Inventory. */ public class Inventory { @@ -46,7 +43,7 @@ public class Inventory { private final Lock lock; /** - * Constructor + * Constructor. */ public Inventory(int inventorySize) { this.inventorySize = inventorySize; @@ -55,7 +52,7 @@ public Inventory(int inventorySize) { } /** - * Add item + * Add item. */ public boolean addItem(Item item) { if (items.size() < inventorySize) { @@ -63,7 +60,8 @@ public boolean addItem(Item item) { try { if (items.size() < inventorySize) { items.add(item); - LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items.size(), inventorySize); + LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items + .size(), inventorySize); return true; } } finally { @@ -74,7 +72,7 @@ public boolean addItem(Item item) { } /** - * Get all the items in the inventory + * Get all the items in the inventory. * * @return All the items of the inventory, as an unmodifiable list */ diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java index c2c5559d05a2..ecedc535fde5 100644 --- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java +++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java @@ -24,9 +24,7 @@ package com.iluwatar.doublechecked.locking; /** - * - * Item - * + * Item. */ public class Item { } diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java index e6b670a6d524..9117ede47af9 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java @@ -23,46 +23,45 @@ package com.iluwatar.doubledispatch; +import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; - /** - * - * When a message with a parameter is sent to an object, the resultant behaviour is defined by the implementation of - * that method in the receiver. Sometimes the behaviour must also be determined by the type of the parameter. - *

- * One way to implement this would be to create multiple instanceof-checks for the methods parameter. However, this - * creates a maintenance issue. When new types are added we would also need to change the method's implementation and - * add a new instanceof-check. This violates the single responsibility principle - a class should have only one reason - * to change. - *

- * Instead of the instanceof-checks a better way is to make another virtual call on the parameter object. This way new - * functionality can be easily added without the need to modify existing implementation (open-closed principle). - *

- * In this example we have hierarchy of objects ({@link GameObject}) that can collide to each other. Each object has its - * own coordinates which are checked against the other objects' coordinates. If there is an overlap, then the objects - * collide utilizing the Double Dispatch pattern. + * When a message with a parameter is sent to an object, the resultant behaviour is defined by the + * implementation of that method in the receiver. Sometimes the behaviour must also be determined by + * the type of the parameter. + * + *

One way to implement this would be to create multiple instanceof-checks for the methods + * parameter. However, this creates a maintenance issue. When new types are added we would also need + * to change the method's implementation and add a new instanceof-check. This violates the single + * responsibility principle - a class should have only one reason to change. + * + *

Instead of the instanceof-checks a better way is to make another virtual call on the + * parameter object. This way new functionality can be easily added without the need to modify + * existing implementation (open-closed principle). * + *

In this example we have hierarchy of objects ({@link GameObject}) that can collide to each + * other. Each object has its own coordinates which are checked against the other objects' + * coordinates. If there is an overlap, then the objects collide utilizing the Double Dispatch + * pattern. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * - * @param args - * command line args + * Program entry point. + * + * @param args command line args */ public static void main(String[] args) { // initialize game objects and print their status List objects = List.of( - new FlamingAsteroid(0, 0, 5, 5), - new SpaceStationMir(1, 1, 2, 2), - new Meteoroid(10, 10, 15, 15), - new SpaceStationIss(12, 12, 14, 14)); + new FlamingAsteroid(0, 0, 5, 5), + new SpaceStationMir(1, 1, 2, 2), + new Meteoroid(10, 10, 15, 15), + new SpaceStationIss(12, 12, 14, 14)); objects.stream().forEach(o -> LOGGER.info(o.toString())); LOGGER.info(""); diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java index ed089c3587e0..c603abcac023 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java @@ -24,9 +24,7 @@ package com.iluwatar.doubledispatch; /** - * - * Flaming asteroid game object - * + * Flaming asteroid game object. */ public class FlamingAsteroid extends Meteoroid { diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java index d04a9c404673..3dcfd5015b43 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java @@ -24,9 +24,7 @@ package com.iluwatar.doubledispatch; /** - * * Game objects have coordinates and some other status information. - * */ public abstract class GameObject extends Rectangle { diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java index 1f2aa441eb35..de9c59f215b2 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java @@ -23,15 +23,12 @@ package com.iluwatar.doubledispatch; +import com.iluwatar.doubledispatch.constants.AppConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.iluwatar.doubledispatch.constants.AppConstants; - /** - * - * Meteoroid game object - * + * Meteoroid game object. */ public class Meteoroid extends GameObject { @@ -48,12 +45,14 @@ public void collision(GameObject gameObject) { @Override public void collisionResolve(FlamingAsteroid asteroid) { - LOGGER.info(AppConstants.HITS, asteroid.getClass().getSimpleName(), this.getClass().getSimpleName()); + LOGGER.info(AppConstants.HITS, asteroid.getClass().getSimpleName(), this.getClass() + .getSimpleName()); } @Override public void collisionResolve(Meteoroid meteoroid) { - LOGGER.info(AppConstants.HITS, meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName()); + LOGGER.info(AppConstants.HITS, meteoroid.getClass().getSimpleName(), this.getClass() + .getSimpleName()); } @Override diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java index f7646add5975..bd832287cd68 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java @@ -24,9 +24,7 @@ package com.iluwatar.doubledispatch; /** - * * Rectangle has coordinates and can be checked for overlap against other Rectangles. - * */ public class Rectangle { @@ -36,7 +34,7 @@ public class Rectangle { private int bottom; /** - * Constructor + * Constructor. */ public Rectangle(int left, int top, int right, int bottom) { this.left = left; diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java index f893b0c2795b..fecdd6b5154b 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java @@ -24,9 +24,7 @@ package com.iluwatar.doubledispatch; /** - * - * Space station ISS game object - * + * Space station ISS game object. */ public class SpaceStationIss extends SpaceStationMir { diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java index 0759645344d7..cc61edcdcd1a 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java @@ -23,15 +23,12 @@ package com.iluwatar.doubledispatch; +import com.iluwatar.doubledispatch.constants.AppConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.iluwatar.doubledispatch.constants.AppConstants; - /** - * - * Space station Mir game object - * + * Space station Mir game object. */ public class SpaceStationMir extends GameObject { @@ -48,29 +45,31 @@ public void collision(GameObject gameObject) { @Override public void collisionResolve(FlamingAsteroid asteroid) { - LOGGER.info(AppConstants.HITS," {} is damaged! {} is set on fire!", asteroid.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); + LOGGER.info(AppConstants.HITS, " {} is damaged! {} is set on fire!", asteroid.getClass() + .getSimpleName(), + this.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass() + .getSimpleName()); setDamaged(true); setOnFire(true); } @Override public void collisionResolve(Meteoroid meteoroid) { - LOGGER.info(AppConstants.HITS," {} is damaged!", meteoroid.getClass().getSimpleName(), + LOGGER.info(AppConstants.HITS, " {} is damaged!", meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } @Override public void collisionResolve(SpaceStationMir mir) { - LOGGER.info(AppConstants.HITS," {} is damaged!", mir.getClass().getSimpleName(), + LOGGER.info(AppConstants.HITS, " {} is damaged!", mir.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } @Override public void collisionResolve(SpaceStationIss iss) { - LOGGER.info(AppConstants.HITS," {} is damaged!", iss.getClass().getSimpleName(), + LOGGER.info(AppConstants.HITS, " {} is damaged!", iss.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java index cc4c312d5a4b..77f6dde4db52 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java @@ -24,9 +24,7 @@ package com.iluwatar.doubledispatch.constants; /** - * - * Constants class to define all constants - * + * Constants class to define all constants. */ public class AppConstants { From 7c888e88864be0ced3e704c039fa8159b255c04a Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 23:04:42 +0530 Subject: [PATCH 12/32] Resolves checkstyle errors for eip-* (#1069) * Reduces checkstyle errors in eip-aggregator * Reduces checkstyle errors in eip-message-channel * Reduces checkstyle errors in eip-publish-subscribe * Reduces checkstyle errors in eip-splitter * Reduces checkstyle errors in eip-wire-tap --- .../java/com/iluwatar/eip/aggregator/App.java | 17 ++++++++--------- .../aggregator/routes/AggregatorRoute.java | 18 +++++++++--------- .../routes/MessageAggregationStrategy.java | 4 ++-- .../com/iluwatar/eip/message/channel/App.java | 18 ++++++++---------- .../iluwatar/eip/publish/subscribe/App.java | 18 ++++++++---------- .../java/com/iluwatar/eip/splitter/App.java | 19 ++++++++++--------- .../eip/splitter/routes/SplitterRoute.java | 14 +++++++------- .../java/com/iluwatar/eip/wiretap/App.java | 16 +++++++++------- .../eip/wiretap/routes/WireTapRoute.java | 13 +++++++------ 9 files changed, 68 insertions(+), 69 deletions(-) diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java index f8fec8121b37..491ddaf0b339 100644 --- a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java +++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java @@ -30,21 +30,20 @@ import org.springframework.context.ConfigurableApplicationContext; /** - * Sometimes in enterprise systems there is a need to group incoming data in order to process it as a whole. For example - * you may need to gather offers and after defined number of offers has been received you would like to choose the one - * with the best parameters. - * - *

- * Aggregator allows you to merge messages based on defined criteria and parameters. It gathers original messages, - * applies aggregation strategy and upon fulfilling given criteria, releasing merged messages. - *

+ * Sometimes in enterprise systems there is a need to group incoming data in order to process it as + * a whole. For example you may need to gather offers and after defined number of offers has been + * received you would like to choose the one with the best parameters. * + *

Aggregator allows you to merge messages based on defined criteria and parameters. It gathers + * original messages, applies aggregation strategy and upon fulfilling given criteria, releasing + * merged messages. */ @SpringBootApplication public class App { /** - * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes. + * Program entry point. It starts Spring Boot application and using Apache Camel it + * auto-configures routes. * * @param args command line args */ diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java index 652ddbb199c1..60499e1b8183 100644 --- a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java +++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java @@ -30,16 +30,15 @@ /** * Sample aggregator route definition. * - *

- * It consumes messages out of the direct:entry entry point and forwards them to direct:endpoint. - * Route accepts messages containing String as a body, it aggregates the messages based on the settings and forwards - * them as CSV to the output chanel. + *

It consumes messages out of the direct:entry entry point and forwards them to + * direct:endpoint. Route accepts messages containing String as a body, it aggregates the + * messages based on the settings and forwards them as CSV to the output chanel. * - * Settings for the aggregation are: aggregate until 3 messages are bundled or wait 2000ms before sending bundled - * messages further. - *

+ *

Settings for the aggregation are: aggregate until 3 messages are bundled or wait 2000ms + * before sending bundled messages further. * - * In this example input/output endpoints names are stored in application.properties file. + *

In this example input/output endpoints names are stored in application.properties + * file. */ @Component public class AggregatorRoute extends RouteBuilder { @@ -48,7 +47,8 @@ public class AggregatorRoute extends RouteBuilder { private MessageAggregationStrategy aggregator; /** - * Configures the route + * Configures the route. + * * @throws Exception in case of exception during configuration */ @Override diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java index f8f2822a9dd6..d38923ecc939 100644 --- a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java +++ b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java @@ -28,8 +28,8 @@ import org.springframework.stereotype.Component; /** - * Aggregation strategy joining bodies of messages. If message is first one oldMessage is null. All changes are - * made on IN messages. + * Aggregation strategy joining bodies of messages. If message is first one oldMessage is + * null. All changes are made on IN messages. */ @Component public class MessageAggregationStrategy implements AggregationStrategy { diff --git a/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/App.java b/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/App.java index bb9b26d10903..78a23bdd34a0 100644 --- a/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/App.java +++ b/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/App.java @@ -30,12 +30,11 @@ import org.slf4j.LoggerFactory; /** - * * When two applications communicate with each other using a messaging system they first need to * establish a communication channel that will carry the data. Message Channel decouples Message * producers and consumers. - *

- * The sending application doesn't necessarily know what particular application will end up + * + *

The sending application doesn't necessarily know what particular application will end up * retrieving it, but it can be assured that the application that retrieves the information is * interested in that information. This is because the messaging system has different Message * Channels for different types of information the applications want to communicate. When an @@ -44,19 +43,18 @@ * Likewise, an application that wants to receive particular information doesn't pull info off some * random channel; it selects what channel to get information from based on what type of information * it wants. - *

- * In this example we use Apache Camel to establish two different Message Channels. The first one - * reads from standard input and delivers messages to Direct endpoint. The second Message Channel is - * established from the Direct component to console output. No actual messages are sent, only the - * established routes are printed to standard output. - * + * + *

In this example we use Apache Camel to establish two different Message Channels. The first + * one reads from standard input and delivers messages to Direct endpoint. The second Message + * Channel is established from the Direct component to console output. No actual messages are sent, + * only the established routes are printed to standard output. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point + * Program entry point. */ public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); diff --git a/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/App.java b/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/App.java index e9081ebbb4d0..c8a311374734 100644 --- a/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/App.java +++ b/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/App.java @@ -31,30 +31,28 @@ import org.slf4j.LoggerFactory; /** - * * There are well-established patterns for implementing broadcasting. The Observer pattern describes * the need to decouple observers from their subject (that is, the originator of the event) so that * the subject can easily provide event notification to all interested observers no matter how many * observers there are (even none). The Publish-Subscribe pattern expands upon Observer by adding * the notion of an event channel for communicating event notifications. - *

- * A Publish-Subscribe Channel works like this: It has one input channel that splits into multiple - * output channels, one for each subscriber. When an event is published into the channel, the - * Publish-Subscribe Channel delivers a copy of the message to each of the output channels. Each + * + *

A Publish-Subscribe Channel works like this: It has one input channel that splits into + * multiple output channels, one for each subscriber. When an event is published into the channel, + * the Publish-Subscribe Channel delivers a copy of the message to each of the output channels. Each * output end of the channel has only one subscriber, which is allowed to consume a message only * once. In this way, each subscriber gets the message only once, and consumed copies disappear from * their channels. - *

- * In this example we use Apache Camel to establish a Publish-Subscribe Channel from "direct-origin" - * to "mock:foo", "mock:bar" and "stream:out". - * + * + *

In this example we use Apache Camel to establish a Publish-Subscribe Channel from + * "direct-origin" to "mock:foo", "mock:bar" and "stream:out". */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point + * Program entry point. */ public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java index e2df6f7e9254..b0e338f27a51 100644 --- a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java +++ b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java @@ -30,23 +30,24 @@ import org.springframework.context.ConfigurableApplicationContext; /** - * It is very common in integration systems that incoming messages consists of many items bundled together. For example - * an invoice document contains multiple invoice lines describing transaction (quantity, name of provided - * service/sold goods, price etc.). Such bundled messages may not be accepted by other systems. This is where splitter - * pattern comes in handy. It will take the whole document, split it based on given criteria and send individual - * items to the endpoint. + * It is very common in integration systems that incoming messages consists of many items bundled + * together. For example an invoice document contains multiple invoice lines describing transaction + * (quantity, name of provided service/sold goods, price etc.). Such bundled messages may not be + * accepted by other systems. This is where splitter pattern comes in handy. It will take the whole + * document, split it based on given criteria and send individual items to the endpoint. * *

- * Splitter allows you to split messages based on defined criteria. It takes original message, process it and send - * multiple parts to the output channel. It is not defined if it should keep the order of items though. + * Splitter allows you to split messages based on defined criteria. It takes original message, + * process it and send multiple parts to the output channel. It is not defined if it should keep the + * order of items though. *

- * */ @SpringBootApplication public class App { /** - * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes. + * Program entry point. It starts Spring Boot application and using Apache Camel it + * auto-configures routes. * * @param args command line args */ diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java index 1efd8401c26b..4d2cb3efb0ab 100644 --- a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java +++ b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java @@ -29,19 +29,19 @@ /** * Sample splitter route definition. * - *

- * It consumes messages out of the direct:entry entry point and forwards them to direct:endpoint. - * Route accepts messages having body of array or collection of objects. Splitter component split message body and - * forwards single objects to the endpoint. - *

+ *

It consumes messages out of the direct:entry entry point and forwards them to + * direct:endpoint. Route accepts messages having body of array or collection of objects. + * Splitter component split message body and forwards single objects to the endpoint. * - * In this example input/output endpoints names are stored in application.properties file. + *

In this example input/output endpoints names are stored in application.properties + * file. */ @Component public class SplitterRoute extends RouteBuilder { /** - * Configures the route + * Configures the route. + * * @throws Exception in case of exception during configuration */ @Override diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java index 5db2e88281b3..36407fbf715a 100644 --- a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java +++ b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java @@ -30,21 +30,23 @@ import org.springframework.context.ConfigurableApplicationContext; /** - * In most integration cases there is a need to monitor the messages flowing through the system. It is usually achieved - * by intercepting the message and redirecting it to a different location like console, filesystem or the database. - * It is important that such functionality should not modify the original message and influence the processing path. + * In most integration cases there is a need to monitor the messages flowing through the system. It + * is usually achieved by intercepting the message and redirecting it to a different location like + * console, filesystem or the database. It is important that such functionality should not modify + * the original message and influence the processing path. * *

- * Wire Tap allows you to route messages to a separate location while they are being forwarded to the ultimate - * destination. It basically consumes messages of the input channel and publishes the unmodified message to both - * output channels. + * Wire Tap allows you to route messages to a separate location while they are being forwarded to + * the ultimate destination. It basically consumes messages of the input channel and publishes the + * unmodified message to both output channels. *

*/ @SpringBootApplication public class App { /** - * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes. + * Program entry point. It starts Spring Boot application and using Apache Camel it + * auto-configures routes. * * @param args command line args */ diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java index 4cb91e162c8e..8eea7adbd2bb 100644 --- a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java +++ b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java @@ -29,19 +29,20 @@ /** * Sample wire tap route definition. * - *

- * It consumes messages out of the direct:entry entry point and forwards them to direct:endpoint. - * Wire Tap intercepts the message and sends it to direct:wireTap, which in turn forwards it to + *

It consumes messages out of the direct:entry entry point and forwards them to + * direct:endpoint. Wire Tap intercepts the message and sends it to direct:wireTap, + * which in turn forwards it to * direct:wireTapEndpoint. - *

* - * In this example input/output endpoints names are stored in application.properties file. + *

In this example input/output endpoints names are stored in application.properties + * file. */ @Component public class WireTapRoute extends RouteBuilder { /** - * Configures the route + * Configures the route. + * * @throws Exception in case of exception during configuration */ @Override From 5ae2ce6e2eb09c6f0c6768eea9d04aecdb4f3076 Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sun, 10 Nov 2019 23:07:10 +0530 Subject: [PATCH 13/32] Resolves checkstyle errors for event-* (#1070) * Reduces checkstyle errors in event-aggregator * Reduces checkstyle errors in event-asynchronous * Reduces checkstyle errors in event-driven-architecture * Reduces checkstyle errors in event-queue * Reduces checkstyle errors in event-sourcing --- .../com/iluwatar/event/aggregator/App.java | 18 ++-- .../com/iluwatar/event/aggregator/Event.java | 2 - .../event/aggregator/EventEmitter.java | 2 - .../event/aggregator/EventObserver.java | 2 - .../event/aggregator/KingJoffrey.java | 2 - .../iluwatar/event/aggregator/KingsHand.java | 2 - .../event/aggregator/LordBaelish.java | 2 - .../iluwatar/event/aggregator/LordVarys.java | 2 - .../com/iluwatar/event/aggregator/Scout.java | 2 - .../iluwatar/event/aggregator/Weekday.java | 4 +- .../com/iluwatar/event/asynchronous/App.java | 85 ++++++++++--------- .../iluwatar/event/asynchronous/Event.java | 7 +- .../EventDoesNotExistException.java | 2 +- .../event/asynchronous/EventManager.java | 39 +++++---- .../iluwatar/event/asynchronous/IEvent.java | 3 +- .../InvalidOperationException.java | 2 +- .../LongRunningEventException.java | 2 +- .../MaxNumOfEventsAllowedException.java | 2 +- .../src/main/java/com/iluwatar/eda/App.java | 13 ++- .../com/iluwatar/eda/event/AbstractEvent.java | 11 ++- .../iluwatar/eda/event/UserCreatedEvent.java | 6 +- .../iluwatar/eda/event/UserUpdatedEvent.java | 6 +- .../com/iluwatar/eda/framework/Event.java | 9 +- .../eda/framework/EventDispatcher.java | 4 +- .../com/iluwatar/eda/framework/Handler.java | 12 +-- .../java/com/iluwatar/eda/model/User.java | 4 +- .../java/com/iluwatar/event/queue/App.java | 32 +++---- .../java/com/iluwatar/event/queue/Audio.java | 37 ++++---- .../com/iluwatar/event/queue/PlayMessage.java | 8 +- .../com/iluwatar/event/sourcing/app/App.java | 10 +-- .../event/sourcing/domain/Account.java | 15 ++-- .../sourcing/event/AccountCreateEvent.java | 15 ++-- .../event/sourcing/event/DomainEvent.java | 6 +- .../sourcing/event/MoneyDepositEvent.java | 15 ++-- .../sourcing/event/MoneyTransferEvent.java | 19 ++--- .../processor/DomainEventProcessor.java | 7 +- .../sourcing/processor/JsonFileJournal.java | 23 +++-- .../sourcing/state/AccountAggregate.java | 5 +- 38 files changed, 208 insertions(+), 229 deletions(-) diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java index 421cf47b31f7..9e459c7a9ff5 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java @@ -27,24 +27,22 @@ import java.util.List; /** - * * A system with lots of objects can lead to complexities when a client wants to subscribe to * events. The client has to find and register for each object individually, if each object has * multiple events then each event requires a separate subscription. - *

- * An Event Aggregator acts as a single source of events for many objects. It registers for all the - * events of the many objects allowing clients to register with just the aggregator. - *

- * In the example {@link LordBaelish}, {@link LordVarys} and {@link Scout} deliver events to - * {@link KingsHand}. {@link KingsHand}, the event aggregator, then delivers the events to - * {@link KingJoffrey}. * + *

An Event Aggregator acts as a single source of events for many objects. It registers for all + * the events of the many objects allowing clients to register with just the aggregator. + * + *

In the example {@link LordBaelish}, {@link LordVarys} and {@link Scout} deliver events to + * {@link KingsHand}. {@link KingsHand}, the event aggregator, then delivers the events to {@link + * KingJoffrey}. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java index 4227571b1547..7a125c042093 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java @@ -24,9 +24,7 @@ package com.iluwatar.event.aggregator; /** - * * Event enumeration. - * */ public enum Event { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java index 209d959281f7..eef64af1a740 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java @@ -27,9 +27,7 @@ import java.util.List; /** - * * EventEmitter is the base class for event producers that can be observed. - * */ public abstract class EventEmitter { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java index 45abc3217f90..db436b50c6f5 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java @@ -24,9 +24,7 @@ package com.iluwatar.event.aggregator; /** - * * Observers of events implement this interface. - * */ public interface EventObserver { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java index cc76eeb73f88..23940c0a2029 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * KingJoffrey observes events from {@link KingsHand}. - * */ public class KingJoffrey implements EventObserver { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java index e5c77d8df78f..e6e05cb8d8fe 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java @@ -24,9 +24,7 @@ package com.iluwatar.event.aggregator; /** - * * KingsHand observes events from multiple sources and delivers them to listeners. - * */ public class KingsHand extends EventEmitter implements EventObserver { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java index 216092c22b4d..dcc01c7df93f 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java @@ -24,9 +24,7 @@ package com.iluwatar.event.aggregator; /** - * * LordBaelish produces events. - * */ public class LordBaelish extends EventEmitter { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java index 2d87051ff205..c39080fa5810 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java @@ -24,9 +24,7 @@ package com.iluwatar.event.aggregator; /** - * * LordVarys produces events. - * */ public class LordVarys extends EventEmitter { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java index 5dd82848a457..24d6f232886d 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java @@ -24,9 +24,7 @@ package com.iluwatar.event.aggregator; /** - * * Scout produces events. - * */ public class Scout extends EventEmitter { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java index 9c89ac34304d..730977bdb42f 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java @@ -24,9 +24,7 @@ package com.iluwatar.event.aggregator; /** - * - * Weekday enumeration - * + * Weekday enumeration. */ public enum Weekday { diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java index bb6f1d6adb2b..42b7b3391fb2 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java @@ -23,38 +23,38 @@ package com.iluwatar.event.asynchronous; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Scanner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** + * This application demonstrates the Event-based Asynchronous pattern. Essentially, users (of + * the pattern) may choose to run events in an Asynchronous or Synchronous mode. There can be + * multiple Asynchronous events running at once but only one Synchronous event can run at a time. + * Asynchronous events are synonymous to multi-threads. The key point here is that the threads run + * in the background and the user is free to carry on with other processes. Once an event is + * complete, the appropriate listener/callback method will be called. The listener then proceeds to + * carry out further processing depending on the needs of the user. * - * This application demonstrates the Event-based Asynchronous pattern. Essentially, users (of the pattern) may - * choose to run events in an Asynchronous or Synchronous mode. There can be multiple Asynchronous events running at - * once but only one Synchronous event can run at a time. Asynchronous events are synonymous to multi-threads. The key - * point here is that the threads run in the background and the user is free to carry on with other processes. Once an - * event is complete, the appropriate listener/callback method will be called. The listener then proceeds to carry out - * further processing depending on the needs of the user. + *

The {@link EventManager} manages the events/threads that the user creates. Currently, the + * supported event operations are: start, stop, getStatus. + * For Synchronous events, the user is unable to start another (Synchronous) event if one is already + * running at the time. The running event would have to either be stopped or completed before a new + * event can be started. * - * The {@link EventManager} manages the events/threads that the user creates. Currently, the supported event operations - * are: start, stop, getStatus. For Synchronous events, the user is unable to - * start another (Synchronous) event if one is already running at the time. The running event would have to either be - * stopped or completed before a new event can be started. - * - * The Event-based Asynchronous Pattern makes available the advantages of multithreaded applications while hiding many - * of the complex issues inherent in multithreaded design. Using a class that supports this pattern can allow you to:- - * (1) Perform time-consuming tasks, such as downloads and database operations, "in the background," without - * interrupting your application. (2) Execute multiple operations simultaneously, receiving notifications when each - * completes. (3) Wait for resources to become available without stopping ("hanging") your application. (4) Communicate - * with pending asynchronous operations using the familiar events-and-delegates model. + *

The Event-based Asynchronous Pattern makes available the advantages of multithreaded + * applications while hiding many of the complex issues inherent in multithreaded design. Using a + * class that supports this pattern can allow you to:- (1) Perform time-consuming tasks, such as + * downloads and database operations, "in the background," without interrupting your application. + * (2) Execute multiple operations simultaneously, receiving notifications when each completes. (3) + * Wait for resources to become available without stopping ("hanging") your application. (4) + * Communicate with pending asynchronous operations using the familiar events-and-delegates model. * * @see EventManager * @see Event - * */ public class App { @@ -67,8 +67,7 @@ public class App { /** * Program entry point. * - * @param args - * command line args + * @param args command line args */ public static void main(String[] args) { App app = new App(); @@ -78,8 +77,9 @@ public static void main(String[] args) { } /** - * App can run in interactive mode or not. Interactive mode == Allow user interaction with command line. - * Non-interactive is a quick sequential run through the available {@link EventManager} operations. + * App can run in interactive mode or not. Interactive mode == Allow user interaction with command + * line. Non-interactive is a quick sequential run through the available {@link EventManager} + * operations. */ public void setUp() { Properties prop = new Properties(); @@ -118,24 +118,24 @@ public void quickRun() { try { // Create an Asynchronous event. - int aEventId = eventManager.createAsync(60); - LOGGER.info("Async Event [{}] has been created.", aEventId); - eventManager.start(aEventId); - LOGGER.info("Async Event [{}] has been started.", aEventId); + int asyncEventId = eventManager.createAsync(60); + LOGGER.info("Async Event [{}] has been created.", asyncEventId); + eventManager.start(asyncEventId); + LOGGER.info("Async Event [{}] has been started.", asyncEventId); // Create a Synchronous event. - int sEventId = eventManager.create(60); - LOGGER.info("Sync Event [{}] has been created.", sEventId); - eventManager.start(sEventId); - LOGGER.info("Sync Event [{}] has been started.", sEventId); + int syncEventId = eventManager.create(60); + LOGGER.info("Sync Event [{}] has been created.", syncEventId); + eventManager.start(syncEventId); + LOGGER.info("Sync Event [{}] has been started.", syncEventId); - eventManager.status(aEventId); - eventManager.status(sEventId); + eventManager.status(asyncEventId); + eventManager.status(syncEventId); - eventManager.cancel(aEventId); - LOGGER.info("Async Event [{}] has been stopped.", aEventId); - eventManager.cancel(sEventId); - LOGGER.info("Sync Event [{}] has been stopped.", sEventId); + eventManager.cancel(asyncEventId); + LOGGER.info("Async Event [{}] has been stopped.", asyncEventId); + eventManager.cancel(syncEventId); + LOGGER.info("Sync Event [{}] has been stopped.", syncEventId); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException | InvalidOperationException e) { @@ -211,7 +211,8 @@ private void processOption1(EventManager eventManager, Scanner s) { int eventId = eventManager.createAsync(eventTime); eventManager.start(eventId); LOGGER.info("Egg [{}] is being boiled.", eventId); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { + } catch (MaxNumOfEventsAllowedException | LongRunningEventException + | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } else if (eventType.equalsIgnoreCase("S")) { @@ -219,8 +220,8 @@ private void processOption1(EventManager eventManager, Scanner s) { int eventId = eventManager.create(eventTime); eventManager.start(eventId); LOGGER.info("Egg [{}] is being boiled.", eventId); - } catch (MaxNumOfEventsAllowedException | InvalidOperationException | LongRunningEventException - | EventDoesNotExistException e) { + } catch (MaxNumOfEventsAllowedException | InvalidOperationException + | LongRunningEventException | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } else { diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java index 5c224fdacbe7..b275b16a2325 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * Each Event runs as a separate/individual thread. - * */ public class Event implements IEvent, Runnable { @@ -43,9 +41,10 @@ public class Event implements IEvent, Runnable { private ThreadCompleteListener eventListener; /** + * Constructor. * - * @param eventId event ID - * @param eventTime event time + * @param eventId event ID + * @param eventTime event time * @param isSynchronous is of synchronous type */ public Event(final int eventId, final int eventTime, final boolean isSynchronous) { diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java index ed68ccfe989e..fdd075d7b634 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java @@ -24,7 +24,7 @@ package com.iluwatar.event.asynchronous; /** - * Custom Exception Class for Non Existent Event + * Custom Exception Class for Non Existent Event. */ public class EventDoesNotExistException extends Exception { diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java index 486030e5f490..2201394d9e23 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java @@ -29,29 +29,28 @@ import java.util.concurrent.ConcurrentHashMap; /** - * - * EventManager handles and maintains a pool of event threads. {@link Event} threads are created upon user request. Thre - * are two types of events; Asynchronous and Synchronous. There can be multiple Asynchronous events running at once but - * only one Synchronous event running at a time. Currently supported event operations are: start, stop, and getStatus. - * Once an event is complete, it then notifies EventManager through a listener. The EventManager then takes the event - * out of the pool. - * + * EventManager handles and maintains a pool of event threads. {@link Event} threads are created + * upon user request. Thre are two types of events; Asynchronous and Synchronous. There can be + * multiple Asynchronous events running at once but only one Synchronous event running at a time. + * Currently supported event operations are: start, stop, and getStatus. Once an event is complete, + * it then notifies EventManager through a listener. The EventManager then takes the event out of + * the pool. */ public class EventManager implements ThreadCompleteListener { - public static final int MAX_RUNNING_EVENTS = 1000; // Just don't wanna have too many running events. :) + public static final int MAX_RUNNING_EVENTS = 1000; + // Just don't wanna have too many running events. :) public static final int MIN_ID = 1; public static final int MAX_ID = MAX_RUNNING_EVENTS; public static final int MAX_EVENT_TIME = 1800; // in seconds / 30 minutes. private int currentlyRunningSyncEvent = -1; private Random rand; private Map eventPool; - + private static final String DOES_NOT_EXIST = " does not exist."; /** * EventManager constructor. - * */ public EventManager() { rand = new Random(1); @@ -65,14 +64,15 @@ public EventManager() { * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. - * @throws InvalidOperationException No new synchronous events can be created when one is already running. - * @throws LongRunningEventException Long running events are not allowed in the app. + * @throws InvalidOperationException No new synchronous events can be created when one is + * already running. + * @throws LongRunningEventException Long running events are not allowed in the app. */ public int create(int eventTime) throws MaxNumOfEventsAllowedException, InvalidOperationException, LongRunningEventException { if (currentlyRunningSyncEvent != -1) { - throw new InvalidOperationException( - "Event [" + currentlyRunningSyncEvent + "] is still running. Please wait until it finishes and try again."); + throw new InvalidOperationException("Event [" + currentlyRunningSyncEvent + "] is still" + + " running. Please wait until it finishes and try again."); } int eventId = createEvent(eventTime, true); @@ -87,16 +87,18 @@ public int create(int eventTime) * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. - * @throws LongRunningEventException Long running events are not allowed in the app. + * @throws LongRunningEventException Long running events are not allowed in the app. */ - public int createAsync(int eventTime) throws MaxNumOfEventsAllowedException, LongRunningEventException { + public int createAsync(int eventTime) throws MaxNumOfEventsAllowedException, + LongRunningEventException { return createEvent(eventTime, false); } private int createEvent(int eventTime, boolean isSynchronous) throws MaxNumOfEventsAllowedException, LongRunningEventException { if (eventPool.size() == MAX_RUNNING_EVENTS) { - throw new MaxNumOfEventsAllowedException("Too many events are running at the moment. Please try again later."); + throw new MaxNumOfEventsAllowedException("Too many events are running at the moment." + + " Please try again later."); } if (eventTime >= MAX_EVENT_TIME) { @@ -185,7 +187,8 @@ public void shutdown() { } /** - * Returns a pseudo-random number between min and max, inclusive. The difference between min and max can be at most + * Returns a pseudo-random number between min and max, inclusive. The difference between min and + * max can be at most * Integer.MAX_VALUE - 1. */ private int generateId() { diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java index 1d451ef74f97..37cce70b49ef 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java @@ -24,8 +24,7 @@ package com.iluwatar.event.asynchronous; /** - * Events that fulfill the start stop and list out current status behaviour - * follow this interface + * Events that fulfill the start stop and list out current status behaviour follow this interface. */ public interface IEvent { diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java index f439b53a8b50..6c016785066d 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java @@ -24,7 +24,7 @@ package com.iluwatar.event.asynchronous; /** - * Type of Exception raised when the Operation being invoked is Invalid + * Type of Exception raised when the Operation being invoked is Invalid. */ public class InvalidOperationException extends Exception { diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java index 76a3ecc85156..aac69e312e77 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java @@ -24,7 +24,7 @@ package com.iluwatar.event.asynchronous; /** - * Type of Exception raised when the Operation being invoked is Long Running + * Type of Exception raised when the Operation being invoked is Long Running. */ public class LongRunningEventException extends Exception { diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java index 4e1417802b31..204f07dd6a95 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java @@ -24,7 +24,7 @@ package com.iluwatar.event.asynchronous; /** - * Type of Exception raised when the max number of allowed events is exceeded + * Type of Exception raised when the max number of allowed events is exceeded. */ public class MaxNumOfEventsAllowedException extends Exception { diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java index 809bfffab853..6e328e04032f 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java @@ -34,11 +34,11 @@ /** * An event-driven architecture (EDA) is a framework that orchestrates behavior around the * production, detection and consumption of events as well as the responses they evoke. An event is - * any identifiable occurrence that has significance for system hardware or software.

The - * example below uses an {@link EventDispatcher} to link/register {@link Event} objects to their - * respective handlers once an {@link Event} is dispatched, it's respective handler is invoked and - * the {@link Event} is handled accordingly. + * any identifiable occurrence that has significance for system hardware or software. * + *

The example below uses an {@link EventDispatcher} to link/register {@link Event} objects to + * their respective handlers once an {@link Event} is dispatched, it's respective handler is invoked + * and the {@link Event} is handled accordingly. */ public class App { @@ -47,9 +47,8 @@ public class App { * made known to the dispatcher by registering them. In this case the {@link UserCreatedEvent} is * bound to the UserCreatedEventHandler, whilst the {@link UserUpdatedEvent} is bound to the * {@link UserUpdatedEventHandler}. The dispatcher can now be called to dispatch specific events. - * When a user is saved, the {@link UserCreatedEvent} can be dispatched. - * On the other hand, when a user is updated, {@link UserUpdatedEvent} can be dispatched. - * + * When a user is saved, the {@link UserCreatedEvent} can be dispatched. On the other hand, when a + * user is updated, {@link UserUpdatedEvent} can be dispatched. */ public static void main(String[] args) { diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java index 5218f4baddca..011cfc3f1ed6 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java @@ -23,12 +23,12 @@ package com.iluwatar.eda.event; -import com.iluwatar.eda.framework.EventDispatcher; import com.iluwatar.eda.framework.Event; +import com.iluwatar.eda.framework.EventDispatcher; /** - * The {@link AbstractEvent} class serves as a base class for defining custom events happening with your - * system. In this example we have two types of events defined. + * The {@link AbstractEvent} class serves as a base class for defining custom events happening with + * your system. In this example we have two types of events defined. *