repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
java-design-patterns
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.hexagonal.banking; import com.iluwatar.hexagonal.domain.LotteryConstants; import java.util.HashMap; import java.util.Map; /** * Banking implementation. */ public class InMemoryBank implements WireTransfers { private static final Map<String, Integer> accounts = new HashMap<>(); static { accounts .put(LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE); } @Override public void setFunds(String bankAccount, int amount) { accounts.put(bankAccount, amount); } @Override public int getFunds(String bankAccount) { return accounts.getOrDefault(bankAccount, 0); } @Override 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; } } }
2,331
35.4375
140
java
java-design-patterns
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.hexagonal.banking; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; import java.util.ArrayList; import org.bson.Document; /** * Mongo based banking adapter. */ public class MongoBank implements WireTransfers { private static final String DEFAULT_DB = "lotteryDB"; private static final String DEFAULT_ACCOUNTS_COLLECTION = "accounts"; private MongoClient mongoClient; private MongoDatabase database; private MongoCollection<Document> accountsCollection; /** * Constructor. */ public MongoBank() { connect(); } /** * Constructor accepting parameters. */ public MongoBank(String dbName, String accountsCollectionName) { connect(dbName, accountsCollectionName); } /** * Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_ACCOUNTS_COLLECTION); } /** * Connect to database with given parameters. */ public void connect(String dbName, String accountsCollectionName) { if (mongoClient != null) { mongoClient.close(); } mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); accountsCollection = database.getCollection(accountsCollectionName); } /** * Get mongo client. * * @return mongo client */ public MongoClient getMongoClient() { return mongoClient; } /** * Get mongo database. * * @return mongo database */ public MongoDatabase getMongoDatabase() { return database; } /** * Get accounts collection. * * @return accounts collection */ public MongoCollection<Document> getAccountsCollection() { return accountsCollection; } @Override public void setFunds(String bankAccount, int amount) { var search = new Document("_id", bankAccount); var update = new Document("_id", bankAccount).append("funds", amount); var updateOptions = new UpdateOptions().upsert(true); accountsCollection.updateOne(search, new Document("$set", update), updateOptions); } @Override public int getFunds(String bankAccount) { return accountsCollection .find(new Document("_id", bankAccount)) .limit(1) .into(new ArrayList<>()) .stream() .findFirst() .map(x -> x.getInteger("funds")) .orElse(0); } @Override public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) { var sourceFunds = getFunds(sourceAccount); if (sourceFunds < amount) { return false; } else { var destFunds = getFunds(destinationAccount); setFunds(sourceAccount, sourceFunds - amount); setFunds(destinationAccount, destFunds + amount); return true; } } }
4,224
28.964539
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for {@link Client} */ class ClientTest { @Test void test() { Client client = new Client(); var result = client.useService(10); assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue()); } }
1,676
37.113636
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for {@link ServiceAmbassador} */ class ServiceAmbassadorTest { @Test void test() { long result = new ServiceAmbassador().doRemoteFunction(10); assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue()); } }
1,687
39.190476
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.ambassador.util.RandomProvider; import org.junit.jupiter.api.Test; /** * Test for {@link RemoteService} */ class RemoteServiceTest { @Test void testFailedCall() { var remoteService = new RemoteService(new StaticRandomProvider(0.21)); var result = remoteService.doRemoteFunction(10); assertEquals(RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue(), result); } @Test void testSuccessfulCall() { var remoteService = new RemoteService(new StaticRandomProvider(0.2)); var result = remoteService.doRemoteFunction(10); assertEquals(100, result); } private static class StaticRandomProvider implements RandomProvider { private final double value; StaticRandomProvider(double value) { this.value = value; } @Override public double random() { return value; } } }
2,244
34.078125
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * * Solution: Inserted assertion to check whether the execution of the main method in {@link App} * throws an exception. */ @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,791
35.571429
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador; import static com.iluwatar.ambassador.RemoteServiceStatus.FAILURE; import static java.lang.Thread.sleep; import lombok.extern.slf4j.Slf4j; /** * 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. */ @Slf4j public class ServiceAmbassador implements RemoteServiceInterface { private static final int RETRIES = 3; private static final int DELAY_MS = 3000; ServiceAmbassador() { } @Override public long doRemoteFunction(int value) { return safeCall(value); } private long checkLatency(int value) { var startTime = System.currentTimeMillis(); var result = RemoteService.getRemoteService().doRemoteFunction(value); var timeTaken = System.currentTimeMillis() - startTime; LOGGER.info("Time taken (ms): {}", timeTaken); return result; } private long safeCall(int value) { var retries = 0; var result = FAILURE.getRemoteServiceStatusValue(); for (int i = 0; i < RETRIES; i++) { if (retries >= RETRIES) { return FAILURE.getRemoteServiceStatusValue(); } if ((result = checkLatency(value)) == FAILURE.getRemoteServiceStatusValue()) { LOGGER.info("Failed to reach remote: ({})", i + 1); retries++; try { sleep(DELAY_MS); } catch (InterruptedException e) { LOGGER.error("Thread sleep state interrupted", e); Thread.currentThread().interrupt(); } } else { break; } } return result; } }
2,998
34.282353
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/main/java/com/iluwatar/ambassador/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.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. * * <p>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. * * <p>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. */ public static void main(String[] args) { var host1 = new Client(); var host2 = new Client(); host1.useService(12); host2.useService(73); } }
2,516
44.763636
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador; /** * Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}). */ interface RemoteServiceInterface { long doRemoteFunction(int value); }
1,480
42.558824
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/main/java/com/iluwatar/ambassador/Client.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador; import lombok.extern.slf4j.Slf4j; /** * A simple Client. */ @Slf4j public class Client { private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador(); long useService(int value) { var result = serviceAmbassador.doRemoteFunction(value); LOGGER.info("Service result: {}", result); return result; } }
1,654
37.488372
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador; import static java.lang.Thread.sleep; import com.iluwatar.ambassador.util.RandomProvider; import lombok.extern.slf4j.Slf4j; /** * A remote legacy application represented by a Singleton implementation. */ @Slf4j public class RemoteService implements RemoteServiceInterface { private static final int THRESHOLD = 200; private static RemoteService service = null; private final RandomProvider randomProvider; static synchronized RemoteService getRemoteService() { if (service == null) { service = new RemoteService(); } return service; } private RemoteService() { this(Math::random); } /** * This constructor is used for testing purposes only. */ 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. * * @param value integer value to be multiplied. * @return if waitTime is less than {@link RemoteService#THRESHOLD}, it returns value * 10, * otherwise {@link RemoteServiceStatus#FAILURE}. */ @Override public long doRemoteFunction(int value) { long waitTime = (long) Math.floor(randomProvider.random() * 1000); try { sleep(waitTime); } catch (InterruptedException e) { LOGGER.error("Thread sleep state interrupted", e); Thread.currentThread().interrupt(); } return waitTime <= THRESHOLD ? value * 10 : RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue(); } }
2,945
34.926829
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceStatus.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador; /** * Holds information regarding the status of the Remote Service. * * <p> This Enum replaces the integer value previously * stored in {@link RemoteServiceInterface} as SonarCloud was identifying * it as an issue. All test cases have been checked after changes, * without failures. </p> */ public enum RemoteServiceStatus { FAILURE(-1); private final long remoteServiceStatusValue; RemoteServiceStatus(long remoteServiceStatusValue) { this.remoteServiceStatusValue = remoteServiceStatusValue; } public long getRemoteServiceStatusValue() { return remoteServiceStatusValue; } }
1,926
38.326531
140
java
java-design-patterns
java-design-patterns-master/ambassador/src/main/java/com/iluwatar/ambassador/util/RandomProvider.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.ambassador.util; /** * An interface for randomness. Useful for testing purposes. */ public interface RandomProvider { double random(); }
1,447
42.878788
140
java
java-design-patterns
java-design-patterns-master/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.fluentinterface.app; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application Test Entry */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,593
37.878049
140
java
java-design-patterns
java-design-patterns-master/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.fluentinterface.fluentiterable; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import org.junit.jupiter.api.Test; /** * Date: 12/12/15 - 7:00 PM * * @author Jeroen Meulemeester */ public abstract class FluentIterableTest { /** * Create a new {@link FluentIterable} from the given integers * * @param integers The integers * @return The new iterable, use for testing */ protected abstract FluentIterable<Integer> createFluentIterable(final Iterable<Integer> integers); @Test void testFirst() { final var integers = List.of(1, 2, 3, 10, 9, 8); final var first = createFluentIterable(integers).first(); assertNotNull(first); assertTrue(first.isPresent()); assertEquals(integers.get(0), first.get()); } @Test void testFirstEmptyCollection() { final var integers = Collections.<Integer>emptyList(); final var first = createFluentIterable(integers).first(); assertNotNull(first); assertFalse(first.isPresent()); } @Test void testFirstCount() { final var integers = List.of(1, 2, 3, 10, 9, 8); final var first4 = createFluentIterable(integers) .first(4) .asList(); assertNotNull(first4); assertEquals(4, first4.size()); assertEquals(integers.get(0), first4.get(0)); assertEquals(integers.get(1), first4.get(1)); assertEquals(integers.get(2), first4.get(2)); assertEquals(integers.get(3), first4.get(3)); } @Test void testFirstCountLessItems() { final var integers = List.of(1, 2, 3); final var first4 = createFluentIterable(integers) .first(4) .asList(); assertNotNull(first4); assertEquals(3, first4.size()); assertEquals(integers.get(0), first4.get(0)); assertEquals(integers.get(1), first4.get(1)); assertEquals(integers.get(2), first4.get(2)); } @Test void testLast() { final var integers = List.of(1, 2, 3, 10, 9, 8); final var last = createFluentIterable(integers).last(); assertNotNull(last); assertTrue(last.isPresent()); assertEquals(integers.get(integers.size() - 1), last.get()); } @Test void testLastEmptyCollection() { final var integers = Collections.<Integer>emptyList(); final var last = createFluentIterable(integers).last(); assertNotNull(last); assertFalse(last.isPresent()); } @Test void testLastCount() { final var integers = List.of(1, 2, 3, 10, 9, 8); final var last4 = createFluentIterable(integers) .last(4) .asList(); assertNotNull(last4); assertEquals(4, last4.size()); assertEquals(Integer.valueOf(3), last4.get(0)); assertEquals(Integer.valueOf(10), last4.get(1)); assertEquals(Integer.valueOf(9), last4.get(2)); assertEquals(Integer.valueOf(8), last4.get(3)); } @Test void testLastCountLessItems() { final var integers = List.of(1, 2, 3); final var last4 = createFluentIterable(integers) .last(4) .asList(); assertNotNull(last4); assertEquals(3, last4.size()); assertEquals(Integer.valueOf(1), last4.get(0)); assertEquals(Integer.valueOf(2), last4.get(1)); assertEquals(Integer.valueOf(3), last4.get(2)); } @Test void testFilter() { final var integers = List.of(1, 2, 3, 10, 9, 8); final var evenItems = createFluentIterable(integers) .filter(i -> i % 2 == 0) .asList(); assertNotNull(evenItems); assertEquals(3, evenItems.size()); assertEquals(Integer.valueOf(2), evenItems.get(0)); assertEquals(Integer.valueOf(10), evenItems.get(1)); assertEquals(Integer.valueOf(8), evenItems.get(2)); } @Test void testMap() { final var integers = List.of(1, 2, 3); final var longs = createFluentIterable(integers) .map(Integer::longValue) .asList(); assertNotNull(longs); assertEquals(integers.size(), longs.size()); assertEquals(Long.valueOf(1), longs.get(0)); assertEquals(Long.valueOf(2), longs.get(1)); assertEquals(Long.valueOf(3), longs.get(2)); } @Test void testForEach() { final var integers = List.of(1, 2, 3); final Consumer<Integer> consumer = mock(Consumer.class); createFluentIterable(integers).forEach(consumer); verify(consumer, times(1)).accept(1); verify(consumer, times(1)).accept(2); verify(consumer, times(1)).accept(3); verifyNoMoreInteractions(consumer); } @Test void testSpliterator() throws Exception { final var integers = List.of(1, 2, 3); final var split = createFluentIterable(integers).spliterator(); assertNotNull(split); } }
6,346
30.735
140
java
java-design-patterns
java-design-patterns-master/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.fluentinterface.fluentiterable.lazy; import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.FluentIterableTest; /** * Date: 12/12/15 - 7:56 PM * * @author Jeroen Meulemeester */ class LazyFluentIterableTest extends FluentIterableTest { @Override protected FluentIterable<Integer> createFluentIterable(Iterable<Integer> integers) { return LazyFluentIterable.from(integers); } }
1,763
40.023256
140
java
java-design-patterns
java-design-patterns-master/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.fluentinterface.fluentiterable.simple; import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.FluentIterableTest; /** * Date: 12/12/15 - 7:56 PM * * @author Jeroen Meulemeester */ class SimpleFluentIterableTest extends FluentIterableTest { @Override protected FluentIterable<Integer> createFluentIterable(Iterable<Integer> integers) { return SimpleFluentIterable.fromCopyOf(integers); } }
1,775
40.302326
140
java
java-design-patterns
java-design-patterns-master/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.fluentinterface.app; import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable; import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable; import java.util.List; import java.util.StringJoiner; import java.util.function.Function; import java.util.function.Predicate; import lombok.extern.slf4j.Slf4j; /** * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API. * Those interfaces tend to mimic domain specific languages, so they can nearly be read as human * languages. * * <p>In this example two implementations of a {@link FluentIterable} interface are given. The * {@link SimpleFluentIterable} evaluates eagerly and would be too costly for real world * applications. The {@link LazyFluentIterable} is evaluated on termination. Their usage is * demonstrated with a simple number list that is filtered, transformed and collected. The result is * printed afterwards. */ @Slf4j public class App { /** * Program entry point. */ public static void main(String[] args) { var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68); prettyPrint("The initial list contains: ", integerList); var firstFiveNegatives = SimpleFluentIterable .fromCopyOf(integerList) .filter(negatives()) .first(3) .asList(); prettyPrint("The first three negative values are: ", firstFiveNegatives); var lastTwoPositives = SimpleFluentIterable .fromCopyOf(integerList) .filter(positives()) .last(2) .asList(); prettyPrint("The last two positive values are: ", lastTwoPositives); SimpleFluentIterable .fromCopyOf(integerList) .filter(number -> number % 2 == 0) .first() .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); var transformedList = SimpleFluentIterable .fromCopyOf(integerList) .filter(negatives()) .map(transformToString()) .asList(); prettyPrint("A string-mapped list of negative numbers contains: ", transformedList); var lastTwoOfFirstFourStringMapped = LazyFluentIterable .from(integerList) .filter(positives()) .first(4) .last(2) .map(number -> "String[" + number + "]") .asList(); prettyPrint("The lazy list contains the last two of the first four positive numbers " + "mapped to Strings: ", lastTwoOfFirstFourStringMapped); LazyFluentIterable .from(integerList) .filter(negatives()) .first(2) .last() .ifPresent(number -> LOGGER.info("Last amongst first two negatives: {}", number)); } private static Function<Integer, String> transformToString() { return integer -> "String[" + integer + "]"; } private static Predicate<? super Integer> negatives() { return integer -> integer < 0; } private static Predicate<? super Integer> positives() { return integer -> integer > 0; } private static <E> void prettyPrint(String prefix, Iterable<E> iterable) { prettyPrint(", ", prefix, iterable); } private static <E> void prettyPrint( String delimiter, String prefix, Iterable<E> iterable ) { var joiner = new StringJoiner(delimiter, prefix, "."); iterable.forEach(e -> joiner.add(e.toString())); LOGGER.info(joiner.toString()); } }
4,803
35.393939
140
java
java-design-patterns
java-design-patterns-master/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.fluentinterface.fluentiterable; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; /** * The FluentIterable is a more convenient implementation of the common iterable interface based on * the fluent interface design pattern. This interface defines common operations, but doesn't aim to * be complete. It was inspired by Guava's com.google.common.collect.FluentIterable. * * @param <E> is the class of objects the iterable contains */ public interface FluentIterable<E> extends Iterable<E> { /** * Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy * the predicate. * * @param predicate the condition to test with for the filtering. If the test is negative, the * tested object is removed by the iterator. * @return a filtered FluentIterable */ FluentIterable<E> filter(Predicate<? super E> predicate); /** * Returns an Optional containing the first element of this iterable if present, else returns * Optional.empty(). * * @return the first element after the iteration is evaluated */ Optional<E> first(); /** * Evaluates the iteration and leaves only the count first elements. * * @return the first count elements as an Iterable */ FluentIterable<E> first(int count); /** * Evaluates the iteration and returns the last element. This is a terminating operation. * * @return the last element after the iteration is evaluated */ Optional<E> last(); /** * Evaluates the iteration and leaves only the count last elements. * * @return the last counts elements as an Iterable */ FluentIterable<E> last(int count); /** * Transforms this FluentIterable into a new one containing objects of the type T. * * @param function a function that transforms an instance of E into an instance of T * @param <T> the target type of the transformation * @return a new FluentIterable of the new type */ <T> FluentIterable<T> map(Function<? super E, T> function); /** * Returns the contents of this Iterable as a List. * * @return a List representation of this Iterable */ List<E> asList(); /** * Utility method that iterates over iterable and adds the contents to a list. * * @param iterable the iterable to collect * @param <E> the type of the objects to iterate * @return a list with all objects of the given iterator */ static <E> List<E> copyToList(Iterable<E> iterable) { var copy = new ArrayList<E>(); iterable.forEach(copy::add); return copy; } }
3,991
35.290909
140
java
java-design-patterns
java-design-patterns-master/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.fluentinterface.fluentiterable.lazy; import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import lombok.RequiredArgsConstructor; /** * This is a lazy implementation of the FluentIterable interface. It evaluates all chained * operations when a terminating operation is applied. * * @param <E> the type of the objects the iteration is about */ @RequiredArgsConstructor public class LazyFluentIterable<E> implements FluentIterable<E> { private final Iterable<E> iterable; /** * This constructor can be used to implement anonymous subclasses of the LazyFluentIterable. */ protected LazyFluentIterable() { iterable = this; } /** * Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy * the predicate. * * @param predicate the condition to test with for the filtering. If the test is negative, the * tested object is removed by the iterator. * @return a new FluentIterable object that decorates the source iterable */ @Override public FluentIterable<E> filter(Predicate<? super E> predicate) { return new LazyFluentIterable<>() { @Override public Iterator<E> iterator() { return new DecoratingIterator<>(iterable.iterator()) { @Override public E computeNext() { while (fromIterator.hasNext()) { var candidate = fromIterator.next(); if (predicate.test(candidate)) { return candidate; } } return null; } }; } }; } /** * Can be used to collect objects from the iteration. Is a terminating operation. * * @return an Optional containing the first object of this Iterable */ @Override public Optional<E> first() { var resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } /** * Can be used to collect objects from the iteration. * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' first * objects. */ @Override public FluentIterable<E> first(int count) { return new LazyFluentIterable<>() { @Override public Iterator<E> iterator() { return new DecoratingIterator<>(iterable.iterator()) { int currentIndex; @Override public E computeNext() { if (currentIndex < count && fromIterator.hasNext()) { var candidate = fromIterator.next(); currentIndex++; return candidate; } return null; } }; } }; } /** * Can be used to collect objects from the iteration. Is a terminating operation. * * @return an Optional containing the last object of this Iterable */ @Override public Optional<E> last() { var resultIterator = last(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } /** * Can be used to collect objects from the Iterable. Is a terminating operation. This operation is * memory intensive, because the contents of this Iterable are collected into a List, when the * next object is requested. * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' last * objects */ @Override public FluentIterable<E> last(int count) { return new LazyFluentIterable<>() { @Override public Iterator<E> iterator() { return new DecoratingIterator<>(iterable.iterator()) { private int stopIndex; private int totalElementsCount; private List<E> list; private int currentIndex; @Override public E computeNext() { initialize(); while (currentIndex < stopIndex && fromIterator.hasNext()) { currentIndex++; fromIterator.next(); } if (currentIndex >= stopIndex && fromIterator.hasNext()) { return fromIterator.next(); } return null; } private void initialize() { if (list == null) { list = new ArrayList<>(); iterable.forEach(list::add); totalElementsCount = list.size(); stopIndex = totalElementsCount - count; } } }; } }; } /** * Transforms this FluentIterable into a new one containing objects of the type T. * * @param function a function that transforms an instance of E into an instance of T * @param <T> the target type of the transformation * @return a new FluentIterable of the new type */ @Override public <T> FluentIterable<T> map(Function<? super E, T> function) { return new LazyFluentIterable<>() { @Override public Iterator<T> iterator() { return new DecoratingIterator<>(null) { final Iterator<E> oldTypeIterator = iterable.iterator(); @Override public T computeNext() { if (oldTypeIterator.hasNext()) { E candidate = oldTypeIterator.next(); return function.apply(candidate); } else { return null; } } }; } }; } /** * Collects all remaining objects of this iteration into a list. * * @return a list with all remaining objects of this iteration */ @Override public List<E> asList() { return FluentIterable.copyToList(iterable); } @Override public Iterator<E> iterator() { return new DecoratingIterator<>(iterable.iterator()) { @Override public E computeNext() { return fromIterator.hasNext() ? fromIterator.next() : null; } }; } /** * Constructors FluentIterable from given iterable. * * @return a FluentIterable from a given iterable. Calls the LazyFluentIterable constructor. */ public static <E> FluentIterable<E> from(Iterable<E> iterable) { return new LazyFluentIterable<>(iterable); } }
7,753
31.174274
140
java
java-design-patterns
java-design-patterns-master/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.fluentinterface.fluentiterable.lazy; import java.util.Iterator; /** * This class is used to realize LazyFluentIterables. It decorates a given iterator. Does not * support consecutive hasNext() calls. * * @param <E> Iterable Collection of Elements of Type E */ public abstract class DecoratingIterator<E> implements Iterator<E> { protected final Iterator<E> fromIterator; private E next; /** * Creates an iterator that decorates the given iterator. */ public DecoratingIterator(Iterator<E> fromIterator) { this.fromIterator = fromIterator; } /** * Precomputes and saves the next element of the Iterable. null is considered as end of data. * * @return true if a next element is available */ @Override public final boolean hasNext() { next = computeNext(); return next != null; } /** * Returns the next element of the Iterable. * * @return the next element of the Iterable, or null if not present. */ @Override public final E next() { if (next == null) { return fromIterator.next(); } else { final var result = next; next = null; return result; } } /** * Computes the next object of the Iterable. Can be implemented to realize custom behaviour for an * iteration process. null is considered as end of data. * * @return the next element of the Iterable. */ public abstract E computeNext(); }
2,729
31.891566
140
java
java-design-patterns
java-design-patterns-master/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.fluentinterface.fluentiterable.simple; import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import lombok.RequiredArgsConstructor; /** * This is a simple implementation of the FluentIterable interface. It evaluates all chained * operations eagerly. This implementation would be costly to be utilized in real applications. * * @param <E> the type of the objects the iteration is about */ @RequiredArgsConstructor public class SimpleFluentIterable<E> implements FluentIterable<E> { private final Iterable<E> iterable; /** * Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy * the predicate. * * @param predicate the condition to test with for the filtering. If the test is negative, the * tested object is removed by the iterator. * @return the same FluentIterable with a filtered collection */ @Override public final FluentIterable<E> filter(Predicate<? super E> predicate) { var iterator = iterator(); while (iterator.hasNext()) { var nextElement = iterator.next(); if (!predicate.test(nextElement)) { iterator.remove(); } } return this; } /** * Can be used to collect objects from the Iterable. Is a terminating operation. * * @return an option of the first object of the Iterable */ @Override public final Optional<E> first() { var resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } /** * Can be used to collect objects from the Iterable. Is a terminating operation. * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' first * objects. */ @Override public final FluentIterable<E> first(int count) { var iterator = iterator(); var currentCount = 0; while (iterator.hasNext()) { iterator.next(); if (currentCount >= count) { iterator.remove(); } currentCount++; } return this; } /** * Can be used to collect objects from the Iterable. Is a terminating operation. * * @return an option of the last object of the Iterable */ @Override public final Optional<E> last() { var list = last(1).asList(); if (list.isEmpty()) { return Optional.empty(); } return Optional.of(list.get(0)); } /** * Can be used to collect objects from the Iterable. Is a terminating operation. * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' last * objects */ @Override public final FluentIterable<E> last(int count) { var remainingElementsCount = getRemainingElementsCount(); var iterator = iterator(); var currentIndex = 0; while (iterator.hasNext()) { iterator.next(); if (currentIndex < remainingElementsCount - count) { iterator.remove(); } currentIndex++; } return this; } /** * Transforms this FluentIterable into a new one containing objects of the type T. * * @param function a function that transforms an instance of E into an instance of T * @param <T> the target type of the transformation * @return a new FluentIterable of the new type */ @Override public final <T> FluentIterable<T> map(Function<? super E, T> function) { var temporaryList = new ArrayList<T>(); this.forEach(e -> temporaryList.add(function.apply(e))); return from(temporaryList); } /** * Collects all remaining objects of this Iterable into a list. * * @return a list with all remaining objects of this Iterable */ @Override public List<E> asList() { return toList(iterable.iterator()); } /** * Constructs FluentIterable from iterable. * * @return a FluentIterable from a given iterable. Calls the SimpleFluentIterable constructor. */ public static <E> FluentIterable<E> from(Iterable<E> iterable) { return new SimpleFluentIterable<>(iterable); } public static <E> FluentIterable<E> fromCopyOf(Iterable<E> iterable) { var copy = FluentIterable.copyToList(iterable); return new SimpleFluentIterable<>(copy); } @Override public Iterator<E> iterator() { return iterable.iterator(); } @Override public void forEach(Consumer<? super E> action) { iterable.forEach(action); } @Override public Spliterator<E> spliterator() { return iterable.spliterator(); } /** * Find the count of remaining objects of current iterable. * * @return the count of remaining objects of the current Iterable */ public final int getRemainingElementsCount() { var counter = 0; for (var ignored : this) { counter++; } return counter; } /** * Collects the remaining objects of the given iterator into a List. * * @return a new List with the remaining objects. */ public static <E> List<E> toList(Iterator<E> iterator) { var copy = new ArrayList<E>(); iterator.forEachRemaining(copy::add); return copy; } }
6,751
30.259259
140
java
java-design-patterns
java-design-patterns-master/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; import static java.time.Duration.ofMillis; 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 java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; /** * <p>This class provides several test case that test singleton construction.</p> * * <p>The first proves that multiple calls to the singleton getInstance object are the same when * called in the SAME thread. The second proves that multiple calls to the singleton getInstance * object are the same when called in the DIFFERENT thread.</p> * * <p>Date: 12/29/15 - 19:25 PM</p> * * @param <S> Supplier method generating singletons * @author Jeroen Meulemeester * @author Richard Jones */ abstract class SingletonTest<S> { /** * The singleton's getInstance method. */ private final Supplier<S> singletonInstanceMethod; /** * Create a new singleton test instance using the given 'getInstance' method. * * @param singletonInstanceMethod The singleton's getInstance method */ public SingletonTest(final Supplier<S> singletonInstanceMethod) { this.singletonInstanceMethod = singletonInstanceMethod; } /** * Test the singleton in a non-concurrent setting. */ @Test void testMultipleCallsReturnTheSameObjectInSameThread() { // Create several instances in the same calling thread var instance1 = this.singletonInstanceMethod.get(); var instance2 = this.singletonInstanceMethod.get(); var instance3 = this.singletonInstanceMethod.get(); // now check they are equal assertSame(instance1, instance2); assertSame(instance1, instance3); assertSame(instance2, instance3); } /** * Test singleton instance in a concurrent setting. */ @Test void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exception { assertTimeout(ofMillis(10000), () -> { // Create 10000 tasks and inside each callable instantiate the singleton class final var tasks = IntStream.range(0, 10000) .<Callable<S>>mapToObj(i -> this.singletonInstanceMethod::get) .collect(Collectors.toCollection(ArrayList::new)); // Use up to 8 concurrent threads to handle the tasks final var executorService = Executors.newFixedThreadPool(8); final var results = executorService.invokeAll(tasks); // wait for all of the threads to complete final var expectedInstance = this.singletonInstanceMethod.get(); for (var res : results) { final var instance = res.get(); assertNotNull(instance); assertSame(expectedInstance, instance); } // tidy up the executor executorService.shutdown(); }); } }
4,267
36.438596
140
java
java-design-patterns
java-design-patterns-master/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; /** * Date: 12/29/15 - 19:26 PM. * * @author Jeroen Meulemeester */ class ThreadSafeLazyLoadedIvoryTowerTest extends SingletonTest<ThreadSafeLazyLoadedIvoryTower> { /** * Create a new singleton test instance using the given 'getInstance' method. */ public ThreadSafeLazyLoadedIvoryTowerTest() { super(ThreadSafeLazyLoadedIvoryTower::getInstance); } }
1,694
38.418605
140
java
java-design-patterns
java-design-patterns-master/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; /** * Date: 12/29/15 - 19:20 PM. * * @author Jeroen Meulemeester */ class EnumIvoryTowerTest extends SingletonTest<EnumIvoryTower> { /** * Create a new singleton test instance using the given 'getInstance' method. */ public EnumIvoryTowerTest() { super(() -> EnumIvoryTower.INSTANCE); } }
1,628
37.785714
140
java
java-design-patterns
java-design-patterns-master/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; /** * Date: 12/29/15 - 19:22 PM. * * @author Jeroen Meulemeester */ class InitializingOnDemandHolderIdiomTest extends SingletonTest<InitializingOnDemandHolderIdiom> { /** * Create a new singleton test instance using the given 'getInstance' method. */ public InitializingOnDemandHolderIdiomTest() { super(InitializingOnDemandHolderIdiom::getInstance); } }
1,697
39.428571
140
java
java-design-patterns
java-design-patterns-master/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; import static org.junit.jupiter.api.Assertions.assertThrows; import java.lang.reflect.InvocationTargetException; import org.junit.jupiter.api.Test; /** * Date: 12/29/15 - 19:26 PM. * * @author Jeroen Meulemeester */ class ThreadSafeDoubleCheckLockingTest extends SingletonTest<ThreadSafeDoubleCheckLocking> { /** * Create a new singleton test instance using the given 'getInstance' method. */ public ThreadSafeDoubleCheckLockingTest() { super(ThreadSafeDoubleCheckLocking::getInstance); } /** * Test creating new instance by refection. */ @Test void testCreatingNewInstanceByRefection() throws Exception { ThreadSafeDoubleCheckLocking.getInstance(); var constructor = ThreadSafeDoubleCheckLocking.class.getDeclaredConstructor(); constructor.setAccessible(true); assertThrows(InvocationTargetException.class, () -> constructor.newInstance((Object[]) null)); } }
2,233
37.517241
140
java
java-design-patterns
java-design-patterns-master/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; /** * Date: 12/29/15 - 19:23 PM. * * @author Jeroen Meulemeester */ class IvoryTowerTest extends SingletonTest<IvoryTower> { /** * Create a new singleton test instance using the given 'getInstance' method. */ public IvoryTowerTest() { super(IvoryTower::getInstance); } }
1,609
38.268293
140
java
java-design-patterns
java-design-patterns-master/singleton/src/test/java/com/iluwatar/singleton/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test. */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,578
37.512195
140
java
java-design-patterns
java-design-patterns-master/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; /** * <p>The Initialize-on-demand-holder idiom is a secure way of creating a lazy initialized singleton * object in Java.</p> * * <p>The technique is as lazy as possible and works in all known versions of Java. It takes * advantage of language guarantees about class initialization, and will therefore work correctly * in all Java-compliant compilers and virtual machines.</p> * * <p>The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) * than the moment that getInstance() is called. Thus, this solution is thread-safe without * requiring special language constructs (i.e. volatile or synchronized).</p> * */ public final class InitializingOnDemandHolderIdiom { /** * Private constructor. */ private InitializingOnDemandHolderIdiom() { } /** * Singleton instance. * * @return Singleton instance */ public static InitializingOnDemandHolderIdiom getInstance() { return HelperHolder.INSTANCE; } /** * Provides the lazy-loaded Singleton instance. */ private static class HelperHolder { private static final InitializingOnDemandHolderIdiom INSTANCE = new InitializingOnDemandHolderIdiom(); } }
2,522
37.815385
140
java
java-design-patterns
java-design-patterns-master/singleton/src/main/java/com/iluwatar/singleton/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; import lombok.extern.slf4j.Slf4j; /** * <p>Singleton pattern ensures that the class can have only one existing instance per Java * classloader instance and provides global access to it.</p> * * <p>One of the risks of this pattern is that bugs resulting from setting a singleton up in a * distributed environment can be tricky to debug since it will work fine if you debug with a * single classloader. Additionally, these problems can crop up a while after the implementation of * a singleton, since they may start synchronous and only become async with time, so it may * not be clear why you are seeing certain changes in behavior.</p> * * <p>There are many ways to implement the Singleton. The first one is the eagerly initialized * instance in {@link IvoryTower}. Eager initialization implies that the implementation is thread * safe. If you can afford to give up control of the instantiation moment, then this implementation * will suit you fine.</p> * * <p>The other option to implement eagerly initialized Singleton is enum-based Singleton. The * example is found in {@link EnumIvoryTower}. At first glance, the code looks short and simple. * However, you should be aware of the downsides including committing to implementation strategy, * extending the enum class, serializability, and restrictions to coding. These are extensively * discussed in Stack Overflow: http://programmers.stackexchange.com/questions/179386/what-are-the-downsides-of-implementing * -a-singleton-with-javas-enum</p> * * <p>{@link ThreadSafeLazyLoadedIvoryTower} is a Singleton implementation that is initialized on * demand. The downside is that it is very slow to access since the whole access method is * synchronized.</p> * * <p>Another Singleton implementation that is initialized on demand is found in * {@link ThreadSafeDoubleCheckLocking}. It is somewhat faster than {@link * ThreadSafeLazyLoadedIvoryTower} since it doesn't synchronize the whole access method but only the * method internals on specific conditions.</p> * * <p>Yet another way to implement thread-safe lazily initialized Singleton can be found in * {@link InitializingOnDemandHolderIdiom}. However, this implementation requires at least Java 8 * API level to work.</p> */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // eagerly initialized singleton var ivoryTower1 = IvoryTower.getInstance(); var ivoryTower2 = IvoryTower.getInstance(); LOGGER.info("ivoryTower1={}", ivoryTower1); LOGGER.info("ivoryTower2={}", ivoryTower2); // lazily initialized singleton var threadSafeIvoryTower1 = ThreadSafeLazyLoadedIvoryTower.getInstance(); var threadSafeIvoryTower2 = ThreadSafeLazyLoadedIvoryTower.getInstance(); LOGGER.info("threadSafeIvoryTower1={}", threadSafeIvoryTower1); LOGGER.info("threadSafeIvoryTower2={}", threadSafeIvoryTower2); // enum singleton var enumIvoryTower1 = EnumIvoryTower.INSTANCE; var enumIvoryTower2 = EnumIvoryTower.INSTANCE; LOGGER.info("enumIvoryTower1={}", enumIvoryTower1); LOGGER.info("enumIvoryTower2={}", enumIvoryTower2); // double checked locking var dcl1 = ThreadSafeDoubleCheckLocking.getInstance(); LOGGER.info(dcl1.toString()); var dcl2 = ThreadSafeDoubleCheckLocking.getInstance(); LOGGER.info(dcl2.toString()); // initialize on demand holder idiom var demandHolderIdiom = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom.toString()); var demandHolderIdiom2 = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom2.toString()); } }
5,034
46.952381
140
java
java-design-patterns
java-design-patterns-master/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; /** * <p>Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization * mechanism.</p> * */ public final class ThreadSafeLazyLoadedIvoryTower { private static volatile ThreadSafeLazyLoadedIvoryTower instance; private ThreadSafeLazyLoadedIvoryTower() { // Protect against instantiation via reflection if (instance != null) { throw new IllegalStateException("Already initialized."); } } /** * The instance doesn't get created until the method is called for the first time. */ public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() { if (instance == null) { instance = new ThreadSafeLazyLoadedIvoryTower(); } return instance; } }
2,056
37.811321
140
java
java-design-patterns
java-design-patterns-master/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; /** * <p>Double check locking.</p> * * <p>http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html</p> * * <p>Broken under Java 1.4.</p> * * @author mortezaadi@gmail.com */ public final class ThreadSafeDoubleCheckLocking { private static volatile ThreadSafeDoubleCheckLocking instance; /** * private constructor to prevent client from instantiating. */ private ThreadSafeDoubleCheckLocking() { // to prevent instantiating by Reflection call if (instance != null) { throw new IllegalStateException("Already initialized."); } } /** * Public accessor. * * @return an instance of the class. */ public static ThreadSafeDoubleCheckLocking getInstance() { // local variable increases performance by 25 percent // Joshua Bloch "Effective Java, Second Edition", p. 283-284 var result = instance; // Check if singleton instance is initialized. // If it is initialized then we can return the instance. if (result == null) { // It is not initialized but we cannot be sure because some other thread might have // initialized it in the meanwhile. // So to make sure we need to lock on an object to get mutual exclusion. synchronized (ThreadSafeDoubleCheckLocking.class) { // Again assign the instance to local variable to check if it was initialized by some // other thread while current thread was blocked to enter the locked zone. // If it was initialized then we can return the previously created instance // just like the previous null check. result = instance; if (result == null) { // The instance is still not initialized so we can safely // (no other thread can enter this zone) // create an instance and make it our singleton instance. instance = result = new ThreadSafeDoubleCheckLocking(); } } } return result; } }
3,263
38.325301
140
java
java-design-patterns
java-design-patterns-master/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; /** * Singleton class. Eagerly initialized static instance guarantees thread safety. */ public final class IvoryTower { /** * Private constructor so nobody can instantiate the class. */ private IvoryTower() { } /** * Static to class instance of the class. */ private static final IvoryTower INSTANCE = new IvoryTower(); /** * To be called by user to obtain instance of the class. * * @return instance of the singleton. */ public static IvoryTower getInstance() { return INSTANCE; } }
1,850
34.596154
140
java
java-design-patterns
java-design-patterns-master/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.singleton; /** * <p>Enum based singleton implementation. Effective Java 2nd Edition (Joshua Bloch) p. 18</p> * * <p>This implementation is thread safe, however adding any other method and its thread safety * is developers responsibility.</p> */ public enum EnumIvoryTower { INSTANCE; @Override public String toString() { return getDeclaringClass().getCanonicalName() + "@" + hashCode(); } }
1,716
39.880952
140
java
java-design-patterns
java-design-patterns-master/filterer/src/test/java/com/iluwatar/filterer/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; class AppTest { @Test void shouldLaunchApp() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,533
40.459459
140
java
java-design-patterns
java-design-patterns-master/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class SimpleThreatAwareSystemTest { @Test void shouldFilterByThreatType() { //given var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit"); var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan"); List<Threat> threats = List.of(rootkit, trojan); var threatAwareSystem = new SimpleThreatAwareSystem("System-1", threats); //when var rootkitThreatAwareSystem = threatAwareSystem.filtered() .by(threat -> threat.type() == ThreatType.ROOTKIT); //then assertEquals(rootkitThreatAwareSystem.threats().size(), 1); assertEquals(rootkitThreatAwareSystem.threats().get(0), rootkit); } }
2,095
40.92
140
java
java-design-patterns
java-design-patterns-master/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.Test; class SimpleProbabilisticThreatAwareSystemTest { @Test void shouldFilterByProbability() { //given var trojan = new SimpleProbableThreat("Troyan-ArcBomb", 1, ThreatType.TROJAN, 0.99); var rootkit = new SimpleProbableThreat("Rootkit-System", 2, ThreatType.ROOTKIT, 0.8); List<ProbableThreat> probableThreats = List.of(trojan, rootkit); var simpleProbabilisticThreatAwareSystem = new SimpleProbabilisticThreatAwareSystem("System-1", probableThreats); //when var filtered = simpleProbabilisticThreatAwareSystem.filtered() .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); //then assertEquals(filtered.threats().size(), 1); assertEquals(filtered.threats().get(0), trojan); } }
2,211
41.538462
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer; import com.iluwatar.filterer.threat.ProbableThreat; import com.iluwatar.filterer.threat.SimpleProbabilisticThreatAwareSystem; import com.iluwatar.filterer.threat.SimpleProbableThreat; import com.iluwatar.filterer.threat.SimpleThreat; import com.iluwatar.filterer.threat.SimpleThreatAwareSystem; import com.iluwatar.filterer.threat.Threat; import com.iluwatar.filterer.threat.ThreatAwareSystem; import com.iluwatar.filterer.threat.ThreatType; import java.util.List; import java.util.function.Predicate; import lombok.extern.slf4j.Slf4j; /** * This demo class represent how {@link com.iluwatar.filterer.domain.Filterer} pattern is used to * filter container-like objects to return filtered versions of themselves. The container like * objects are systems that are aware of threats that they can be vulnerable to. We would like * to have a way to create copy of different system objects but with filtered threats. * The thing is to keep it simple if we add new subtype of {@link Threat} * (for example {@link ProbableThreat}) - we still need to be able to filter by it's properties. */ @Slf4j public class App { public static void main(String[] args) { filteringSimpleThreats(); filteringSimpleProbableThreats(); } /** * Demonstrates how to filter {@link com.iluwatar.filterer.threat.ProbabilisticThreatAwareSystem} * based on probability property. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)} * method is able to use {@link com.iluwatar.filterer.threat.ProbableThreat} * as predicate argument. */ private static void filteringSimpleProbableThreats() { LOGGER.info("### Filtering ProbabilisticThreatAwareSystem by probability ###"); var trojanArcBomb = new SimpleProbableThreat("Trojan-ArcBomb", 1, ThreatType.TROJAN, 0.99); var rootkit = new SimpleProbableThreat("Rootkit-Kernel", 2, ThreatType.ROOTKIT, 0.8); List<ProbableThreat> probableThreats = List.of(trojanArcBomb, rootkit); var probabilisticThreatAwareSystem = new SimpleProbabilisticThreatAwareSystem("Sys-1", probableThreats); LOGGER.info("Filtering ProbabilisticThreatAwareSystem. Initial : " + probabilisticThreatAwareSystem); //Filtering using filterer var filteredThreatAwareSystem = probabilisticThreatAwareSystem.filtered() .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); LOGGER.info("Filtered by probability = 0.99 : " + filteredThreatAwareSystem); } /** * Demonstrates how to filter {@link ThreatAwareSystem} based on startingOffset property * of {@link SimpleThreat}. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)} * method is able to use {@link Threat} as predicate argument. */ private static void filteringSimpleThreats() { LOGGER.info("### Filtering ThreatAwareSystem by ThreatType ###"); var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit"); var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan"); List<Threat> threats = List.of(rootkit, trojan); var threatAwareSystem = new SimpleThreatAwareSystem("Sys-1", threats); LOGGER.info("Filtering ThreatAwareSystem. Initial : " + threatAwareSystem); //Filtering using Filterer var rootkitThreatAwareSystem = threatAwareSystem.filtered() .by(threat -> threat.type() == ThreatType.ROOTKIT); LOGGER.info("Filtered by threatType = ROOTKIT : " + rootkitThreatAwareSystem); } }
4,785
44.150943
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; /** * Represents threat that might be a threat with given probability. */ public interface ProbableThreat extends Threat { /** * Returns probability of occurrence of given threat. * @return probability of occurrence of given threat. */ double probability(); }
1,597
43.388889
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; import com.iluwatar.filterer.domain.Filterer; import java.util.List; /** * Represents system that is aware of it's threats with given probability of their occurrence. */ public interface ProbabilisticThreatAwareSystem extends ThreatAwareSystem { /** * {@inheritDoc} * @return {@link ProbableThreat} */ @Override List<? extends ProbableThreat> threats(); /** * {@inheritDoc} * @return {@link Filterer} */ @Override Filterer<? extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat> filtered(); }
1,864
36.3
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; /** * Represents a threat that can be detected in given system. */ public interface Threat { /** * Returns name of the threat. * * @return value representing name of the threat. */ String name(); /** * Returns unique id of the threat. * * @return value representing threat id. */ int id(); /** * Returns threat type. * @return {@link ThreatType} */ ThreatType type(); }
1,742
33.176471
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; import com.iluwatar.filterer.domain.Filterer; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.ToString; /** * {@inheritDoc} */ @ToString @EqualsAndHashCode @RequiredArgsConstructor public class SimpleProbabilisticThreatAwareSystem implements ProbabilisticThreatAwareSystem { private final String systemId; private final List<ProbableThreat> threats; /** * {@inheritDoc} */ @Override public String systemId() { return systemId; } /** * {@inheritDoc} */ @Override public List<? extends ProbableThreat> threats() { return threats; } /** * {@inheritDoc} */ @Override public Filterer<? extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat> filtered() { return this::filteredGroup; } private ProbabilisticThreatAwareSystem filteredGroup( final Predicate<? super ProbableThreat> predicate) { return new SimpleProbabilisticThreatAwareSystem(this.systemId, filteredItems(predicate)); } private List<ProbableThreat> filteredItems( final Predicate<? super ProbableThreat> predicate) { return this.threats.stream() .filter(predicate) .toList(); } }
2,618
30.554217
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.ToString; /** * Represents a simple threat. */ @ToString @EqualsAndHashCode @RequiredArgsConstructor public class SimpleThreat implements Threat { private final ThreatType threatType; private final int id; private final String name; /** * {@inheritDoc} */ @Override public String name() { return name; } /** * {@inheritDoc} */ @Override public int id() { return id; } /** * {@inheritDoc} */ @Override public ThreatType type() { return threatType; } }
1,928
27.367647
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; /** * Enum class representing Threat types. */ public enum ThreatType { TROJAN, WORM, ROOTKIT }
1,427
39.8
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; import com.iluwatar.filterer.domain.Filterer; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.ToString; /** * {@inheritDoc} */ @ToString @EqualsAndHashCode @RequiredArgsConstructor public class SimpleThreatAwareSystem implements ThreatAwareSystem { private final String systemId; private final List<Threat> issues; /** * {@inheritDoc} */ @Override public String systemId() { return systemId; } /** * {@inheritDoc} */ @Override public List<? extends Threat> threats() { return new ArrayList<>(issues); } /** * {@inheritDoc} */ @Override public Filterer<? extends ThreatAwareSystem, ? extends Threat> filtered() { return this::filteredGroup; } private ThreatAwareSystem filteredGroup(Predicate<? super Threat> predicate) { return new SimpleThreatAwareSystem(this.systemId, filteredItems(predicate)); } private List<Threat> filteredItems(Predicate<? super Threat> predicate) { return this.issues.stream() .filter(predicate).toList(); } }
2,516
30.074074
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; import lombok.EqualsAndHashCode; /** * {@inheritDoc} */ @EqualsAndHashCode(callSuper = false) public class SimpleProbableThreat extends SimpleThreat implements ProbableThreat { private final double probability; public SimpleProbableThreat(final String name, final int id, final ThreatType threatType, final double probability) { super(threatType, id, name); this.probability = probability; } /** * {@inheritDoc} */ @Override public double probability() { return probability; } @Override public String toString() { return "SimpleProbableThreat{" + "probability=" + probability + "} " + super.toString(); } }
2,033
33.474576
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.threat; import com.iluwatar.filterer.domain.Filterer; import java.util.List; /** * Represents system that is aware of threats that are present in it. */ public interface ThreatAwareSystem { /** * Returns the system id. * * @return system id. */ String systemId(); /** * Returns list of threats for this system. * @return list of threats for this system. */ List<? extends Threat> threats(); /** * Returns the instance of {@link Filterer} helper interface that allows to covariantly * specify lower bound for predicate that we want to filter by. * @return an instance of {@link Filterer} helper interface. */ Filterer<? extends ThreatAwareSystem, ? extends Threat> filtered(); }
2,045
35.535714
140
java
java-design-patterns
java-design-patterns-master/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.filterer.domain; import java.util.function.Predicate; /** * Filterer helper interface. * @param <G> type of the container-like object. * @param <E> type of the elements contained within this container-like object. */ @FunctionalInterface public interface Filterer<G, E> { G by(Predicate<? super E> predicate); }
1,624
42.918919
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; /** * Date: 12/21/15 - 12:12 PM * * @author Jeroen Meulemeester */ class FileLoaderTest { @Test void testLoadData() { final var fileLoader = new FileLoader(); fileLoader.setFileName("non-existing-file"); assertNull(fileLoader.loadData()); } }
1,690
36.577778
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * This test case is responsible for testing our application by taking advantage of the * Model-View-Controller architectural pattern. */ class FileSelectorPresenterTest { /** * The Presenter component. */ private FileSelectorPresenter presenter; /** * The View component, implemented this time as a Stub!!! */ private FileSelectorStub stub; /** * The Model component. */ private FileLoader loader; /** * Initializes the components of the test case. */ @BeforeEach void setUp() { this.stub = new FileSelectorStub(); this.loader = new FileLoader(); presenter = new FileSelectorPresenter(this.stub); presenter.setLoader(loader); } /** * Tests if the Presenter was successfully connected with the View. */ @Test void wiring() { presenter.start(); assertNotNull(stub.getPresenter()); assertTrue(stub.isOpened()); } /** * Tests if the name of the file changes. */ @Test void updateFileNameToLoader() { var expectedFile = "Stamatis"; stub.setFileName(expectedFile); presenter.start(); presenter.fileNameChanged(); assertEquals(expectedFile, loader.getFileName()); } /** * Tests if we receive a confirmation when we attempt to open a file that it's name is null or an * empty string. */ @Test void fileConfirmationWhenNameIsNull() { stub.setFileName(null); presenter.start(); presenter.fileNameChanged(); presenter.confirmed(); assertFalse(loader.isLoaded()); assertEquals(1, stub.getMessagesSent()); } /** * Tests if we receive a confirmation when we attempt to open a file that it doesn't exist. */ @Test void fileConfirmationWhenFileDoesNotExist() { stub.setFileName("RandomName.txt"); presenter.start(); presenter.fileNameChanged(); presenter.confirmed(); assertFalse(loader.isLoaded()); assertEquals(1, stub.getMessagesSent()); } /** * Tests if we can open the file, when it exists. */ @Test void fileConfirmationWhenFileExists() { stub.setFileName("etc/data/test.txt"); presenter.start(); presenter.fileNameChanged(); presenter.confirmed(); assertTrue(loader.isLoaded()); assertTrue(stub.dataDisplayed()); } /** * Tests if the view closes after cancellation. */ @Test void cancellation() { presenter.start(); presenter.cancelled(); assertFalse(stub.isOpened()); } @Test void testNullFile() { stub.setFileName(null); presenter.start(); presenter.fileNameChanged(); presenter.confirmed(); assertFalse(loader.isLoaded()); assertFalse(stub.dataDisplayed()); } }
4,326
26.04375
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorJframeTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import java.awt.event.ActionEvent; import org.junit.jupiter.api.Test; /** * Date: 01/29/23 - 6:00 PM * * @author Rahul Raj */ class FileSelectorJframeTest { /** * Tests if the jframe action event is triggered without any exception. */ @Test void testActionEvent() { assertDoesNotThrow(() ->{ FileSelectorJframe jFrame = new FileSelectorJframe(); ActionEvent action = new ActionEvent("dummy", 1, "dummy"); jFrame.actionPerformed(action); }); } }
1,915
35.150943
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,600
37.119048
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; /** * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is called "The * separation of concerns" principle. This is accomplished by separating the application's logic * (Model), GUIs (View), and finally the way that the user's actions update the application's logic * (Presenter). * * <p>In the following example, The {@link FileLoader} class represents the app's logic, the {@link * FileSelectorJframe} is the GUI and the {@link FileSelectorPresenter} is responsible to respond to * users' actions. * * <p>Finally, please notice the wiring between the Presenter and the View and between the * Presenter and the Model. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var loader = new FileLoader(); var frame = new FileSelectorJframe(); var presenter = new FileSelectorPresenter(frame); presenter.setLoader(loader); presenter.start(); } }
2,321
41.218182
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJframe.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; /** * This class is the GUI implementation of the View component in the Model-View-Presenter pattern. */ public class FileSelectorJframe extends JFrame implements FileSelectorView, ActionListener { /** * Default serial version ID. */ private static final long serialVersionUID = 1L; /** * The "OK" button for loading the file. */ private final JButton ok; /** * The cancel button. */ private final JButton cancel; /** * The text field for giving the name of the file that we want to open. */ private final JTextField input; /** * A text area that will keep the contents of the file opened. */ private final JTextArea area; /** * The Presenter component that the frame will interact with. */ private FileSelectorPresenter presenter; /** * The name of the file that we want to read it's contents. */ private String fileName; /** * Constructor. */ public FileSelectorJframe() { super("File Loader"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setLayout(null); this.setBounds(100, 100, 500, 200); /* * Add the panel. */ var panel = new JPanel(); panel.setLayout(null); this.add(panel); panel.setBounds(0, 0, 500, 200); panel.setBackground(Color.LIGHT_GRAY); /* * Add the info label. */ var info = new JLabel("File Name :"); panel.add(info); info.setBounds(30, 10, 100, 30); /* * Add the contents label. */ var contents = new JLabel("File contents :"); panel.add(contents); contents.setBounds(30, 100, 120, 30); /* * Add the text field. */ this.input = new JTextField(100); panel.add(input); this.input.setBounds(150, 15, 200, 20); /* * Add the text area. */ this.area = new JTextArea(100, 100); var pane = new JScrollPane(area); pane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED); pane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED); panel.add(pane); this.area.setEditable(false); pane.setBounds(150, 100, 250, 80); /* * Add the OK button. */ this.ok = new JButton("OK"); panel.add(ok); this.ok.setBounds(250, 50, 100, 25); this.ok.addActionListener(this); /* * Add the cancel button. */ this.cancel = new JButton("Cancel"); panel.add(this.cancel); this.cancel.setBounds(380, 50, 100, 25); this.cancel.addActionListener(this); this.presenter = null; this.fileName = null; } @Override public void actionPerformed(ActionEvent e) { if (this.ok.equals(e.getSource())) { this.fileName = this.input.getText(); presenter.fileNameChanged(); presenter.confirmed(); } else if (this.cancel.equals(e.getSource())) { presenter.cancelled(); } } @Override public void open() { this.setVisible(true); } @Override public void close() { this.dispose(); } @Override public boolean isOpened() { return this.isVisible(); } @Override public void setPresenter(FileSelectorPresenter presenter) { this.presenter = presenter; } @Override public FileSelectorPresenter getPresenter() { return this.presenter; } @Override public void setFileName(String name) { this.fileName = name; } @Override public String getFileName() { return this.fileName; } @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @Override public void displayData(String data) { this.area.setText(data); } }
5,421
25.067308
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; import java.io.Serializable; /** * This interface represents the View component in the Model-View-Presenter pattern. It can be * implemented by either the GUI components, or by the Stub. */ public interface FileSelectorView extends Serializable { /** * Opens the view. */ void open(); /** * Closes the view. */ void close(); /** * Returns true if view is opened. * * @return True, if the view is opened, false otherwise. */ boolean isOpened(); /** * Sets the presenter component, to the one given as parameter. * * @param presenter The new presenter component. */ void setPresenter(FileSelectorPresenter presenter); /** * Gets presenter component. * * @return The presenter Component. */ FileSelectorPresenter getPresenter(); /** * Sets the file's name, to the value given as parameter. * * @param name The new name of the file. */ void setFileName(String name); /** * Gets the name of file. * * @return The name of the file. */ String getFileName(); /** * Displays a message to the users. * * @param message The message to be displayed. */ void showMessage(String message); /** * Displays the data to the view. * * @param data The data to be written. */ void displayData(String data); }
2,661
27.319149
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.Serializable; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Every instance of this class represents the Model component in the Model-View-Presenter * architectural pattern. * * <p>It is responsible for reading and loading the contents of a given file. */ public class FileLoader implements Serializable { /** * Generated serial version UID. */ private static final long serialVersionUID = -4745803872902019069L; private static final Logger LOGGER = LoggerFactory.getLogger(FileLoader.class); /** * Indicates if the file is loaded or not. */ private boolean loaded; /** * The name of the file that we want to load. */ private String fileName; /** * Loads the data of the file specified. */ public String loadData() { var dataFileName = this.fileName; try (var br = new BufferedReader(new FileReader(new File(dataFileName)))) { var result = br.lines().collect(Collectors.joining("\n")); this.loaded = true; return result; } catch (Exception e) { LOGGER.error("File {} does not exist", dataFileName); } return null; } /** * Sets the path of the file to be loaded, to the given value. * * @param fileName The path of the file to be loaded. */ public void setFileName(String fileName) { this.fileName = fileName; } /** * Gets the path of the file to be loaded. * * @return fileName The path of the file to be loaded. */ public String getFileName() { return this.fileName; } /** * Returns true if the given file exists. * * @return True, if the file given exists, false otherwise. */ public boolean fileExists() { return new File(this.fileName).exists(); } /** * Returns true if the given file is loaded. * * @return True, if the file is loaded, false otherwise. */ public boolean isLoaded() { return this.loaded; } }
3,379
29.178571
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; import java.io.Serializable; /** * Every instance of this class represents the Presenter component in the Model-View-Presenter * architectural pattern. * * <p>It is responsible for reacting to the user's actions and update the View component. */ public class FileSelectorPresenter implements Serializable { /** * Generated serial version UID. */ private static final long serialVersionUID = 1210314339075855074L; /** * The View component that the presenter interacts with. */ private final FileSelectorView view; /** * The Model component that the presenter interacts with. */ private FileLoader loader; /** * Constructor. * * @param view The view component that the presenter will interact with. */ public FileSelectorPresenter(FileSelectorView view) { this.view = view; } /** * Sets the {@link FileLoader} object, to the value given as parameter. * * @param loader The new {@link FileLoader} object(the Model component). */ public void setLoader(FileLoader loader) { this.loader = loader; } /** * Starts the presenter. */ public void start() { view.setPresenter(this); view.open(); } /** * An "event" that fires when the name of the file to be loaded changes. */ public void fileNameChanged() { loader.setFileName(view.getFileName()); } /** * Ok button handler. */ public void confirmed() { if (loader.getFileName() == null || loader.getFileName().equals("")) { view.showMessage("Please give the name of the file first!"); return; } if (loader.fileExists()) { var data = loader.loadData(); view.displayData(data); } else { view.showMessage("The file specified does not exist."); } } /** * Cancels the file loading process. */ public void cancelled() { view.close(); } }
3,204
28.40367
140
java
java-design-patterns
java-design-patterns-master/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.model.view.presenter; /** * Every instance of this class represents the Stub component in the Model-View-Presenter * architectural pattern. * * <p>The stub implements the View interface and it is useful when we want the test the reaction to * user events, such as mouse clicks. * * <p>Since we can not test the GUI directly, the MVP pattern provides this functionality through * the View's dummy implementation, the Stub. */ public class FileSelectorStub implements FileSelectorView { /** * Indicates whether or not the view is opened. */ private boolean opened; /** * The presenter Component. */ private FileSelectorPresenter presenter; /** * The current name of the file. */ private String name; /** * Indicates the number of messages that were "displayed" to the user. */ private int numOfMessageSent; /** * Indicates if the data of the file where displayed or not. */ private boolean dataDisplayed; /** * Constructor. */ public FileSelectorStub() { this.opened = false; this.presenter = null; this.name = ""; this.numOfMessageSent = 0; this.dataDisplayed = false; } @Override public void open() { this.opened = true; } @Override public void setPresenter(FileSelectorPresenter presenter) { this.presenter = presenter; } @Override public boolean isOpened() { return this.opened; } @Override public FileSelectorPresenter getPresenter() { return this.presenter; } @Override public String getFileName() { return this.name; } @Override public void setFileName(String name) { this.name = name; } @Override public void showMessage(String message) { this.numOfMessageSent++; } @Override public void close() { this.opened = false; } @Override public void displayData(String data) { this.dataDisplayed = true; } /** * Returns the number of messages that were displayed to the user. */ public int getMessagesSent() { return this.numOfMessageSent; } /** * Returns true, if the data were displayed. * * @return True if the data where displayed, false otherwise. */ public boolean dataDisplayed() { return this.dataDisplayed; } }
3,561
25.191176
140
java
java-design-patterns
java-design-patterns-master/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.nullobject; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** * Date: 12/26/15 - 11:44 PM * * @author Jeroen Meulemeester */ class TreeTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } /** * During the tests, the same tree structure will be used, shown below. End points will be * terminated with the {@link NullNode} instance. * * <pre> * root * ├── level1_a * │   ├── level2_a * │   │   ├── level3_a * │   │   └── level3_b * │   └── level2_b * └── level1_b * </pre> */ private static final Node TREE_ROOT; static { final var level1B = new NodeImpl("level1_b", NullNode.getInstance(), NullNode.getInstance()); final var level2B = new NodeImpl("level2_b", NullNode.getInstance(), NullNode.getInstance()); final var level3A = new NodeImpl("level3_a", NullNode.getInstance(), NullNode.getInstance()); final var level3B = new NodeImpl("level3_b", NullNode.getInstance(), NullNode.getInstance()); final var level2A = new NodeImpl("level2_a", level3A, level3B); final var level1A = new NodeImpl("level1_a", level2A, level2B); TREE_ROOT = new NodeImpl("root", level1A, level1B); } /** * Verify the number of items in the tree. The root has 6 children so we expect a {@link * Node#getTreeSize()} of 7 {@link Node}s in total. */ @Test void testTreeSize() { assertEquals(7, TREE_ROOT.getTreeSize()); } /** * Walk through the tree and verify if every item is handled */ @Test void testWalk() { TREE_ROOT.walk(); assertTrue(appender.logContains("root")); assertTrue(appender.logContains("level1_a")); assertTrue(appender.logContains("level2_a")); assertTrue(appender.logContains("level3_a")); assertTrue(appender.logContains("level3_b")); assertTrue(appender.logContains("level2_b")); assertTrue(appender.logContains("level1_b")); assertEquals(7, appender.getLogSize()); } @Test void testGetLeft() { final var level1 = TREE_ROOT.getLeft(); assertNotNull(level1); assertEquals("level1_a", level1.getName()); assertEquals(5, level1.getTreeSize()); final var level2 = level1.getLeft(); assertNotNull(level2); assertEquals("level2_a", level2.getName()); assertEquals(3, level2.getTreeSize()); final var level3 = level2.getLeft(); assertNotNull(level3); assertEquals("level3_a", level3.getName()); assertEquals(1, level3.getTreeSize()); assertSame(NullNode.getInstance(), level3.getRight()); assertSame(NullNode.getInstance(), level3.getLeft()); } @Test void testGetRight() { final var level1 = TREE_ROOT.getRight(); assertNotNull(level1); assertEquals("level1_b", level1.getName()); assertEquals(1, level1.getTreeSize()); assertSame(NullNode.getInstance(), level1.getRight()); assertSame(NullNode.getInstance(), level1.getLeft()); } private static class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public boolean logContains(String message) { return log.stream().map(ILoggingEvent::getMessage).anyMatch(message::equals); } public int getLogSize() { return log.size(); } } }
5,407
31.578313
140
java
java-design-patterns
java-design-patterns-master/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.nullobject; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,589
37.780488
140
java
java-design-patterns
java-design-patterns-master/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.nullobject; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; /** * Date: 12/26/15 - 11:47 PM * * @author Jeroen Meulemeester */ class NullNodeTest { /** * Verify if {@link NullNode#getInstance()} actually returns the same object instance */ @Test void testGetInstance() { final var instance = NullNode.getInstance(); assertNotNull(instance); assertSame(instance, NullNode.getInstance()); } @Test void testFields() { final var node = NullNode.getInstance(); assertEquals(0, node.getTreeSize()); assertNull(node.getName()); assertNull(node.getLeft()); assertNull(node.getRight()); } /** * Removed unnecessary test method for {@link NullNode#walk()} as the method doesn't have an implementation. */ }
2,301
34.415385
140
java
java-design-patterns
java-design-patterns-master/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.nullobject; /** * Null Object implementation for binary tree node. * * <p>Implemented as Singleton, since all the NullNodes are the same. */ public final class NullNode implements Node { private static final NullNode instance = new NullNode(); private NullNode() { } public static NullNode getInstance() { return instance; } @Override public int getTreeSize() { return 0; } @Override public Node getLeft() { return null; } @Override public Node getRight() { return null; } @Override public String getName() { return null; } @Override public void walk() { // Do nothing } }
1,955
27.764706
140
java
java-design-patterns
java-design-patterns-master/null-object/src/main/java/com/iluwatar/nullobject/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.nullobject; /** * Null Object pattern replaces null values with neutral objects. Many times this simplifies * algorithms since no extra null checks are needed. * * <p>In this example we build a binary tree where the nodes are either normal or Null Objects. No * null values are used in the tree making the traversal easy. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var root = new NodeImpl("1", new NodeImpl("11", new NodeImpl("111", NullNode.getInstance(), NullNode.getInstance()), NullNode.getInstance() ), new NodeImpl("12", NullNode.getInstance(), new NodeImpl("122", NullNode.getInstance(), NullNode.getInstance()) ) ); root.walk(); } }
2,148
38.072727
140
java
java-design-patterns
java-design-patterns-master/null-object/src/main/java/com/iluwatar/nullobject/Node.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.nullobject; /** * Interface for binary tree node. */ public interface Node { String getName(); int getTreeSize(); Node getLeft(); Node getRight(); void walk(); }
1,485
34.380952
140
java
java-design-patterns
java-design-patterns-master/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.nullobject; import lombok.extern.slf4j.Slf4j; /** * Implementation for binary tree's normal nodes. */ @Slf4j public record NodeImpl(String name, Node left, Node right) implements Node { @Override public Node getLeft() { return left; } @Override public Node getRight() { return right; } @Override public String getName() { return name; } @Override public int getTreeSize() { return 1 + left.getTreeSize() + right.getTreeSize(); } @Override public void walk() { LOGGER.info(name); if (left.getTreeSize() > 0) { left.walk(); } if (right.getTreeSize() > 0) { right.walk(); } } }
1,965
29.71875
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests {@link Hotel} */ class HotelTest { private static final String H2_DB_URL = "jdbc:h2:~/test"; private Hotel hotel; private HotelDaoImpl dao; @BeforeEach void setUp() throws Exception { final var dataSource = createDataSource(); deleteSchema(dataSource); createSchema(dataSource); dao = new HotelDaoImpl(dataSource); addRooms(dao); hotel = new Hotel(dao); } @Test void bookingRoomShouldChangeBookedStatusToTrue() throws Exception { hotel.bookRoom(1); assertTrue(dao.getById(1).get().isBooked()); } @Test() void bookingRoomWithInvalidIdShouldRaiseException() { assertThrows(Exception.class, () -> { hotel.bookRoom(getNonExistingRoomId()); }); } @Test() void bookingRoomAgainShouldRaiseException() { assertThrows(Exception.class, () -> { hotel.bookRoom(1); hotel.bookRoom(1); }); } @Test void NotBookingRoomShouldNotChangeBookedStatus() throws Exception { assertFalse(dao.getById(1).get().isBooked()); } @Test void cancelRoomBookingShouldChangeBookedStatus() throws Exception { hotel.bookRoom(1); assertTrue(dao.getById(1).get().isBooked()); hotel.cancelRoomBooking(1); assertFalse(dao.getById(1).get().isBooked()); } @Test void cancelRoomBookingWithInvalidIdShouldRaiseException() { assertThrows(Exception.class, () -> { hotel.cancelRoomBooking(getNonExistingRoomId()); }); } @Test void cancelRoomBookingForUnbookedRoomShouldRaiseException() { assertThrows(Exception.class, () -> { hotel.cancelRoomBooking(1); }); } private static void deleteSchema(DataSource dataSource) throws java.sql.SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws Exception { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL); } catch (Exception e) { throw new Exception(e.getMessage(), e); } } public static DataSource createDataSource() { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setUrl(H2_DB_URL); return dataSource; } private static void addRooms(HotelDaoImpl hotelDao) throws Exception { for (var room : generateSampleRooms()) { hotelDao.add(room); } } public static List<Room> generateSampleRooms() { final var room1 = new Room(1, "Single", 50, false); final var room2 = new Room(2, "Double", 80, false); final var room3 = new Room(3, "Queen", 120, false); final var room4 = new Room(4, "King", 150, false); final var room5 = new Room(5, "Single", 50, false); final var room6 = new Room(6, "Double", 80, false); return List.of(room1, room2, room3, room4, room5, room6); } /** * An arbitrary number which does not correspond to an active Room id. * * @return an int of a room id which doesn't exist */ private int getNonExistingRoomId() { return 999; } }
4,855
30.532468
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** * Tests {@link HotelDaoImpl}. */ class HotelDaoImplTest { private static final String DB_URL = "jdbc:h2:~/test"; private HotelDaoImpl dao; private Room existingRoom = new Room(1, "Single", 50, false); /** * Creates rooms schema. * * @throws SQLException if there is any error while creating schema. */ @BeforeEach void createSchema() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL); statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL); } } /** * Represents the scenario where DB connectivity is present. */ @Nested class ConnectionSuccess { /** * Setup for connection success scenario. * * @throws Exception if any error occurs. */ @BeforeEach void setUp() throws Exception { var dataSource = new JdbcDataSource(); dataSource.setURL(DB_URL); dao = new HotelDaoImpl(dataSource); var result = dao.add(existingRoom); Assertions.assertTrue(result); } /** * Represents the scenario when DAO operations are being performed on a non existing room. */ @Nested class NonExistingRoom { @Test void addingShouldResultInSuccess() throws Exception { try (var allRooms = dao.getAll()) { assumeTrue(allRooms.count() == 1); } final var nonExistingRoom = new Room(2, "Double", 80, false); var result = dao.add(nonExistingRoom); Assertions.assertTrue(result); assertRoomCountIs(2); assertEquals(nonExistingRoom, dao.getById(nonExistingRoom.getId()).get()); } @Test void deletionShouldBeFailureAndNotAffectExistingRooms() throws Exception { final var nonExistingRoom = new Room(2, "Double", 80, false); var result = dao.delete(nonExistingRoom); Assertions.assertFalse(result); assertRoomCountIs(1); } @Test void updationShouldBeFailureAndNotAffectExistingRooms() throws Exception { final var nonExistingId = getNonExistingRoomId(); final var newRoomType = "Double"; final var newPrice = 80; final var room = new Room(nonExistingId, newRoomType, newPrice, false); var result = dao.update(room); Assertions.assertFalse(result); assertFalse(dao.getById(nonExistingId).isPresent()); } @Test void retrieveShouldReturnNoRoom() throws Exception { assertFalse(dao.getById(getNonExistingRoomId()).isPresent()); } } /** * Represents a scenario where DAO operations are being performed on an already existing * room. */ @Nested class ExistingRoom { @Test void addingShouldResultInFailureAndNotAffectExistingRooms() throws Exception { var existingRoom = new Room(1, "Single", 50, false); var result = dao.add(existingRoom); Assertions.assertFalse(result); assertRoomCountIs(1); assertEquals(existingRoom, dao.getById(existingRoom.getId()).get()); } @Test void deletionShouldBeSuccessAndRoomShouldBeNonAccessible() throws Exception { var result = dao.delete(existingRoom); Assertions.assertTrue(result); assertRoomCountIs(0); assertFalse(dao.getById(existingRoom.getId()).isPresent()); } @Test void updationShouldBeSuccessAndAccessingTheSameRoomShouldReturnUpdatedInformation() throws Exception { final var newRoomType = "Double"; final var newPrice = 80; final var newBookingStatus = false; final var Room = new Room(existingRoom.getId(), newRoomType, newPrice, newBookingStatus); var result = dao.update(Room); Assertions.assertTrue(result); final var room = dao.getById(existingRoom.getId()).get(); assertEquals(newRoomType, room.getRoomType()); assertEquals(newPrice, room.getPrice()); assertEquals(newBookingStatus, room.isBooked()); } } } /** * Represents a scenario where DB connectivity is not present due to network issue, or DB service * unavailable. */ @Nested class ConnectivityIssue { private static final String EXCEPTION_CAUSE = "Connection not available"; /** * setup a connection failure scenario. * * @throws SQLException if any error occurs. */ @BeforeEach void setUp() throws SQLException { dao = new HotelDaoImpl(mockedDatasource()); } private DataSource mockedDatasource() throws SQLException { var mockedDataSource = mock(DataSource.class); var mockedConnection = mock(Connection.class); var exception = new SQLException(EXCEPTION_CAUSE); doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString()); doReturn(mockedConnection).when(mockedDataSource).getConnection(); return mockedDataSource; } @Test void addingARoomFailsWithExceptionAsFeedbackToClient() { assertThrows(Exception.class, () -> { dao.add(new Room(2, "Double", 80, false)); }); } @Test void deletingARoomFailsWithExceptionAsFeedbackToTheClient() { assertThrows(Exception.class, () -> { dao.delete(existingRoom); }); } @Test void updatingARoomFailsWithFeedbackToTheClient() { final var newRoomType = "Double"; final var newPrice = 80; final var newBookingStatus = false; assertThrows(Exception.class, () -> { dao.update(new Room(existingRoom.getId(), newRoomType, newPrice, newBookingStatus)); }); } @Test void retrievingARoomByIdFailsWithExceptionAsFeedbackToClient() { assertThrows(Exception.class, () -> { dao.getById(existingRoom.getId()); }); } @Test void retrievingAllRoomsFailsWithExceptionAsFeedbackToClient() { assertThrows(Exception.class, () -> { dao.getAll(); }); } } /** * Delete room schema for fresh setup per test. * * @throws SQLException if any error occurs. */ @AfterEach void deleteSchema() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL); } } private void assertRoomCountIs(int count) throws Exception { try (var allRooms = dao.getAll()) { assertEquals(count, allRooms.count()); } } /** * An arbitrary number which does not correspond to an active Room id. * * @return an int of a room id which doesn't exist */ private int getNonExistingRoomId() { return 999; } }
8,844
30.816547
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/test/java/com/iluwatar/transactionscript/RoomTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests {@link Room}. */ class RoomTest { private Room room; private static final int ID = 1; private static final String ROOMTYPE = "Single"; private static final int PRICE = 50; private static final boolean BOOKED = false; @BeforeEach void setUp() { room = new Room(ID, ROOMTYPE, PRICE, BOOKED); } @Test void getAndSetId() { final var newId = 2; room.setId(newId); assertEquals(newId, room.getId()); } @Test void getAndSetRoomType() { final var newRoomType = "Double"; room.setRoomType(newRoomType); assertEquals(newRoomType, room.getRoomType()); } @Test void getAndSetLastName() { final var newPrice = 60; room.setPrice(newPrice); assertEquals(newPrice, room.getPrice()); } @Test void notEqualWithDifferentId() { final var newId = 2; final var otherRoom = new Room(newId, ROOMTYPE, PRICE, BOOKED); assertNotEquals(room, otherRoom); assertNotEquals(room.hashCode(), otherRoom.hashCode()); } @Test void equalsWithSameObjectValues() { final var otherRoom = new Room(ID, ROOMTYPE, PRICE, BOOKED); assertEquals(room, otherRoom); assertEquals(room.hashCode(), otherRoom.hashCode()); } @Test void equalsWithSameObjects() { assertEquals(room, room); assertEquals(room.hashCode(), room.hashCode()); } @Test void testToString() { assertEquals(String.format("Room(id=%s, roomType=%s, price=%s, booked=%s)", room.getId(), room.getRoomType(), room.getPrice(), room.isBooked()), room.toString()); } }
3,079
30.752577
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/test/java/com/iluwatar/transactionscript/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that Transaction script example runs without errors. */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,627
38.707317
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/main/java/com/iluwatar/transactionscript/Room.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * A room POJO that represents the data that will be read from the data source. */ @Setter @Getter @ToString @EqualsAndHashCode @AllArgsConstructor public class Room { private int id; private String roomType; private int price; private boolean booked; }
1,730
34.326531
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; import java.util.List; import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Transaction Script (TS) is one of the simplest domain logic pattern. * It needs less work to implement than other domain logic patterns and therefore * it’s perfect fit for smaller applications that don't need big architecture behind them. * * <p>In this example we will use the TS pattern to implement booking and cancellation * methods for a Hotel management App. The main method will initialise an instance of * {@link Hotel} and add rooms to it. After that it will book and cancel a couple of rooms * and that will be printed by the logger.</p> * * <p>The thing we have to note here is that all the operations related to booking or cancelling * a room like checking the database if the room exists, checking the booking status or the * room, calculating refund price are all clubbed inside a single transaction script method.</p> */ public class App { private static final String H2_DB_URL = "jdbc:h2:~/test"; private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Program entry point. * Initialises an instance of Hotel and adds rooms to it. * Carries out booking and cancel booking transactions. * @param args command line arguments * @throws Exception if any error occurs */ public static void main(String[] args) throws Exception { final var dataSource = createDataSource(); deleteSchema(dataSource); createSchema(dataSource); final var dao = new HotelDaoImpl(dataSource); // Add rooms addRooms(dao); // Print room booking status getRoomStatus(dao); var hotel = new Hotel(dao); // Book rooms hotel.bookRoom(1); hotel.bookRoom(2); hotel.bookRoom(3); hotel.bookRoom(4); hotel.bookRoom(5); hotel.bookRoom(6); // Cancel booking for a few rooms hotel.cancelRoomBooking(1); hotel.cancelRoomBooking(3); hotel.cancelRoomBooking(5); getRoomStatus(dao); deleteSchema(dataSource); } private static void getRoomStatus(HotelDaoImpl dao) throws Exception { try (var customerStream = dao.getAll()) { customerStream.forEach((customer) -> LOGGER.info(customer.toString())); } } private static void deleteSchema(DataSource dataSource) throws java.sql.SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws Exception { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL); } catch (Exception e) { throw new Exception(e.getMessage(), e); } } /** * Get database. * * @return h2 datasource */ private static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setUrl(H2_DB_URL); return dataSource; } private static void addRooms(HotelDaoImpl hotelDao) throws Exception { for (var room : generateSampleRooms()) { hotelDao.add(room); } } /** * Generate rooms. * * @return list of rooms */ private static List<Room> generateSampleRooms() { final var room1 = new Room(1, "Single", 50, false); final var room2 = new Room(2, "Double", 80, false); final var room3 = new Room(3, "Queen", 120, false); final var room4 = new Room(4, "King", 150, false); final var room5 = new Room(5, "Single", 50, false); final var room6 = new Room(6, "Double", 80, false); return List.of(room1, room2, room3, room4, room5, room6); } }
5,122
33.85034
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/main/java/com/iluwatar/transactionscript/Hotel.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; import lombok.extern.slf4j.Slf4j; /** * Hotel class to implement TS pattern. */ @Slf4j public class Hotel { private final HotelDaoImpl hotelDao; public Hotel(HotelDaoImpl hotelDao) { this.hotelDao = hotelDao; } /** * Book a room. * * @param roomNumber room to book * @throws Exception if any error */ public void bookRoom(int roomNumber) throws Exception { var room = hotelDao.getById(roomNumber); if (room.isEmpty()) { throw new Exception("Room number: " + roomNumber + " does not exist"); } else { if (room.get().isBooked()) { throw new Exception("Room already booked!"); } else { var updateRoomBooking = room.get(); updateRoomBooking.setBooked(true); hotelDao.update(updateRoomBooking); } } } /** * Cancel a room booking. * * @param roomNumber room to cancel booking * @throws Exception if any error */ public void cancelRoomBooking(int roomNumber) throws Exception { var room = hotelDao.getById(roomNumber); if (room.isEmpty()) { throw new Exception("Room number: " + roomNumber + " does not exist"); } else { if (room.get().isBooked()) { var updateRoomBooking = room.get(); updateRoomBooking.setBooked(false); int refundAmount = updateRoomBooking.getPrice(); hotelDao.update(updateRoomBooking); LOGGER.info("Booking cancelled for room number: " + roomNumber); LOGGER.info(refundAmount + " is refunded"); } else { throw new Exception("No booking for the room exists"); } } } }
2,938
31.296703
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDaoImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Optional; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; /** * Implementation of database operations for Hotel class. */ @Slf4j public class HotelDaoImpl implements HotelDao { private final DataSource dataSource; public HotelDaoImpl(DataSource dataSource) { this.dataSource = dataSource; } @Override public Stream<Room> getAll() throws Exception { try { var connection = getConnection(); var statement = connection.prepareStatement("SELECT * FROM ROOMS"); // NOSONAR var resultSet = statement.executeQuery(); // NOSONAR return StreamSupport.stream(new Spliterators.AbstractSpliterator<Room>(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public boolean tryAdvance(Consumer<? super Room> action) { try { if (!resultSet.next()) { return false; } action.accept(createRoom(resultSet)); return true; } catch (Exception e) { throw new RuntimeException(e); // NOSONAR } } }, false).onClose(() -> { try { mutedClose(connection, statement, resultSet); } catch (Exception e) { LOGGER.error(e.getMessage()); } }); } catch (Exception e) { throw new Exception(e.getMessage(), e); } } @Override public Optional<Room> getById(int id) throws Exception { ResultSet resultSet = null; try (var connection = getConnection(); var statement = connection.prepareStatement("SELECT * FROM ROOMS WHERE ID = ?")) { statement.setInt(1, id); resultSet = statement.executeQuery(); if (resultSet.next()) { return Optional.of(createRoom(resultSet)); } else { return Optional.empty(); } } catch (Exception e) { throw new Exception(e.getMessage(), e); } finally { if (resultSet != null) { resultSet.close(); } } } @Override public Boolean add(Room room) throws Exception { if (getById(room.getId()).isPresent()) { return false; } try (var connection = getConnection(); var statement = connection.prepareStatement("INSERT INTO ROOMS VALUES (?,?,?,?)")) { statement.setInt(1, room.getId()); statement.setString(2, room.getRoomType()); statement.setInt(3, room.getPrice()); statement.setBoolean(4, room.isBooked()); statement.execute(); return true; } catch (Exception e) { throw new Exception(e.getMessage(), e); } } @Override public Boolean update(Room room) throws Exception { try (var connection = getConnection(); var statement = connection .prepareStatement("UPDATE ROOMS SET ROOM_TYPE = ?, PRICE = ?, BOOKED = ?" + " WHERE ID = ?")) { statement.setString(1, room.getRoomType()); statement.setInt(2, room.getPrice()); statement.setBoolean(3, room.isBooked()); statement.setInt(4, room.getId()); return statement.executeUpdate() > 0; } catch (Exception e) { throw new Exception(e.getMessage(), e); } } @Override public Boolean delete(Room room) throws Exception { try (var connection = getConnection(); var statement = connection.prepareStatement("DELETE FROM ROOMS WHERE ID = ?")) { statement.setInt(1, room.getId()); return statement.executeUpdate() > 0; } catch (Exception e) { throw new Exception(e.getMessage(), e); } } private Connection getConnection() throws Exception { return dataSource.getConnection(); } private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) throws Exception { try { resultSet.close(); statement.close(); connection.close(); } catch (Exception e) { throw new Exception(e.getMessage(), e); } } private Room createRoom(ResultSet resultSet) throws Exception { return new Room(resultSet.getInt("ID"), resultSet.getString("ROOM_TYPE"), resultSet.getInt("PRICE"), resultSet.getBoolean("BOOKED")); } }
5,756
31.710227
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; /** * Customer Schema SQL Class. */ public final class RoomSchemaSql { public static final String CREATE_SCHEMA_SQL = "CREATE TABLE ROOMS (ID NUMBER, ROOM_TYPE VARCHAR(100), PRICE INT, BOOKED VARCHAR(100))"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE ROOMS IF EXISTS"; private RoomSchemaSql() { } }
1,659
40.5
140
java
java-design-patterns
java-design-patterns-master/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDao.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.transactionscript; import java.util.Optional; import java.util.stream.Stream; /** * DAO interface for hotel transactions. */ public interface HotelDao { Stream<Room> getAll() throws Exception; Optional<Room> getById(int id) throws Exception; Boolean add(Room room) throws Exception; Boolean update(Room room) throws Exception; Boolean delete(Room room) throws Exception; }
1,697
36.733333
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Message test case. */ class MessageTest { @Test void testGetType() { var message = new Message(MessageType.HEARTBEAT, ""); assertEquals(MessageType.HEARTBEAT, message.getType()); } @Test void testGetContent() { var content = "test"; var message = new Message(MessageType.HEARTBEAT, content); assertEquals(content, message.getContent()); } }
1,804
35.1
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.bully; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.fail; import com.iluwatar.leaderelection.AbstractInstance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.Queue; import org.junit.jupiter.api.Test; /** * BullyInstance unit test. */ class BullyinstanceTest { @Test void testOnMessage() { try { final var bullyInstance = new BullyInstance(null, 1, 1); var bullyMessage = new Message(MessageType.HEARTBEAT, ""); bullyInstance.onMessage(bullyMessage); var instanceClass = AbstractInstance.class; var messageQueueField = instanceClass.getDeclaredField("messageQueue"); messageQueueField.setAccessible(true); assertEquals(bullyMessage, ((Queue<Message>) messageQueueField.get(bullyInstance)).poll()); } catch (IllegalAccessException | NoSuchFieldException e) { fail("fail to access messasge queue."); } } @Test void testIsAlive() { try { final var bullyInstance = new BullyInstance(null, 1, 1); var instanceClass = AbstractInstance.class; var aliveField = instanceClass.getDeclaredField("alive"); aliveField.setAccessible(true); aliveField.set(bullyInstance, false); assertFalse(bullyInstance.isAlive()); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Fail to access field alive."); } } @Test void testSetAlive() { final var bullyInstance = new BullyInstance(null, 1, 1); bullyInstance.setAlive(false); assertFalse(bullyInstance.isAlive()); } }
3,019
36.75
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.bully; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * BullyApp unit test. */ class BullyAppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> BullyApp.main(new String[]{})); } }
1,613
37.428571
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.bully; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.iluwatar.leaderelection.AbstractInstance; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.Map; import java.util.Queue; import org.junit.jupiter.api.Test; /** * BullyMessageManager unit test. */ class BullyMessageManagerTest { @Test void testSendHeartbeatMessage() { var instance1 = new BullyInstance(null, 1, 1); Map<Integer, Instance> instanceMap = Map.of(1, instance1); var messageManager = new BullyMessageManager(instanceMap); assertTrue(messageManager.sendHeartbeatMessage(1)); } @Test void testSendElectionMessageNotAccepted() { try { var instance1 = new BullyInstance(null, 1, 1); var instance2 = new BullyInstance(null, 1, 2); var instance3 = new BullyInstance(null, 1, 3); var instance4 = new BullyInstance(null, 1, 4); Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); instance1.setAlive(false); var messageManager = new BullyMessageManager(instanceMap); var result = messageManager.sendElectionMessage(3, "3"); var instanceClass = AbstractInstance.class; var messageQueueField = instanceClass.getDeclaredField("messageQueue"); messageQueueField.setAccessible(true); var message2 = ((Queue<Message>) messageQueueField.get(instance2)).poll(); var instance4QueueSize = ((Queue<Message>) messageQueueField.get(instance4)).size(); var expectedMessage = new Message(MessageType.ELECTION_INVOKE, ""); assertEquals(message2, expectedMessage); assertEquals(instance4QueueSize, 0); assertEquals(result, false); } catch (IllegalAccessException | NoSuchFieldException e) { fail("Error to access private field."); } } @Test void testElectionMessageAccepted() { var instance1 = new BullyInstance(null, 1, 1); var instance2 = new BullyInstance(null, 1, 2); var instance3 = new BullyInstance(null, 1, 3); var instance4 = new BullyInstance(null, 1, 4); Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); instance1.setAlive(false); var messageManager = new BullyMessageManager(instanceMap); var result = messageManager.sendElectionMessage(2, "2"); assertEquals(result, true); } @Test void testSendLeaderMessage() { try { var instance1 = new BullyInstance(null, 1, 1); var instance2 = new BullyInstance(null, 1, 2); var instance3 = new BullyInstance(null, 1, 3); var instance4 = new BullyInstance(null, 1, 4); Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); instance1.setAlive(false); var messageManager = new BullyMessageManager(instanceMap); messageManager.sendLeaderMessage(2, 2); var instanceClass = AbstractInstance.class; var messageQueueField = instanceClass.getDeclaredField("messageQueue"); messageQueueField.setAccessible(true); var message3 = ((Queue<Message>) messageQueueField.get(instance3)).poll(); var message4 = ((Queue<Message>) messageQueueField.get(instance4)).poll(); var expectedMessage = new Message(MessageType.LEADER, "2"); assertEquals(message3, expectedMessage); assertEquals(message4, expectedMessage); } catch (IllegalAccessException | NoSuchFieldException e) { fail("Error to access private field."); } } @Test void testSendHeartbeatInvokeMessage() { try { var instance1 = new BullyInstance(null, 1, 1); var instance2 = new BullyInstance(null, 1, 2); var instance3 = new BullyInstance(null, 1, 3); Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); var messageManager = new BullyMessageManager(instanceMap); messageManager.sendHeartbeatInvokeMessage(2); var message = new Message(MessageType.HEARTBEAT_INVOKE, ""); var instanceClass = AbstractInstance.class; var messageQueueField = instanceClass.getDeclaredField("messageQueue"); messageQueueField.setAccessible(true); var messageSent = ((Queue<Message>) messageQueueField.get(instance3)).poll(); assertEquals(messageSent.getType(), message.getType()); assertEquals(messageSent.getContent(), message.getContent()); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Error to access private field."); } } }
6,025
42.985401
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.ring; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.fail; import com.iluwatar.leaderelection.AbstractInstance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.Queue; import org.junit.jupiter.api.Test; /** * RingInstance unit test. */ class RingInstanceTest { @Test void testOnMessage() { try { final var ringInstance = new RingInstance(null, 1, 1); var ringMessage = new Message(MessageType.HEARTBEAT, ""); ringInstance.onMessage(ringMessage); var ringInstanceClass = AbstractInstance.class; var messageQueueField = ringInstanceClass.getDeclaredField("messageQueue"); messageQueueField.setAccessible(true); assertEquals(ringMessage, ((Queue<Message>) messageQueueField.get(ringInstance)).poll()); } catch (IllegalAccessException | NoSuchFieldException e) { fail("fail to access messasge queue."); } } @Test void testIsAlive() { try { final var ringInstance = new RingInstance(null, 1, 1); var ringInstanceClass = AbstractInstance.class; var aliveField = ringInstanceClass.getDeclaredField("alive"); aliveField.setAccessible(true); aliveField.set(ringInstance, false); assertFalse(ringInstance.isAlive()); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Fail to access field alive."); } } @Test void testSetAlive() { final var ringInstance = new RingInstance(null, 1, 1); ringInstance.setAlive(false); assertFalse(ringInstance.isAlive()); } }
3,015
37.666667
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.ring; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * RingApp unit test. */ class RingAppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> RingApp.main(new String[]{})); } }
1,609
37.333333
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.ring; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.iluwatar.leaderelection.AbstractInstance; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.Map; import java.util.Queue; import org.junit.jupiter.api.Test; /** * RingMessageManager unit test. */ class RingMessageManagerTest { @Test void testSendHeartbeatMessage() { var instance1 = new RingInstance(null, 1, 1); Map<Integer, Instance> instanceMap = Map.of(1, instance1); var messageManager = new RingMessageManager(instanceMap); assertTrue(messageManager.sendHeartbeatMessage(1)); } @Test void testSendElectionMessage() { try { var instance1 = new RingInstance(null, 1, 1); var instance2 = new RingInstance(null, 1, 2); var instance3 = new RingInstance(null, 1, 3); Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); var messageManager = new RingMessageManager(instanceMap); var messageContent = "2"; messageManager.sendElectionMessage(2, messageContent); var ringMessage = new Message(MessageType.ELECTION, messageContent); var instanceClass = AbstractInstance.class; var messageQueueField = instanceClass.getDeclaredField("messageQueue"); messageQueueField.setAccessible(true); var ringMessageSent = ((Queue<Message>) messageQueueField.get(instance3)).poll(); assertEquals(ringMessageSent.getType(), ringMessage.getType()); assertEquals(ringMessageSent.getContent(), ringMessage.getContent()); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Error to access private field."); } } @Test void testSendLeaderMessage() { try { var instance1 = new RingInstance(null, 1, 1); var instance2 = new RingInstance(null, 1, 2); var instance3 = new RingInstance(null, 1, 3); Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); var messageManager = new RingMessageManager(instanceMap); var messageContent = "3"; messageManager.sendLeaderMessage(2, 3); var ringMessage = new Message(MessageType.LEADER, messageContent); var instanceClass = AbstractInstance.class; var messageQueueField = instanceClass.getDeclaredField("messageQueue"); messageQueueField.setAccessible(true); var ringMessageSent = ((Queue<Message>) messageQueueField.get(instance3)).poll(); assertEquals(ringMessageSent, ringMessage); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Error to access private field."); } } @Test void testSendHeartbeatInvokeMessage() { try { var instance1 = new RingInstance(null, 1, 1); var instance2 = new RingInstance(null, 1, 2); var instance3 = new RingInstance(null, 1, 3); Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); var messageManager = new RingMessageManager(instanceMap); messageManager.sendHeartbeatInvokeMessage(2); var ringMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); var instanceClass = AbstractInstance.class; var messageQueueField = instanceClass.getDeclaredField("messageQueue"); messageQueueField.setAccessible(true); var ringMessageSent = ((Queue<Message>) messageQueueField.get(instance3)).poll(); assertEquals(ringMessageSent.getType(), ringMessage.getType()); assertEquals(ringMessageSent.getContent(), ringMessage.getContent()); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Error to access private field."); } } }
5,161
43.119658
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Message used to transport data between instances. */ @Setter @Getter @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class Message { private MessageType type; private String content; }
1,683
34.829787
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection; /** * Instance interface. */ public interface Instance { /** * Check if the instance is alive or not. * * @return {@code true} if the instance is alive. */ boolean isAlive(); /** * Set the health status of the certain instance. * * @param alive {@code true} for alive. */ void setAlive(boolean alive); /** * Consume messages from other instances. * * @param message Message sent by other instances */ void onMessage(Message message); }
1,812
32.574074
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import lombok.extern.slf4j.Slf4j; /** * Abstract class of all the instance implementation classes. */ @Slf4j public abstract class AbstractInstance implements Instance, Runnable { protected static final int HEARTBEAT_INTERVAL = 5000; private static final String INSTANCE = "Instance "; protected MessageManager messageManager; protected Queue<Message> messageQueue; protected final int localId; protected int leaderId; protected boolean alive; /** * Constructor of BullyInstance. */ public AbstractInstance(MessageManager messageManager, int localId, int leaderId) { this.messageManager = messageManager; this.messageQueue = new ConcurrentLinkedQueue<>(); this.localId = localId; this.leaderId = leaderId; this.alive = true; } /** * The instance will execute the message in its message queue periodically once it is alive. */ @Override @SuppressWarnings("squid:S2189") public void run() { while (true) { if (!this.messageQueue.isEmpty()) { this.processMessage(this.messageQueue.remove()); } } } /** * Once messages are sent to the certain instance, it will firstly be added to the queue and wait * to be executed. * * @param message Message sent by other instances */ @Override public void onMessage(Message message) { messageQueue.offer(message); } /** * Check if the instance is alive or not. * * @return {@code true} if the instance is alive. */ @Override public boolean isAlive() { return alive; } /** * Set the health status of the certain instance. * * @param alive {@code true} for alive. */ @Override public void setAlive(boolean alive) { this.alive = alive; } /** * Process the message according to its type. * * @param message Message polled from queue. */ private void processMessage(Message message) { switch (message.getType()) { case ELECTION -> { LOGGER.info(INSTANCE + localId + " - Election Message handling..."); handleElectionMessage(message); } case LEADER -> { LOGGER.info(INSTANCE + localId + " - Leader Message handling..."); handleLeaderMessage(message); } case HEARTBEAT -> { LOGGER.info(INSTANCE + localId + " - Heartbeat Message handling..."); handleHeartbeatMessage(message); } case ELECTION_INVOKE -> { LOGGER.info(INSTANCE + localId + " - Election Invoke Message handling..."); handleElectionInvokeMessage(); } case LEADER_INVOKE -> { LOGGER.info(INSTANCE + localId + " - Leader Invoke Message handling..."); handleLeaderInvokeMessage(); } case HEARTBEAT_INVOKE -> { LOGGER.info(INSTANCE + localId + " - Heartbeat Invoke Message handling..."); handleHeartbeatInvokeMessage(); } default -> { } } } /** * Abstract methods to handle different types of message. These methods need to be implemented in * concrete instance class to implement corresponding leader-selection pattern. */ protected abstract void handleElectionMessage(Message message); protected abstract void handleElectionInvokeMessage(); protected abstract void handleLeaderMessage(Message message); protected abstract void handleLeaderInvokeMessage(); protected abstract void handleHeartbeatMessage(Message message); protected abstract void handleHeartbeatInvokeMessage(); }
4,876
30.668831
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection; /** * Message Type enum. */ public enum MessageType { /** * Start the election. The content of the message stores ID(s) of the candidate instance(s). */ ELECTION, /** * Nodify the new leader. The content of the message should be the leader ID. */ LEADER, /** * Check health of current leader instance. */ HEARTBEAT, /** * Inform target instance to start election. */ ELECTION_INVOKE, /** * Inform target instance to notify all the other instance that it is the new leader. */ LEADER_INVOKE, /** * Inform target instance to start heartbeat. */ HEARTBEAT_INVOKE }
1,954
29.546875
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection; import java.util.Map; /** * Abstract class of all the message manager classes. */ public abstract class AbstractMessageManager implements MessageManager { /** * Contain all the instances in the system. Key is its ID, and value is the instance itself. */ protected Map<Integer, Instance> instanceMap; /** * Construtor of AbstractMessageManager. */ public AbstractMessageManager(Map<Integer, Instance> instanceMap) { this.instanceMap = instanceMap; } /** * Find the next instance with smallest ID. * * @return The next instance. */ protected Instance findNextInstance(int currentId) { Instance result = null; var candidateList = instanceMap.keySet() .stream() .filter((i) -> i > currentId && instanceMap.get(i).isAlive()) .sorted() .toList(); if (candidateList.isEmpty()) { var index = instanceMap.keySet() .stream() .filter((i) -> instanceMap.get(i).isAlive()) .sorted() .toList() .get(0); result = instanceMap.get(index); } else { var index = candidateList.get(0); result = instanceMap.get(index); } return result; } }
2,522
33.094595
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection; /** * MessageManager interface. */ public interface MessageManager { /** * Send heartbeat message to leader instance to check whether the leader instance is alive. * * @param leaderId Instance ID of leader instance. * @return {@code true} if leader instance is alive, or {@code false} if not. */ boolean sendHeartbeatMessage(int leaderId); /** * Send election message to other instances. * * @param currentId Instance ID of which sends this message. * @param content Election message content. * @return {@code true} if the message is accepted by the target instances. */ boolean sendElectionMessage(int currentId, String content); /** * Send new leader notification message to other instances. * * @param currentId Instance ID of which sends this message. * @param leaderId Leader message content. * @return {@code true} if the message is accepted by the target instances. */ boolean sendLeaderMessage(int currentId, int leaderId); /** * Send heartbeat invoke message. This will invoke heartbeat task in the target instance. * * @param currentId Instance ID of which sends this message. */ void sendHeartbeatInvokeMessage(int currentId); }
2,551
37.666667
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.bully; import com.iluwatar.leaderelection.AbstractInstance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageManager; import lombok.extern.slf4j.Slf4j; /** * 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. */ @Slf4j public class BullyInstance extends AbstractInstance { private static final String INSTANCE = "Instance "; /** * Constructor of BullyInstance. */ public BullyInstance(MessageManager messageManager, int localId, int leaderId) { super(messageManager, localId, leaderId); } /** * Process the heartbeat invoke message. After receiving the message, the instance will send a * heartbeat to leader to check its health. If alive, it will inform the next instance to do the * heartbeat. If not, it will start the election process. */ @Override protected void handleHeartbeatInvokeMessage() { try { boolean isLeaderAlive = messageManager.sendHeartbeatMessage(leaderId); if (isLeaderAlive) { LOGGER.info(INSTANCE + localId + "- Leader is alive."); Thread.sleep(HEARTBEAT_INTERVAL); messageManager.sendHeartbeatInvokeMessage(localId); } else { LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election."); boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); if (electionResult) { LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification."); messageManager.sendLeaderMessage(localId, localId); } } } catch (InterruptedException e) { LOGGER.info(INSTANCE + localId + "- Interrupted."); } } /** * Process election invoke message. Send election message to all the instances with smaller ID. If * any one of them is alive, do nothing. If no instance alive, send leader message to all the * alive instance and restart heartbeat. */ @Override protected void handleElectionInvokeMessage() { if (!isLeader()) { LOGGER.info(INSTANCE + localId + "- Start election."); boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); if (electionResult) { LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification."); leaderId = localId; messageManager.sendLeaderMessage(localId, localId); messageManager.sendHeartbeatInvokeMessage(localId); } } } /** * Process leader message. Update local leader information. */ @Override protected void handleLeaderMessage(Message message) { leaderId = Integer.valueOf(message.getContent()); LOGGER.info(INSTANCE + localId + " - Leader update done."); } private boolean isLeader() { return localId == leaderId; } @Override protected void handleLeaderInvokeMessage() { // Not used in Bully Instance } @Override protected void handleHeartbeatMessage(Message message) { // Not used in Bully Instance } @Override protected void handleElectionMessage(Message message) { // Not used in Bully Instance } }
5,080
39.325397
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.bully; import com.iluwatar.leaderelection.AbstractMessageManager; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.List; import java.util.Map; /** * Implementation of BullyMessageManager. */ public class BullyMessageManager extends AbstractMessageManager { /** * Constructor of BullyMessageManager. */ public BullyMessageManager(Map<Integer, Instance> instanceMap) { super(instanceMap); } /** * Send heartbeat message to current leader instance to check the health. * * @param leaderId leaderID * @return {@code true} if the leader is alive. */ @Override public boolean sendHeartbeatMessage(int leaderId) { var leaderInstance = instanceMap.get(leaderId); var alive = leaderInstance.isAlive(); return alive; } /** * Send election message to all the instances with smaller ID. * * @param currentId Instance ID of which sends this message. * @param content Election message content. * @return {@code true} if no alive instance has smaller ID, so that the election is accepted. */ @Override public boolean sendElectionMessage(int currentId, String content) { var candidateList = findElectionCandidateInstanceList(currentId); if (candidateList.isEmpty()) { return true; } else { var electionMessage = new Message(MessageType.ELECTION_INVOKE, ""); candidateList.stream().forEach((i) -> instanceMap.get(i).onMessage(electionMessage)); return false; } } /** * Send leader message to all the instances to notify the new leader. * * @param currentId Instance ID of which sends this message. * @param leaderId Leader message content. * @return {@code true} if the message is accepted. */ @Override public boolean sendLeaderMessage(int currentId, int leaderId) { var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); instanceMap.keySet() .stream() .filter((i) -> i != currentId) .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage)); return false; } /** * Send heartbeat invoke message to the next instance. * * @param currentId Instance ID of which sends this message. */ @Override public void sendHeartbeatInvokeMessage(int currentId) { var nextInstance = this.findNextInstance(currentId); var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); nextInstance.onMessage(heartbeatInvokeMessage); } /** * Find all the alive instances with smaller ID than current instance. * * @param currentId ID of current instance. * @return ID list of all the candidate instance. */ private List<Integer> findElectionCandidateInstanceList(int currentId) { return instanceMap.keySet() .stream() .filter((i) -> i < currentId && instanceMap.get(i).isAlive()) .toList(); } }
4,296
34.512397
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.bully; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageManager; import com.iluwatar.leaderelection.MessageType; import java.util.HashMap; import java.util.Map; /** * Example of how to use bully leader election. Initially 5 instances is created in the clould * system, and the instance with ID 1 is set as leader. After the system is started stop the leader * instance, and the new leader will be elected. */ public class BullyApp { /** * Program entry point. */ public static void main(String[] args) { Map<Integer, Instance> instanceMap = new HashMap<>(); var messageManager = new BullyMessageManager(instanceMap); var instance1 = new BullyInstance(messageManager, 1, 1); var instance2 = new BullyInstance(messageManager, 2, 1); var instance3 = new BullyInstance(messageManager, 3, 1); var instance4 = new BullyInstance(messageManager, 4, 1); var instance5 = new BullyInstance(messageManager, 5, 1); instanceMap.put(1, instance1); instanceMap.put(2, instance2); instanceMap.put(3, instance3); instanceMap.put(4, instance4); instanceMap.put(5, instance5); instance4.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); final var thread1 = new Thread(instance1); final var thread2 = new Thread(instance2); final var thread3 = new Thread(instance3); final var thread4 = new Thread(instance4); final var thread5 = new Thread(instance5); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); instance1.setAlive(false); } }
2,980
37.217949
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.ring; import com.iluwatar.leaderelection.AbstractInstance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageManager; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; /** * 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. */ @Slf4j public class RingInstance extends AbstractInstance { private static final String INSTANCE = "Instance "; /** * Constructor of RingInstance. */ public RingInstance(MessageManager messageManager, int localId, int leaderId) { super(messageManager, localId, leaderId); } /** * Process the heartbeat invoke message. After receiving the message, the instance will send a * heartbeat to leader to check its health. If alive, it will inform the next instance to do the * heartbeat. If not, it will start the election process. */ @Override protected void handleHeartbeatInvokeMessage() { try { var isLeaderAlive = messageManager.sendHeartbeatMessage(this.leaderId); if (isLeaderAlive) { LOGGER.info(INSTANCE + localId + "- Leader is alive. Start next heartbeat in 5 second."); Thread.sleep(HEARTBEAT_INTERVAL); messageManager.sendHeartbeatInvokeMessage(this.localId); } else { LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election."); messageManager.sendElectionMessage(this.localId, String.valueOf(this.localId)); } } catch (InterruptedException e) { LOGGER.info(INSTANCE + localId + "- Interrupted."); } } /** * Process election message. If the local ID is contained in the ID list, the instance will select * the alive instance with smallest ID to be the new leader, and send the leader inform message. * If not, it will add its local ID to the list and send the message to the next instance in the * ring. */ @Override protected void handleElectionMessage(Message message) { var content = message.getContent(); LOGGER.info(INSTANCE + localId + " - Election Message: " + content); var candidateList = Arrays.stream(content.trim().split(",")) .map(Integer::valueOf) .sorted() .toList(); if (candidateList.contains(localId)) { var newLeaderId = candidateList.get(0); LOGGER.info(INSTANCE + localId + " - New leader should be " + newLeaderId + "."); messageManager.sendLeaderMessage(localId, newLeaderId); } else { content += "," + localId; messageManager.sendElectionMessage(localId, content); } } /** * Process leader Message. The instance will set the leader ID to be the new one and send the * message to the next instance until all the alive instance in the ring is informed. */ @Override protected void handleLeaderMessage(Message message) { var newLeaderId = Integer.valueOf(message.getContent()); if (this.leaderId != newLeaderId) { LOGGER.info(INSTANCE + localId + " - Update leaderID"); this.leaderId = newLeaderId; messageManager.sendLeaderMessage(localId, newLeaderId); } else { LOGGER.info(INSTANCE + localId + " - Leader update done. Start heartbeat."); messageManager.sendHeartbeatInvokeMessage(localId); } } /** * Not used in Ring instance. */ @Override protected void handleLeaderInvokeMessage() { // Not used in Ring instance. } @Override protected void handleHeartbeatMessage(Message message) { // Not used in Ring instance. } @Override protected void handleElectionInvokeMessage() { // Not used in Ring instance. } }
5,629
40.094891
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.ring; import com.iluwatar.leaderelection.AbstractMessageManager; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.Map; /** * Implementation of RingMessageManager. */ public class RingMessageManager extends AbstractMessageManager { /** * Constructor of RingMessageManager. */ public RingMessageManager(Map<Integer, Instance> instanceMap) { super(instanceMap); } /** * Send heartbeat message to current leader instance to check the health. * * @param leaderId leaderID * @return {@code true} if the leader is alive. */ @Override public boolean sendHeartbeatMessage(int leaderId) { var leaderInstance = instanceMap.get(leaderId); var alive = leaderInstance.isAlive(); return alive; } /** * Send election message to the next instance. * * @param currentId currentID * @param content list contains all the IDs of instances which have received this election * message. * @return {@code true} if the election message is accepted by the target instance. */ @Override public boolean sendElectionMessage(int currentId, String content) { var nextInstance = this.findNextInstance(currentId); var electionMessage = new Message(MessageType.ELECTION, content); nextInstance.onMessage(electionMessage); return true; } /** * Send leader message to the next instance. * * @param currentId Instance ID of which sends this message. * @param leaderId Leader message content. * @return {@code true} if the leader message is accepted by the target instance. */ @Override public boolean sendLeaderMessage(int currentId, int leaderId) { var nextInstance = this.findNextInstance(currentId); var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); nextInstance.onMessage(leaderMessage); return true; } /** * Send heartbeat invoke message to the next instance. * * @param currentId Instance ID of which sends this message. */ @Override public void sendHeartbeatInvokeMessage(int currentId) { var nextInstance = this.findNextInstance(currentId); var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); nextInstance.onMessage(heartbeatInvokeMessage); } }
3,693
35.215686
140
java
java-design-patterns
java-design-patterns-master/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderelection.ring; import com.iluwatar.leaderelection.Instance; import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageManager; import com.iluwatar.leaderelection.MessageType; import java.util.HashMap; import java.util.Map; /** * Example of how to use ring leader election. Initially 5 instances is created in the clould * system, and the instance with ID 1 is set as leader. After the system is started stop the leader * instance, and the new leader will be elected. */ public class RingApp { /** * Program entry point. */ public static void main(String[] args) { Map<Integer, Instance> instanceMap = new HashMap<>(); var messageManager = new RingMessageManager(instanceMap); var instance1 = new RingInstance(messageManager, 1, 1); var instance2 = new RingInstance(messageManager, 2, 1); var instance3 = new RingInstance(messageManager, 3, 1); var instance4 = new RingInstance(messageManager, 4, 1); var instance5 = new RingInstance(messageManager, 5, 1); instanceMap.put(1, instance1); instanceMap.put(2, instance2); instanceMap.put(3, instance3); instanceMap.put(4, instance4); instanceMap.put(5, instance5); instance2.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); final var thread1 = new Thread(instance1); final var thread2 = new Thread(instance2); final var thread3 = new Thread(instance3); final var thread4 = new Thread(instance4); final var thread5 = new Thread(instance5); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); instance1.setAlive(false); } }
2,971
37.102564
140
java
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/OrcsTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.observer; import java.util.Collection; import java.util.List; /** * Date: 12/27/15 - 12:07 PM * * @author Jeroen Meulemeester */ class OrcsTest extends WeatherObserverTest<Orcs> { @Override public Collection<Object[]> dataProvider() { return List.of( new Object[]{WeatherType.SUNNY, "The orcs are facing Sunny weather now"}, new Object[]{WeatherType.RAINY, "The orcs are facing Rainy weather now"}, new Object[]{WeatherType.WINDY, "The orcs are facing Windy weather now"}, new Object[]{WeatherType.COLD, "The orcs are facing Cold weather now"}); } /** * Create a new test with the given weather and expected response */ public OrcsTest() { super(Orcs::new); } }
2,034
36.685185
140
java
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.observer; import java.util.Collection; import java.util.List; /** * Date: 12/27/15 - 12:07 PM * * @author Jeroen Meulemeester */ class HobbitsTest extends WeatherObserverTest<Hobbits> { @Override public Collection<Object[]> dataProvider() { return List.of( new Object[]{WeatherType.SUNNY, "The hobbits are facing Sunny weather now"}, new Object[]{WeatherType.RAINY, "The hobbits are facing Rainy weather now"}, new Object[]{WeatherType.WINDY, "The hobbits are facing Windy weather now"}, new Object[]{WeatherType.COLD, "The hobbits are facing Cold weather now"}); } /** * Create a new test with the given weather and expected response */ public HobbitsTest() { super(Hobbits::new); } }
2,058
37.12963
140
java
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.observer; import com.iluwatar.observer.utils.InMemoryAppender; import java.util.Collection; import java.util.function.Supplier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/27/15 - 11:44 AM * Weather Observer Tests * @param <O> Type of WeatherObserver * @author Jeroen Meulemeester */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class WeatherObserverTest<O extends WeatherObserver> { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } /** * The observer instance factory */ private final Supplier<O> factory; /** * Create a new test instance using the given parameters * * @param factory The factory, used to create an instance of the tested observer */ WeatherObserverTest(final Supplier<O> factory) { this.factory = factory; } public abstract Collection<Object[]> dataProvider(); /** * Verify if the weather has the expected influence on the observer */ @ParameterizedTest @MethodSource("dataProvider") void testObserver(WeatherType weather, String response) { final var observer = this.factory.get(); assertEquals(0, appender.getLogSize()); observer.update(weather); assertEquals(response, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } }
2,997
31.586957
140
java
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.observer; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * * Application test * */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,593
36.069767
140
java
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/WeatherTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.observer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import com.iluwatar.observer.utils.InMemoryAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Date: 12/27/15 - 11:08 AM * * @author Jeroen Meulemeester */ class WeatherTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(Weather.class); } @AfterEach void tearDown() { appender.stop(); } /** * Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the * observer again and verify that there are no more notifications. */ @Test void testAddRemoveObserver() { final var observer = mock(WeatherObserver.class); final var weather = new Weather(); weather.addObserver(observer); verifyNoMoreInteractions(observer); weather.timePasses(); assertEquals("The weather changed to rainy.", appender.getLastMessage()); verify(observer).update(WeatherType.RAINY); weather.removeObserver(observer); weather.timePasses(); assertEquals("The weather changed to windy.", appender.getLastMessage()); verifyNoMoreInteractions(observer); assertEquals(2, appender.getLogSize()); } /** * Verify if the weather passes in the order of the {@link WeatherType}s */ @Test void testTimePasses() { final var observer = mock(WeatherObserver.class); final var weather = new Weather(); weather.addObserver(observer); final var inOrder = inOrder(observer); final var weatherTypes = WeatherType.values(); for (var i = 1; i < 20; i++) { weather.timePasses(); inOrder.verify(observer).update(weatherTypes[i % weatherTypes.length]); } verifyNoMoreInteractions(observer); } }
3,321
31.891089
140
java