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/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.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.servicelocator; import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; /** * The service cache implementation which will cache services that are being created. On first hit, * the cache will be empty and thus any service that is being requested, will be created fresh and * then placed into the cache map. On next hit, if same service name will be requested, it will be * returned from the cache * * @author saifasif */ @Slf4j public class ServiceCache { private final Map<String, Service> serviceCache; public ServiceCache() { serviceCache = new HashMap<>(); } /** * Get the service from the cache. null if no service is found matching the name * * @param serviceName a string * @return {@link Service} */ public Service getService(String serviceName) { if (serviceCache.containsKey(serviceName)) { var cachedService = serviceCache.get(serviceName); var name = cachedService.getName(); var id = cachedService.getId(); LOGGER.info("(cache call) Fetched service {}({}) from cache... !", name, id); return cachedService; } return null; } /** * Adds the service into the cache map. * * @param newService a {@link Service} */ public void addService(Service newService) { serviceCache.put(newService.getName(), newService); } }
2,663
35
140
java
java-design-patterns
java-design-patterns-master/monitor/src/test/java/com/iluwatar/monitor/MainTest.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.monitor; import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; import static org.junit.jupiter.api.Assertions.*; /** Test if the application starts without throwing an exception. */ class MainTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> Main.main(new String[] {})); } @Test void RunnerExecuteWithoutException() { var bank = new Bank(4, 1000); var latch = new CountDownLatch(1); assertDoesNotThrow(() -> Main.runner(bank, latch)); assertEquals(0, latch.getCount()); } }
1,879
38.166667
140
java
java-design-patterns
java-design-patterns-master/monitor/src/test/java/com/iluwatar/monitor/BankTest.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.monitor; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.*; class BankTest { private static final int ACCOUNT_NUM = 4; private static final int BASE_AMOUNT = 1000; private static Bank bank; @BeforeAll public static void Setup() { bank = new Bank(ACCOUNT_NUM, BASE_AMOUNT); } @AfterAll public static void TearDown() { bank = null; } @Test void GetAccountHaveNotBeNull() { assertNotNull(bank.getAccounts()); } @Test void LengthOfAccountsHaveToEqualsToAccountNumConstant() { assumeTrue(bank.getAccounts() != null); assertEquals(ACCOUNT_NUM, bank.getAccounts().length); } @Test void TransferMethodHaveToTransferAmountFromAnAccountToOtherAccount() { bank.transfer(0, 1, 1000); int[] accounts = bank.getAccounts(); assertEquals(0, accounts[0]); assertEquals(2000, accounts[1]); } @Test void BalanceHaveToBeOK() { assertEquals(4000, bank.getBalance()); } }
2,410
32.027397
140
java
java-design-patterns
java-design-patterns-master/monitor/src/main/java/com/iluwatar/monitor/Main.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.monitor; import java.security.SecureRandom; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import lombok.extern.slf4j.Slf4j; /** * The Monitor pattern is used in concurrent algorithms to achieve mutual exclusion. * * <p>Bank is a simple class that transfers money from an account to another account using {@link * Bank#transfer}. It can also return the balance of the bank account stored in the bank. * * <p>Main class uses ThreadPool to run threads that do transactions on the bank accounts. */ @Slf4j public class Main { private static final int NUMBER_OF_THREADS = 5; /** * Runner to perform a bunch of transfers and handle exception. * * @param bank bank object * @param latch signal finished execution */ public static void runner(Bank bank, CountDownLatch latch) { try { SecureRandom random = new SecureRandom(); Thread.sleep(random.nextInt(1000)); LOGGER.info("Start transferring..."); for (int i = 0; i < 1000000; i++) { bank.transfer(random.nextInt(4), random.nextInt(4), random.nextInt()); } LOGGER.info("Finished transferring."); latch.countDown(); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); Thread.currentThread().interrupt(); } } /** * Program entry point. * * @param args command line args */ public static void main(String[] args) throws InterruptedException { var bank = new Bank(4, 1000); var latch = new CountDownLatch(NUMBER_OF_THREADS); var executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS); for (int i = 0; i < NUMBER_OF_THREADS; i++) { executorService.execute(() -> runner(bank, latch)); } latch.await(); } }
3,070
35.559524
140
java
java-design-patterns
java-design-patterns-master/monitor/src/main/java/com/iluwatar/monitor/Bank.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. */ /* *The MIT License *Copyright © 2014-2021 Ilkka Seppälä * *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.monitor; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; /** Bank Definition. */ @Slf4j public class Bank { private final int[] accounts; /** * Constructor. * * @param accountNum - account number * @param baseAmount - base amount */ public Bank(int accountNum, int baseAmount) { accounts = new int[accountNum]; Arrays.fill(accounts, baseAmount); } /** * Transfer amounts from one account to another. * * @param accountA - source account * @param accountB - destination account * @param amount - amount to be transferred */ public synchronized void transfer(int accountA, int accountB, int amount) { if (accounts[accountA] >= amount) { accounts[accountB] += amount; accounts[accountA] -= amount; if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Transferred from account: {} to account: {} , amount: {} , balance: {}", accountA, accountB, amount, getBalance()); } } } /** * Calculates the total balance. * * @return balance */ public synchronized int getBalance() { int balance = 0; for (int account : accounts) { balance += account; } return balance; } /** * Get all accounts. * * @return accounts */ public int[] getAccounts() { return accounts; } }
3,790
32.254386
140
java
java-design-patterns
java-design-patterns-master/throttling/src/test/java/com/iluwatar/throttling/BarCustomerTest.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.throttling; import org.junit.jupiter.api.Test; import java.security.InvalidParameterException; import static org.junit.jupiter.api.Assertions.assertThrows; /** * TenantTest to test the creation of Tenant with valid parameters. */ class BarCustomerTest { @Test void constructorTest() { assertThrows(InvalidParameterException.class, () -> { new BarCustomer("sirBrave", -1, new CallsCount()); }); } }
1,729
38.318182
140
java
java-design-patterns
java-design-patterns-master/throttling/src/test/java/com/iluwatar/throttling/BartenderTest.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.throttling; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.throttling.timer.Throttler; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; /** * B2BServiceTest class to test the B2BService */ class BartenderTest { private final CallsCount callsCount = new CallsCount(); @Test void dummyCustomerApiTest() { var tenant = new BarCustomer("pirate", 2, callsCount); // In order to assure that throttling limits will not be reset, we use an empty throttling implementation var timer = (Throttler) () -> {}; var service = new Bartender(timer, callsCount); IntStream.range(0, 5).mapToObj(i -> tenant).forEach(service::orderDrink); var counter = callsCount.getCount(tenant.getName()); assertEquals(2, counter, "Counter limit must be reached"); } }
2,140
40.173077
140
java
java-design-patterns
java-design-patterns-master/throttling/src/test/java/com/iluwatar/throttling/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.throttling; 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/throttling/src/main/java/com/iluwatar/throttling/CallsCount.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.throttling; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import lombok.extern.slf4j.Slf4j; /** * A class to keep track of the counter of different Tenants. * * @author drastogi */ @Slf4j public final class CallsCount { private final Map<String, AtomicLong> tenantCallsCount = new ConcurrentHashMap<>(); /** * Add a new tenant to the map. * * @param tenantName name of the tenant. */ public void addTenant(String tenantName) { tenantCallsCount.putIfAbsent(tenantName, new AtomicLong(0)); } /** * Increment the count of the specified tenant. * * @param tenantName name of the tenant. */ public void incrementCount(String tenantName) { tenantCallsCount.get(tenantName).incrementAndGet(); } /** * Get count of tenant based on tenant name. * * @param tenantName name of the tenant. * @return the count of the tenant. */ public long getCount(String tenantName) { return tenantCallsCount.get(tenantName).get(); } /** * Resets the count of all the tenants in the map. */ public void reset() { tenantCallsCount.replaceAll((k, v) -> new AtomicLong(0)); LOGGER.info("reset counters"); } }
2,555
32.194805
140
java
java-design-patterns
java-design-patterns-master/throttling/src/main/java/com/iluwatar/throttling/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.throttling; import com.iluwatar.throttling.timer.ThrottleTimerImpl; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import lombok.extern.slf4j.Slf4j; /** * Throttling pattern is a design pattern to throttle or limit the use of resources or even a * complete service by users or a particular tenant. This can allow systems to continue to function * and meet service level agreements, even when an increase in demand places load on resources. * <p> * In this example there is a {@link Bartender} serving beer to {@link BarCustomer}s. This is a time * based throttling, i.e. only a certain number of calls are allowed per second. * </p> * ({@link BarCustomer}) is the service tenant class having a name and the number of calls allowed. * ({@link Bartender}) is the service which is consumed by the tenants and is throttled. */ @Slf4j public class App { /** * Application entry point. * * @param args main arguments */ public static void main(String[] args) { var callsCount = new CallsCount(); var human = new BarCustomer("young human", 2, callsCount); var dwarf = new BarCustomer("dwarf soldier", 4, callsCount); var executorService = Executors.newFixedThreadPool(2); executorService.execute(() -> makeServiceCalls(human, callsCount)); executorService.execute(() -> makeServiceCalls(dwarf, callsCount)); executorService.shutdown(); try { if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) { executorService.shutdownNow(); } } catch (InterruptedException e) { executorService.shutdownNow(); } } /** * Make calls to the bartender. */ private static void makeServiceCalls(BarCustomer barCustomer, CallsCount callsCount) { var timer = new ThrottleTimerImpl(1000, callsCount); var service = new Bartender(timer, callsCount); // Sleep is introduced to keep the output in check and easy to view and analyze the results. IntStream.range(0, 50).forEach(i -> { service.orderDrink(barCustomer); try { Thread.sleep(100); } catch (InterruptedException e) { LOGGER.error("Thread interrupted: {}", e.getMessage()); } }); } }
3,560
39.011236
140
java
java-design-patterns
java-design-patterns-master/throttling/src/main/java/com/iluwatar/throttling/Bartender.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.throttling; import com.iluwatar.throttling.timer.Throttler; import java.util.concurrent.ThreadLocalRandom; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Bartender is a service which accepts a BarCustomer (tenant) and throttles * the resource based on the time given to the tenant. */ class Bartender { private static final Logger LOGGER = LoggerFactory.getLogger(Bartender.class); private final CallsCount callsCount; public Bartender(Throttler timer, CallsCount callsCount) { this.callsCount = callsCount; timer.start(); } /** * Orders a drink from the bartender. * @return customer id which is randomly generated */ public int orderDrink(BarCustomer barCustomer) { var tenantName = barCustomer.getName(); var count = callsCount.getCount(tenantName); if (count >= barCustomer.getAllowedCallsPerSecond()) { LOGGER.error("I'm sorry {}, you've had enough for today!", tenantName); return -1; } callsCount.incrementCount(tenantName); LOGGER.debug("Serving beer to {} : [{} consumed] ", barCustomer.getName(), count + 1); return getRandomCustomerId(); } private int getRandomCustomerId() { return ThreadLocalRandom.current().nextInt(1, 10000); } }
2,554
37.712121
140
java
java-design-patterns
java-design-patterns-master/throttling/src/main/java/com/iluwatar/throttling/BarCustomer.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.throttling; import java.security.InvalidParameterException; import lombok.Getter; /** * BarCustomer is a tenant with a name and a number of allowed calls per second. */ public class BarCustomer { @Getter private final String name; @Getter private final int allowedCallsPerSecond; /** * Constructor. * * @param name Name of the BarCustomer * @param allowedCallsPerSecond The number of calls allowed for this particular tenant. * @throws InvalidParameterException If number of calls is less than 0, throws exception. */ public BarCustomer(String name, int allowedCallsPerSecond, CallsCount callsCount) { if (allowedCallsPerSecond < 0) { throw new InvalidParameterException("Number of calls less than 0 not allowed"); } this.name = name; this.allowedCallsPerSecond = allowedCallsPerSecond; callsCount.addTenant(name); } }
2,188
38.089286
140
java
java-design-patterns
java-design-patterns-master/throttling/src/main/java/com/iluwatar/throttling/timer/Throttler.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.throttling.timer; /** * An interface for defining the structure of different types of throttling ways. * @author drastogi * */ public interface Throttler { void start(); }
1,485
40.277778
140
java
java-design-patterns
java-design-patterns-master/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.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.throttling.timer; import com.iluwatar.throttling.CallsCount; import java.util.Timer; import java.util.TimerTask; /** * Implementation of throttler interface. This class resets the counter every second. * @author drastogi * */ public class ThrottleTimerImpl implements Throttler { private final int throttlePeriod; private final CallsCount callsCount; public ThrottleTimerImpl(int throttlePeriod, CallsCount callsCount) { this.throttlePeriod = throttlePeriod; this.callsCount = callsCount; } /** * A timer is initiated with this method. The timer runs every second and resets the * counter. */ @Override public void start() { new Timer(true).schedule(new TimerTask() { @Override public void run() { callsCount.reset(); } }, 0, throttlePeriod); } }
2,128
34.483333
140
java
java-design-patterns
java-design-patterns-master/converter/src/test/java/com/iluwatar/converter/ConverterTest.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.converter; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.Random; import org.junit.jupiter.api.Test; /** * Tests for {@link Converter} */ class ConverterTest { private final UserConverter userConverter = new UserConverter(); /** * Tests whether a converter created of opposite functions holds equality as a bijection. */ @Test void testConversionsStartingFromDomain() { var u1 = new User("Tom", "Hanks", true, "tom@hanks.com"); var u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1)); assertEquals(u1, u2); } /** * Tests whether a converter created of opposite functions holds equality as a bijection. */ @Test void testConversionsStartingFromDto() { var u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com"); var u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1)); assertEquals(u1, u2); } /** * Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and cleanly * instantiated allowing various different conversion strategies to be implemented. */ @Test void testCustomConverter() { var converter = new Converter<UserDto, User>( userDto -> new User( userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), String.valueOf(new Random().nextInt()) ), user -> new UserDto( user.getFirstName(), user.getLastName(), user.isActive(), user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com") ); var u1 = new User("John", "Doe", false, "12324"); var userDto = converter.convertFromEntity(u1); assertEquals("johndoe@whatever.com", userDto.getEmail()); } /** * Test whether converting a collection of Users to DTO Users and then converting them back to * domain users returns an equal collection. */ @Test void testCollectionConversion() { var users = List.of( new User("Camile", "Tough", false, "124sad"), new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243") ); var fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); assertEquals(users, fromDtos); } }
3,657
35.949495
140
java
java-design-patterns
java-design-patterns-master/converter/src/test/java/com/iluwatar/converter/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.converter; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * App running 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#main(String[])} * throws an exception. */ @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,806
35.14
140
java
java-design-patterns
java-design-patterns-master/converter/src/main/java/com/iluwatar/converter/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.converter; import java.util.List; import lombok.extern.slf4j.Slf4j; /** * The Converter pattern is a behavioral design pattern which allows a common way of bidirectional * conversion between corresponding types (e.g. DTO and domain representations of the logically * isomorphic types). Moreover, the pattern introduces a common way of converting a collection of * objects between types. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { Converter<UserDto, User> userConverter = new UserConverter(); UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); User user = userConverter.convertFromDto(dtoUser); LOGGER.info("Entity converted from DTO: {}", user); var users = List.of( new User("Camile", "Tough", false, "124sad"), new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243") ); LOGGER.info("Domain entities:"); users.stream().map(User::toString).forEach(LOGGER::info); LOGGER.info("DTO entities converted from domain:"); List<UserDto> dtoEntities = userConverter.createFromEntities(users); dtoEntities.stream().map(UserDto::toString).forEach(LOGGER::info); } }
2,610
39.169231
140
java
java-design-patterns
java-design-patterns-master/converter/src/main/java/com/iluwatar/converter/Converter.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.converter; import java.util.Collection; import java.util.List; import java.util.function.Function; import lombok.RequiredArgsConstructor; /** * Generic converter, thanks to Java8 features not only provides a way of generic bidirectional * conversion between corresponding types, but also a common way of converting a collection of * objects of the same type, reducing boilerplate code to the absolute minimum. * * @param <T> DTO representation's type * @param <U> Domain representation's type */ @RequiredArgsConstructor public class Converter<T, U> { private final Function<T, U> fromDto; private final Function<U, T> fromEntity; /** * Converts DTO to Entity. * * @param dto DTO entity * @return The domain representation - the result of the converting function application on dto * entity. */ public final U convertFromDto(final T dto) { return fromDto.apply(dto); } /** * Converts Entity to DTO. * * @param entity domain entity * @return The DTO representation - the result of the converting function application on domain * entity. */ public final T convertFromEntity(final U entity) { return fromEntity.apply(entity); } /** * Converts list of DTOs to list of Entities. * * @param dtos collection of DTO entities * @return List of domain representation of provided entities retrieved by mapping each of them * with the conversion function */ public final List<U> createFromDtos(final Collection<T> dtos) { return dtos.stream().map(this::convertFromDto).toList(); } /** * Converts list of Entities to list of DTOs. * * @param entities collection of domain entities * @return List of domain representation of provided entities retrieved by mapping each of them * with the conversion function */ public final List<T> createFromEntities(final Collection<U> entities) { return entities.stream().map(this::convertFromEntity).toList(); } }
3,289
35.153846
140
java
java-design-patterns
java-design-patterns-master/converter/src/main/java/com/iluwatar/converter/UserConverter.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.converter; /** * Example implementation of the simple User converter. */ public class UserConverter extends Converter<UserDto, User> { public UserConverter() { super(UserConverter::convertToEntity, UserConverter::convertToDto); } private static UserDto convertToDto(User user) { return new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), user.getUserId()); } private static User convertToEntity(UserDto dto) { return new User(dto.getFirstName(), dto.getLastName(), dto.isActive(), dto.getEmail()); } }
1,856
40.266667
140
java
java-design-patterns
java-design-patterns-master/converter/src/main/java/com/iluwatar/converter/UserDto.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.converter; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; /** * User DTO class. */ @RequiredArgsConstructor @Getter @EqualsAndHashCode @ToString public class UserDto { private final String firstName; private final String lastName; private final boolean active; private final String email; }
1,681
34.787234
140
java
java-design-patterns
java-design-patterns-master/converter/src/main/java/com/iluwatar/converter/User.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.converter; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; /** * User class. */ @ToString @EqualsAndHashCode @Getter @RequiredArgsConstructor public class User { private final String firstName; private final String lastName; private final boolean active; private final String userId; }
1,673
36.2
140
java
java-design-patterns
java-design-patterns-master/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.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.mediator; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; 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 java.util.function.Supplier; import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; /** * Date: 12/19/15 - 10:13 PM * * @author Jeroen Meulemeester */ class PartyMemberTest { static Stream<Arguments> dataProvider() { return Stream.of( Arguments.of((Supplier<PartyMember>) Hobbit::new), Arguments.of((Supplier<PartyMember>) Hunter::new), Arguments.of((Supplier<PartyMember>) Rogue::new), Arguments.of((Supplier<PartyMember>) Wizard::new) ); } private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(PartyMemberBase.class); } @AfterEach void tearDown() { appender.stop(); } /** * Verify if a party action triggers the correct output to the std-Out */ @ParameterizedTest @MethodSource("dataProvider") void testPartyAction(Supplier<PartyMember> memberSupplier) { final var member = memberSupplier.get(); for (final var action : Action.values()) { member.partyAction(action); assertEquals(member.toString() + " " + action.getDescription(), appender.getLastMessage()); } assertEquals(Action.values().length, appender.getLogSize()); } /** * Verify if a member action triggers the expected interactions with the party class */ @ParameterizedTest @MethodSource("dataProvider") void testAct(Supplier<PartyMember> memberSupplier) { final var member = memberSupplier.get(); member.act(Action.GOLD); assertEquals(0, appender.getLogSize()); final var party = mock(Party.class); member.joinedParty(party); assertEquals(member.toString() + " joins the party", appender.getLastMessage()); for (final var action : Action.values()) { member.act(action); assertEquals(member.toString() + " " + action.toString(), appender.getLastMessage()); verify(party).act(member, action); } assertEquals(Action.values().length + 1, appender.getLogSize()); } /** * Verify if {@link PartyMemberBase#toString()} generate the expected output */ @ParameterizedTest @MethodSource("dataProvider") void testToString(Supplier<PartyMember> memberSupplier) { final var member = memberSupplier.get(); final var memberClass = member.getClass(); assertEquals(memberClass.getSimpleName(), member.toString()); } private static class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender(Class<?> clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public int getLogSize() { return log.size(); } public String getLastMessage() { return log.get(log.size() - 1).getFormattedMessage(); } } }
4,778
31.290541
140
java
java-design-patterns
java-design-patterns-master/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.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.mediator; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; /** * Date: 12/19/15 - 10:00 PM * * @author Jeroen Meulemeester */ class PartyImplTest { /** * Verify if a member is notified when it's joining a party. Generate an action and see if the * other member gets it. Also check members don't get their own actions. */ @Test void testPartyAction() { final var partyMember1 = mock(PartyMember.class); final var partyMember2 = mock(PartyMember.class); final var party = new PartyImpl(); party.addMember(partyMember1); party.addMember(partyMember2); verify(partyMember1).joinedParty(party); verify(partyMember2).joinedParty(party); party.act(partyMember1, Action.GOLD); verifyNoMoreInteractions(partyMember1); verify(partyMember2).partyAction(Action.GOLD); verifyNoMoreInteractions(partyMember1, partyMember2); } }
2,321
35.28125
140
java
java-design-patterns
java-design-patterns-master/mediator/src/test/java/com/iluwatar/mediator/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.mediator; 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,587
37.731707
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/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.mediator; /** * The Mediator pattern defines an object that encapsulates how a set of objects interact. This * pattern is considered to be a behavioral pattern due to the way it can alter the program's * running behavior. * * <p>Usually a program is made up of a large number of classes. So the logic and computation is * distributed among these classes. However, as more classes are developed in a program, especially * during maintenance and/or refactoring, the problem of communication between these classes may * become more complex. This makes the program harder to read and maintain. Furthermore, it can * become difficult to change the program, since any change may affect code in several other * classes. * * <p>With the Mediator pattern, communication between objects is encapsulated with a mediator * object. Objects no longer communicate directly with each other, but instead communicate through * the mediator. This reduces the dependencies between communicating objects, thereby lowering the * coupling. * * <p>In this example the mediator encapsulates how a set of objects ({@link PartyMember}) * interact. Instead of referring to each other directly they use the mediator ({@link Party}) * interface. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // create party and members Party party = new PartyImpl(); var hobbit = new Hobbit(); var wizard = new Wizard(); var rogue = new Rogue(); var hunter = new Hunter(); // add party members party.addMember(hobbit); party.addMember(wizard); party.addMember(rogue); party.addMember(hunter); // perform actions -> the other party members // are notified by the party hobbit.act(Action.ENEMY); wizard.act(Action.TALE); rogue.act(Action.GOLD); hunter.act(Action.HUNT); } }
3,223
40.333333
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/PartyMember.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.mediator; /** * Interface for party members interacting with {@link Party}. */ public interface PartyMember { void joinedParty(Party party); void partyAction(Action action); void act(Action action); }
1,518
38.973684
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/Hunter.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.mediator; /** * Hunter party member. */ public class Hunter extends PartyMemberBase { @Override public String toString() { return "Hunter"; } }
1,463
38.567568
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/Wizard.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.mediator; /** * Wizard party member. */ public class Wizard extends PartyMemberBase { @Override public String toString() { return "Wizard"; } }
1,464
37.552632
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/Party.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.mediator; /** * Party interface. */ public interface Party { void addMember(PartyMember member); void act(PartyMember actor, Action action); }
1,458
38.432432
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/Action.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.mediator; /** * Action enumeration. */ public enum Action { HUNT("hunted a rabbit", "arrives for dinner"), TALE("tells a tale", "comes to listen"), GOLD("found gold", "takes his share of the gold"), ENEMY("spotted enemies", "runs for cover"), NONE("", ""); private final String title; private final String description; Action(String title, String description) { this.title = title; this.description = description; } public String getDescription() { return description; } public String toString() { return title; } }
1,870
34.301887
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/Hobbit.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.mediator; /** * Hobbit party member. */ public class Hobbit extends PartyMemberBase { @Override public String toString() { return "Hobbit"; } }
1,464
37.552632
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.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.mediator; import java.util.ArrayList; import java.util.List; /** * Party implementation. */ public class PartyImpl implements Party { private final List<PartyMember> members; public PartyImpl() { members = new ArrayList<>(); } @Override public void act(PartyMember actor, Action action) { for (var member : members) { if (!member.equals(actor)) { member.partyAction(action); } } } @Override public void addMember(PartyMember member) { members.add(member); member.joinedParty(this); } }
1,857
32.178571
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.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.mediator; import lombok.extern.slf4j.Slf4j; /** * Abstract base class for party members. */ @Slf4j public abstract class PartyMemberBase implements PartyMember { protected Party party; @Override public void joinedParty(Party party) { LOGGER.info("{} joins the party", this); this.party = party; } @Override public void partyAction(Action action) { LOGGER.info("{} {}", this, action.getDescription()); } @Override public void act(Action action) { if (party != null) { LOGGER.info("{} {}", this, action); party.act(this, action); } } @Override public abstract String toString(); }
1,950
31.516667
140
java
java-design-patterns
java-design-patterns-master/mediator/src/main/java/com/iluwatar/mediator/Rogue.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.mediator; /** * Rogue party member. */ public class Rogue extends PartyMemberBase { @Override public String toString() { return "Rogue"; } }
1,461
37.473684
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/test/java/com/iluwatar/page/controller/SignupModelTest.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.page.controller; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for Signup Model */ public class SignupModelTest { /** * Verify if a user can set a name properly */ @Test void testSetName() { SignupModel model = new SignupModel(); model.setName("Lily"); assertEquals("Lily", model.getName()); } /** * Verify if a user can set an email properly */ @Test void testSetEmail() { SignupModel model = new SignupModel(); model.setEmail("Lily@email"); assertEquals("Lily@email", model.getEmail()); } /** * Verify if a user can set a password properly */ @Test void testSetPassword() { SignupModel model = new SignupModel(); model.setPassword("password1234"); assertEquals("password1234", model.getPassword()); } }
2,155
32.6875
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/test/java/com/iluwatar/page/controller/SignupControllerTest.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.page.controller; import org.junit.jupiter.api.Test; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for Signup Controller */ public class SignupControllerTest { /** * Verify if user can sign up and redirect to user page */ @Test void testSignup() { var controller = new SignupController(); controller.getSignup(); RedirectAttributes redirectAttributes = new RedirectAttributesModelMap(); String redirectPath = controller.create(retrieveSignupData(), redirectAttributes); assertEquals("redirect:/user", redirectPath); } public static SignupModel retrieveSignupData() { SignupModel model = new SignupModel(); model.setName("Lily"); model.setEmail("lily@email.com"); model.setPassword("password1234"); return model; } }
2,261
38
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/test/java/com/iluwatar/page/controller/UserControllerTest.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.page.controller; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc public class UserControllerTest { private UserController userController; @Autowired MockMvc mockMvc; /** * Verify if view and model are directed properly */ @Test void testGetUserPath () throws Exception { this.mockMvc.perform(get("/user") .param("name", "Lily") .param("email", "Lily@email.com")) .andExpect(status().isOk()) .andExpect(model().attribute("name", "Lily")) .andExpect(model().attribute("email", "Lily@email.com")) .andReturn(); } }
2,619
41.95082
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/test/java/com/iluwatar/page/controller/UserModelTest.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.page.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class UserModelTest { /** * Verify if a user can set a name properly */ @Test void testSetName() { UserModel model = new UserModel(); model.setName("Lily"); assertEquals("Lily", model.getName()); } /** * Verify if a user can set an email properly */ @Test void testSetEmail() { UserModel model = new UserModel(); model.setEmail("Lily@email"); assertEquals("Lily@email", model.getEmail()); } }
1,874
35.057692
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/test/java/com/iluwatar/page/controller/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.page.controller; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ public class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,599
40.025641
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/main/java/com.iluwatar.page.controller/SignupModel.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.page.controller; import lombok.Getter; import lombok.Setter; import org.springframework.stereotype.Component; /** * ignup model. */ @Component @Getter @Setter public class SignupModel { private String name; private String email; private String password; public SignupModel() { } }
1,601
34.6
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/main/java/com.iluwatar.page.controller/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.page.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Page Controller pattern is utilized when we want to simplify relationship in a dynamic website. * It is an approach of one front page leading to one logical file that handles HTTP requests and actions. * In this example, we build a website with signup page handling an input form with Signup Controller, Signup View, and Signup Model * and after signup, it is redirected to a user page handling with User Controller, User View, and User Model. */ @Slf4j @SpringBootApplication public class App { /** * Program entry point. * * @param args command line args */ public static void main(final String[] args) { SpringApplication.run(App.class, args); } }
2,161
43.122449
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/main/java/com.iluwatar.page.controller/SignupController.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.page.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * Signup Controller. */ @Slf4j @Controller @Component public class SignupController { SignupView view = new SignupView(); /** * Signup Controller can handle http request and decide which model and view use. */ SignupController() { } /** * Handle http GET request. */ @GetMapping("/signup") public String getSignup() { return view.display(); } /** * Handle http POST request and access model and view. */ @PostMapping("/signup") public String create(SignupModel form, RedirectAttributes redirectAttributes) { LOGGER.info(form.getName()); LOGGER.info(form.getEmail()); redirectAttributes.addAttribute("name", form.getName()); redirectAttributes.addAttribute("email", form.getEmail()); redirectAttributes.addFlashAttribute("userInfo", form); return view.redirect(form); } }
2,496
35.188406
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/main/java/com.iluwatar.page.controller/UserModel.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.page.controller; import lombok.Getter; import lombok.Setter; /** * User model. */ @Getter @Setter public class UserModel { private String name; private String email; public UserModel() {} }
1,508
35.804878
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/main/java/com.iluwatar.page.controller/UserController.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.page.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; /** * User Controller. */ @Slf4j @Controller public class UserController { private final UserView view = new UserView(); public UserController() {} /** * Handle http GET request and access view and model. */ @GetMapping("/user") public String getUserPath(SignupModel form, Model model) { model.addAttribute("name", form.getName()); model.addAttribute("email", form.getEmail()); return view.display(form); } }
1,947
36.461538
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/main/java/com.iluwatar.page.controller/UserView.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.page.controller; import lombok.extern.slf4j.Slf4j; /** * User view class generating html file. */ @Slf4j public class UserView { /** * displaying command to generate html. * @param user model content. */ public String display(SignupModel user) { LOGGER.info("display user html" + " name " + user.getName() + " email " + user.getEmail()); return "/user"; } }
1,690
38.325581
140
java
java-design-patterns
java-design-patterns-master/page-controller/src/main/java/com.iluwatar.page.controller/SignupView.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.page.controller; import lombok.extern.slf4j.Slf4j; /** * Signup View. */ @Slf4j public class SignupView { public SignupView() { } public String display() { LOGGER.info("display signup front page"); return "/signup"; } /** * redirect to user page. */ public String redirect(SignupModel form) { LOGGER.info("Redirect to user page with " + "name " + form.getName() + " email " + form.getEmail()); return "redirect:/user"; } }
1,770
34.42
140
java
java-design-patterns
java-design-patterns-master/bytecode/src/test/java/com/iluwatar/bytecode/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.bytecode; 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,788
36.270833
140
java
java-design-patterns
java-design-patterns-master/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.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.bytecode; import static com.iluwatar.bytecode.Instruction.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; /** * Test for {@link VirtualMachine} */ class VirtualMachineTest { @Test void testLiteral() { var bytecode = new int[2]; bytecode[0] = LITERAL.getIntValue(); bytecode[1] = 10; var vm = new VirtualMachine(); vm.execute(bytecode); assertEquals(1, vm.getStack().size()); assertEquals(Integer.valueOf(10), vm.getStack().pop()); } @Test void testSetHealth() { var wizardNumber = 0; var bytecode = new int[5]; bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); bytecode[3] = 50; // health amount bytecode[4] = SET_HEALTH.getIntValue(); var vm = new VirtualMachine(); vm.execute(bytecode); assertEquals(50, vm.getWizards()[wizardNumber].getHealth()); } @Test void testSetAgility() { var wizardNumber = 0; var bytecode = new int[5]; bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); bytecode[3] = 50; // agility amount bytecode[4] = SET_AGILITY.getIntValue(); var vm = new VirtualMachine(); vm.execute(bytecode); assertEquals(50, vm.getWizards()[wizardNumber].getAgility()); } @Test void testSetWisdom() { var wizardNumber = 0; var bytecode = new int[5]; bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); bytecode[3] = 50; // wisdom amount bytecode[4] = SET_WISDOM.getIntValue(); var vm = new VirtualMachine(); vm.execute(bytecode); assertEquals(50, vm.getWizards()[wizardNumber].getWisdom()); } @Test void testGetHealth() { var wizardNumber = 0; var bytecode = new int[8]; bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); bytecode[3] = 50; // health amount bytecode[4] = SET_HEALTH.getIntValue(); bytecode[5] = LITERAL.getIntValue(); bytecode[6] = wizardNumber; bytecode[7] = GET_HEALTH.getIntValue(); var vm = new VirtualMachine(); vm.execute(bytecode); assertEquals(Integer.valueOf(50), vm.getStack().pop()); } @Test void testPlaySound() { var wizardNumber = 0; var bytecode = new int[3]; bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = PLAY_SOUND.getIntValue(); var vm = new VirtualMachine(); vm.execute(bytecode); assertEquals(0, vm.getStack().size()); assertEquals(1, vm.getWizards()[0].getNumberOfPlayedSounds()); } @Test void testSpawnParticles() { var wizardNumber = 0; var bytecode = new int[3]; bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = SPAWN_PARTICLES.getIntValue(); var vm = new VirtualMachine(); vm.execute(bytecode); assertEquals(0, vm.getStack().size()); assertEquals(1, vm.getWizards()[0].getNumberOfSpawnedParticles()); } @Test void testInvalidInstruction() { var bytecode = new int[1]; bytecode[0] = 999; var vm = new VirtualMachine(); assertThrows(IllegalArgumentException.class, () -> vm.execute(bytecode)); } }
4,781
29.458599
140
java
java-design-patterns
java-design-patterns-master/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.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.bytecode.util; import com.iluwatar.bytecode.Instruction; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link InstructionConverterUtil} */ class InstructionConverterUtilTest { @Test void testEmptyInstruction() { var instruction = ""; var bytecode = InstructionConverterUtil.convertToByteCode(instruction); Assertions.assertEquals(0, bytecode.length); } @Test void testInstructions() { var instructions = "LITERAL 35 SET_HEALTH SET_WISDOM SET_AGILITY PLAY_SOUND" + " SPAWN_PARTICLES GET_HEALTH ADD DIVIDE"; var bytecode = InstructionConverterUtil.convertToByteCode(instructions); Assertions.assertEquals(10, bytecode.length); Assertions.assertEquals(Instruction.LITERAL.getIntValue(), bytecode[0]); Assertions.assertEquals(35, bytecode[1]); Assertions.assertEquals(Instruction.SET_HEALTH.getIntValue(), bytecode[2]); Assertions.assertEquals(Instruction.SET_WISDOM.getIntValue(), bytecode[3]); Assertions.assertEquals(Instruction.SET_AGILITY.getIntValue(), bytecode[4]); Assertions.assertEquals(Instruction.PLAY_SOUND.getIntValue(), bytecode[5]); Assertions.assertEquals(Instruction.SPAWN_PARTICLES.getIntValue(), bytecode[6]); Assertions.assertEquals(Instruction.GET_HEALTH.getIntValue(), bytecode[7]); Assertions.assertEquals(Instruction.ADD.getIntValue(), bytecode[8]); Assertions.assertEquals(Instruction.DIVIDE.getIntValue(), bytecode[9]); } }
2,792
41.318182
140
java
java-design-patterns
java-design-patterns-master/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.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.bytecode; import lombok.AllArgsConstructor; import lombok.Getter; /** * Representation of instructions understandable by virtual machine. */ @AllArgsConstructor @Getter public enum Instruction { LITERAL(1), // e.g. "LITERAL 0", push 0 to stack SET_HEALTH(2), // e.g. "SET_HEALTH", pop health and wizard number, call set health SET_WISDOM(3), // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom SET_AGILITY(4), // e.g. "SET_AGILITY", pop agility and wizard number, call set agility PLAY_SOUND(5), // e.g. "PLAY_SOUND", pop value as wizard number, call play sound SPAWN_PARTICLES(6), // e.g. "SPAWN_PARTICLES", pop value as wizard number, call spawn particles GET_HEALTH(7), // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health GET_AGILITY(8), // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility GET_WISDOM(9), // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom ADD(10), // e.g. "ADD", pop 2 values, push their sum DIVIDE(11); // e.g. "DIVIDE", pop 2 values, push their division private final int intValue; /** * Converts integer value to Instruction. * * @param value value of instruction * @return representation of the instruction */ public static Instruction getInstruction(int value) { for (var i = 0; i < Instruction.values().length; i++) { if (Instruction.values()[i].getIntValue() == value) { return Instruction.values()[i]; } } throw new IllegalArgumentException("Invalid instruction value"); } }
2,928
43.378788
140
java
java-design-patterns
java-design-patterns-master/bytecode/src/main/java/com/iluwatar/bytecode/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.bytecode; import com.iluwatar.bytecode.util.InstructionConverterUtil; import lombok.extern.slf4j.Slf4j; /** * The intention of Bytecode pattern is to give behavior the flexibility of data by encoding it as * instructions for a virtual machine. An instruction set defines the low-level operations that can * be performed. A series of instructions is encoded as a sequence of bytes. A virtual machine * executes these instructions one at a time, using a stack for intermediate values. By combining * instructions, complex high-level behavior can be defined. * * <p>This pattern should be used when there is a need to define high number of behaviours and * implementation engine is not a good choice because It is too lowe level Iterating on it takes too * long due to slow compile times or other tooling issues. It has too much trust. If you want to * ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of * the codebase. */ @Slf4j public class App { private static final String LITERAL_0 = "LITERAL 0"; private static final String HEALTH_PATTERN = "%s_HEALTH"; private static final String GET_AGILITY = "GET_AGILITY"; private static final String GET_WISDOM = "GET_WISDOM"; private static final String ADD = "ADD"; private static final String LITERAL_2 = "LITERAL 2"; private static final String DIVIDE = "DIVIDE"; /** * Main app method. * * @param args command line args */ public static void main(String[] args) { var vm = new VirtualMachine( new Wizard(45, 7, 11, 0, 0), new Wizard(36, 18, 8, 0, 0)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "GET"))); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); vm.execute(InstructionConverterUtil.convertToByteCode(GET_AGILITY)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); vm.execute(InstructionConverterUtil.convertToByteCode(GET_WISDOM)); vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_2)); vm.execute(InstructionConverterUtil.convertToByteCode(DIVIDE)); vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "SET"))); } }
3,817
47.329114
140
java
java-design-patterns
java-design-patterns-master/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.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.bytecode; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * This class represent game objects which properties can be changed by instructions interpreted by * virtual machine. */ @AllArgsConstructor @Setter @Getter @Slf4j public class Wizard { private int health; private int agility; private int wisdom; private int numberOfPlayedSounds; private int numberOfSpawnedParticles; public void playSound() { LOGGER.info("Playing sound"); numberOfPlayedSounds++; } public void spawnParticles() { LOGGER.info("Spawning particles"); numberOfSpawnedParticles++; } }
1,972
33.017241
140
java
java-design-patterns
java-design-patterns-master/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.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.bytecode; import java.util.Stack; import java.util.concurrent.ThreadLocalRandom; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * Implementation of virtual machine. */ @Getter @Slf4j public class VirtualMachine { private final Stack<Integer> stack = new Stack<>(); private final Wizard[] wizards = new Wizard[2]; /** * No-args constructor. */ public VirtualMachine() { wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), 0, 0); wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), 0, 0); } /** * Constructor taking the wizards as arguments. */ public VirtualMachine(Wizard wizard1, Wizard wizard2) { wizards[0] = wizard1; wizards[1] = wizard2; } /** * Executes provided bytecode. * * @param bytecode to execute */ public void execute(int[] bytecode) { for (var i = 0; i < bytecode.length; i++) { Instruction instruction = Instruction.getInstruction(bytecode[i]); switch (instruction) { case LITERAL: // Read the next byte from the bytecode. int value = bytecode[++i]; // Push the next value to stack stack.push(value); break; case SET_AGILITY: var amount = stack.pop(); var wizard = stack.pop(); setAgility(wizard, amount); break; case SET_WISDOM: amount = stack.pop(); wizard = stack.pop(); setWisdom(wizard, amount); break; case SET_HEALTH: amount = stack.pop(); wizard = stack.pop(); setHealth(wizard, amount); break; case GET_HEALTH: wizard = stack.pop(); stack.push(getHealth(wizard)); break; case GET_AGILITY: wizard = stack.pop(); stack.push(getAgility(wizard)); break; case GET_WISDOM: wizard = stack.pop(); stack.push(getWisdom(wizard)); break; case ADD: var a = stack.pop(); var b = stack.pop(); stack.push(a + b); break; case DIVIDE: a = stack.pop(); b = stack.pop(); stack.push(b / a); break; case PLAY_SOUND: wizard = stack.pop(); getWizards()[wizard].playSound(); break; case SPAWN_PARTICLES: wizard = stack.pop(); getWizards()[wizard].spawnParticles(); break; default: throw new IllegalArgumentException("Invalid instruction value"); } LOGGER.info("Executed " + instruction.name() + ", Stack contains " + getStack()); } } public void setHealth(int wizard, int amount) { wizards[wizard].setHealth(amount); } public void setWisdom(int wizard, int amount) { wizards[wizard].setWisdom(amount); } public void setAgility(int wizard, int amount) { wizards[wizard].setAgility(amount); } public int getHealth(int wizard) { return wizards[wizard].getHealth(); } public int getWisdom(int wizard) { return wizards[wizard].getWisdom(); } public int getAgility(int wizard) { return wizards[wizard].getAgility(); } private int randomInt(int min, int max) { return ThreadLocalRandom.current().nextInt(min, max + 1); } }
4,676
28.980769
140
java
java-design-patterns
java-design-patterns-master/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.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.bytecode.util; import com.iluwatar.bytecode.Instruction; /** * Utility class used for instruction validation and conversion. */ public class InstructionConverterUtil { /** * Converts instructions represented as String. * * @param instructions to convert * @return array of int representing bytecode */ public static int[] convertToByteCode(String instructions) { if (instructions == null || instructions.trim().length() == 0) { return new int[0]; } var splitedInstructions = instructions.trim().split(" "); var bytecode = new int[splitedInstructions.length]; for (var i = 0; i < splitedInstructions.length; i++) { if (isValidInstruction(splitedInstructions[i])) { bytecode[i] = Instruction.valueOf(splitedInstructions[i]).getIntValue(); } else if (isValidInt(splitedInstructions[i])) { bytecode[i] = Integer.parseInt(splitedInstructions[i]); } else { var errorMessage = "Invalid instruction or number: " + splitedInstructions[i]; throw new IllegalArgumentException(errorMessage); } } return bytecode; } private static boolean isValidInstruction(String instruction) { try { Instruction.valueOf(instruction); return true; } catch (IllegalArgumentException e) { return false; } } private static boolean isValidInt(String value) { try { Integer.parseInt(value); return true; } catch (NumberFormatException e) { return false; } } }
2,819
35.153846
140
java
java-design-patterns
java-design-patterns-master/monad/src/test/java/com/iluwatar/monad/MonadTest.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.monad; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Objects; import org.junit.jupiter.api.Test; /** * Test for Monad Pattern */ class MonadTest { @Test void testForInvalidName() { var tom = new User(null, 21, Sex.MALE, "tom@foo.bar"); assertThrows( IllegalStateException.class, () -> Validator.of(tom) .validate(User::name, Objects::nonNull, "name cannot be null") .get() ); } @Test void testForInvalidAge() { var john = new User("John", 17, Sex.MALE, "john@qwe.bar"); assertThrows( IllegalStateException.class, () -> Validator.of(john) .validate(User::name, Objects::nonNull, "name cannot be null") .validate(User::age, age -> age > 21, "user is underage") .get() ); } @Test void testForValid() { var sarah = new User("Sarah", 42, Sex.FEMALE, "sarah@det.org"); var validated = Validator.of(sarah) .validate(User::name, Objects::nonNull, "name cannot be null") .validate(User::age, age -> age > 21, "user is underage") .validate(User::sex, sex -> sex == Sex.FEMALE, "user is not female") .validate(User::email, email -> email.contains("@"), "email does not contain @ sign") .get(); assertSame(validated, sarah); } }
2,707
36.09589
140
java
java-design-patterns
java-design-patterns-master/monad/src/test/java/com/iluwatar/monad/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.monad; 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,586
35.906977
140
java
java-design-patterns
java-design-patterns-master/monad/src/main/java/com/iluwatar/monad/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.monad; import java.util.Objects; import java.util.function.Function; import java.util.function.Predicate; import lombok.extern.slf4j.Slf4j; /** * The Monad pattern defines a monad structure, that enables chaining operations in pipelines and * processing data step by step. Formally, monad consists of a type constructor M and two * operations: * <br>bind - that takes monadic object and a function from plain object to the * monadic value and returns monadic value. * <br>return - that takes plain type object and returns this object wrapped in a monadic value. * * <p>In the given example, the Monad pattern is represented as a {@link Validator} that takes an * instance of a plain object with {@link Validator#of(Object)} and validates it {@link * Validator#validate(Function, Predicate, String)} against given predicates. * * <p>As a validation result {@link Validator#get()} either returns valid object * or throws {@link IllegalStateException} with list of exceptions collected during validation. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var user = new User("user", 24, Sex.FEMALE, "foobar.com"); LOGGER.info(Validator.of(user).validate(User::name, Objects::nonNull, "name is null") .validate(User::name, name -> !name.isEmpty(), "name is empty") .validate(User::email, email -> !email.contains("@"), "email doesn't contains '@'") .validate(User::age, age -> age > 20 && age < 30, "age isn't between...").get() .toString()); } }
2,907
44.4375
140
java
java-design-patterns
java-design-patterns-master/monad/src/main/java/com/iluwatar/monad/Sex.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.monad; /** * Enumeration of Types of Sex. */ public enum Sex { MALE, FEMALE }
1,388
41.090909
140
java
java-design-patterns
java-design-patterns-master/monad/src/main/java/com/iluwatar/monad/Validator.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.monad; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.function.Predicate; /** * Class representing Monad design pattern. Monad is a way of chaining operations on the given * object together step by step. In Validator each step results in either success or failure * indicator, giving a way of receiving each of them easily and finally getting validated object or * list of exceptions. * * @param <T> Placeholder for an object. */ public class Validator<T> { /** * Object that is validated. */ private final T obj; /** * List of exception thrown during validation. */ private final List<Throwable> exceptions = new ArrayList<>(); /** * Creates a monadic value of given object. * * @param obj object to be validated */ private Validator(T obj) { this.obj = obj; } /** * Creates validator against given object. * * @param t object to be validated * @param <T> object's type * @return new instance of a validator */ public static <T> Validator<T> of(T t) { return new Validator<>(Objects.requireNonNull(t)); } /** * Checks if the validation is successful. * * @param validation one argument boolean-valued function that represents one step of validation. * Adds exception to main validation exception list when single step validation * ends with failure. * @param message error message when object is invalid * @return this */ public Validator<T> validate(Predicate<? super T> validation, String message) { if (!validation.test(obj)) { exceptions.add(new IllegalStateException(message)); } return this; } /** * Extension for the {@link Validator#validate(Predicate, String)} method, dedicated for objects, * that need to be projected before requested validation. * * @param projection function that gets an objects, and returns projection representing element to * be validated. * @param validation see {@link Validator#validate(Predicate, String)} * @param message see {@link Validator#validate(Predicate, String)} * @param <U> see {@link Validator#validate(Predicate, String)} * @return this */ public <U> Validator<T> validate( Function<? super T, ? extends U> projection, Predicate<? super U> validation, String message ) { return validate(projection.andThen(validation::test)::apply, message); } /** * Receives validated object or throws exception when invalid. * * @return object that was validated * @throws IllegalStateException when any validation step results with failure */ public T get() throws IllegalStateException { if (exceptions.isEmpty()) { return obj; } var e = new IllegalStateException(); exceptions.forEach(e::addSuppressed); throw e; } }
4,255
33.885246
140
java
java-design-patterns
java-design-patterns-master/monad/src/main/java/com/iluwatar/monad/User.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.monad; /** * Record class. * * @param name - name * @param age - age * @param sex - sex * @param email - email address */ public record User(String name, int age, Sex sex, String email) { }
1,509
38.736842
140
java
java-design-patterns
java-design-patterns-master/caching/src/test/java/com/iluwatar/caching/CachingTest.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.caching; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Application test */ class CachingTest { private App app; /** * Setup of application test includes: initializing DB connection and cache size/capacity. */ @BeforeEach void setUp() { // VirtualDB (instead of MongoDB) was used in running the JUnit tests // to avoid Maven compilation errors. Set flag to true to run the // tests with MongoDB (provided that MongoDB is installed and socket // connection is open). app = new App(false); } @Test void testReadAndWriteThroughStrategy() { assertNotNull(app); app.useReadAndWriteThroughStrategy(); } @Test void testReadThroughAndWriteAroundStrategy() { assertNotNull(app); app.useReadThroughAndWriteAroundStrategy(); } @Test void testReadThroughAndWriteBehindStrategy() { assertNotNull(app); app.useReadThroughAndWriteBehindStrategy(); } @Test void testCacheAsideStrategy() { assertNotNull(app); app.useCacheAsideStategy(); } }
2,429
31.837838
140
java
java-design-patterns
java-design-patterns-master/caching/src/test/java/com/iluwatar/caching/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.caching; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that Caching example runs without errors. */ class AppTest { /** * Issue: Add at least one assertion to this test case. * <p> * 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,821
37.765957
140
java
java-design-patterns
java-design-patterns-master/caching/src/test/java/com/iluwatar/caching/database/MongoDbTest.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.caching.database; import com.iluwatar.caching.UserAccount; import com.iluwatar.caching.constants.CachingConstants; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import static com.iluwatar.caching.constants.CachingConstants.ADD_INFO; import static com.iluwatar.caching.constants.CachingConstants.USER_ID; import static com.iluwatar.caching.constants.CachingConstants.USER_NAME; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; class MongoDbTest { private static final String ID = "123"; private static final String NAME = "Some user"; private static final String ADDITIONAL_INFO = "Some app Info"; @Mock MongoDatabase db; private MongoDb mongoDb = new MongoDb(); private UserAccount userAccount; @BeforeEach void init() { db = mock(MongoDatabase.class); mongoDb.setDb(db); userAccount = new UserAccount(ID, NAME, ADDITIONAL_INFO); } @Test void connect() { assertDoesNotThrow(() -> mongoDb.connect()); } @Test void readFromDb() { Document document = new Document(USER_ID, ID) .append(USER_NAME, NAME) .append(ADD_INFO, ADDITIONAL_INFO); MongoCollection<Document> mongoCollection = mock(MongoCollection.class); when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); FindIterable<Document> findIterable = mock(FindIterable.class); when(mongoCollection.find(any(Document.class))).thenReturn(findIterable); when(findIterable.first()).thenReturn(document); assertEquals(mongoDb.readFromDb(ID),userAccount); } @Test void writeToDb() { MongoCollection<Document> mongoCollection = mock(MongoCollection.class); when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); assertDoesNotThrow(()-> {mongoDb.writeToDb(userAccount);}); } @Test void updateDb() { MongoCollection<Document> mongoCollection = mock(MongoCollection.class); when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); assertDoesNotThrow(()-> {mongoDb.updateDb(userAccount);}); } @Test void upsertDb() { MongoCollection<Document> mongoCollection = mock(MongoCollection.class); when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); assertDoesNotThrow(()-> {mongoDb.upsertDb(userAccount);}); } }
3,950
37.359223
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/package-info.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.caching;
1,314
49.576923
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/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.caching; import com.iluwatar.caching.database.DbManager; import com.iluwatar.caching.database.DbManagerFactory; import lombok.extern.slf4j.Slf4j; /** * The Caching pattern describes how to avoid expensive re-acquisition of * resources by not releasing the resources immediately after their use. * The resources retain their identity, are kept in some fast-access storage, * and are re-used to avoid having to acquire them again. There are four main * caching strategies/techniques in this pattern; each with their own pros and * cons. They are <code>write-through</code> which writes data to the cache and * DB in a single transaction, <code>write-around</code> which writes data * immediately into the DB instead of the cache, <code>write-behind</code> * which writes data into the cache initially whilst the data is only * written into the DB when the cache is full, and <code>cache-aside</code> * which pushes the responsibility of keeping the data synchronized in both * data sources to the application itself. The <code>read-through</code> * strategy is also included in the mentioned four strategies -- * returns data from the cache to the caller <b>if</b> it exists <b>else</b> * queries from DB and stores it into the cache for future use. These strategies * determine when the data in the cache should be written back to the backing * store (i.e. Database) and help keep both data sources * synchronized/up-to-date. This pattern can improve performance and also helps * to maintainconsistency between data held in the cache and the data in * the underlying data store. * * <p>In this example, the user account ({@link UserAccount}) entity is used * as the underlying application data. The cache itself is implemented as an * internal (Java) data structure. It adopts a Least-Recently-Used (LRU) * strategy for evicting data from itself when its full. The four * strategies are individually tested. The testing of the cache is restricted * towards saving and querying of user accounts from the * underlying data store( {@link DbManager}). The main class ( {@link App} * is not aware of the underlying mechanics of the application * (i.e. save and query) and whether the data is coming from the cache or the * DB (i.e. separation of concern). The AppManager ({@link AppManager}) handles * the transaction of data to-and-from the underlying data store (depending on * the preferred caching policy/strategy). * <p> * <i>{@literal App --> AppManager --> CacheStore/LRUCache/CachingPolicy --> * DBManager} </i> * </p> * * <p> * There are 2 ways to launch the application. * - to use "in Memory" database. * - to use the MongoDb as a database * * To run the application with "in Memory" database, just launch it without parameters * Example: 'java -jar app.jar' * * To run the application with MongoDb you need to be installed the MongoDb * in your system, or to launch it in the docker container. * You may launch docker container from the root of current module with command: * 'docker-compose up' * Then you can start the application with parameter --mongo * Example: 'java -jar app.jar --mongo' * </p> * * @see CacheStore * @see LruCache * @see CachingPolicy */ @Slf4j public class App { /** * Constant parameter name to use mongoDB. */ private static final String USE_MONGO_DB = "--mongo"; /** * Application manager. */ private final AppManager appManager; /** * Constructor of current App. * * @param isMongo boolean */ public App(final boolean isMongo) { DbManager dbManager = DbManagerFactory.initDb(isMongo); appManager = new AppManager(dbManager); appManager.initDb(); } /** * Program entry point. * * @param args command line args */ public static void main(final String[] args) { // VirtualDB (instead of MongoDB) was used in running the JUnit tests // and the App class to avoid Maven compilation errors. Set flag to // true to run the tests with MongoDB (provided that MongoDB is // installed and socket connection is open). boolean isDbMongo = isDbMongo(args); if (isDbMongo) { LOGGER.info("Using the Mongo database engine to run the application."); } else { LOGGER.info("Using the 'in Memory' database to run the application."); } App app = new App(isDbMongo); app.useReadAndWriteThroughStrategy(); String splitLine = "=============================================="; LOGGER.info(splitLine); app.useReadThroughAndWriteAroundStrategy(); LOGGER.info(splitLine); app.useReadThroughAndWriteBehindStrategy(); LOGGER.info(splitLine); app.useCacheAsideStategy(); LOGGER.info(splitLine); } /** * Check the input parameters. if * * @param args input params * @return true if there is "--mongo" parameter in arguments */ private static boolean isDbMongo(final String[] args) { for (String arg : args) { if (arg.equals(USE_MONGO_DB)) { return true; } } return false; } /** * Read-through and write-through. */ public void useReadAndWriteThroughStrategy() { LOGGER.info("# CachingPolicy.THROUGH"); appManager.initCachingPolicy(CachingPolicy.THROUGH); var userAccount1 = new UserAccount("001", "John", "He is a boy."); appManager.save(userAccount1); LOGGER.info(appManager.printCacheContent()); appManager.find("001"); appManager.find("001"); } /** * Read-through and write-around. */ public void useReadThroughAndWriteAroundStrategy() { LOGGER.info("# CachingPolicy.AROUND"); appManager.initCachingPolicy(CachingPolicy.AROUND); var userAccount2 = new UserAccount("002", "Jane", "She is a girl."); appManager.save(userAccount2); LOGGER.info(appManager.printCacheContent()); appManager.find("002"); LOGGER.info(appManager.printCacheContent()); userAccount2 = appManager.find("002"); userAccount2.setUserName("Jane G."); appManager.save(userAccount2); LOGGER.info(appManager.printCacheContent()); appManager.find("002"); LOGGER.info(appManager.printCacheContent()); appManager.find("002"); } /** * Read-through and write-behind. */ public void useReadThroughAndWriteBehindStrategy() { LOGGER.info("# CachingPolicy.BEHIND"); appManager.initCachingPolicy(CachingPolicy.BEHIND); var userAccount3 = new UserAccount("003", "Adam", "He likes food."); var userAccount4 = new UserAccount("004", "Rita", "She hates cats."); var userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard."); appManager.save(userAccount3); appManager.save(userAccount4); appManager.save(userAccount5); LOGGER.info(appManager.printCacheContent()); appManager.find("003"); LOGGER.info(appManager.printCacheContent()); UserAccount userAccount6 = new UserAccount("006", "Yasha", "She is an only child."); appManager.save(userAccount6); LOGGER.info(appManager.printCacheContent()); appManager.find("004"); LOGGER.info(appManager.printCacheContent()); } /** * Cache-Aside. */ public void useCacheAsideStategy() { LOGGER.info("# CachingPolicy.ASIDE"); appManager.initCachingPolicy(CachingPolicy.ASIDE); LOGGER.info(appManager.printCacheContent()); var userAccount3 = new UserAccount("003", "Adam", "He likes food."); var userAccount4 = new UserAccount("004", "Rita", "She hates cats."); var userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard."); appManager.save(userAccount3); appManager.save(userAccount4); appManager.save(userAccount5); LOGGER.info(appManager.printCacheContent()); appManager.find("003"); LOGGER.info(appManager.printCacheContent()); appManager.find("004"); LOGGER.info(appManager.printCacheContent()); } }
9,340
36.06746
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/AppManager.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.caching; import com.iluwatar.caching.database.DbManager; import java.util.Optional; import lombok.extern.slf4j.Slf4j; /** * AppManager helps to bridge the gap in communication between the main class * and the application's back-end. DB connection is initialized through this * class. The chosen caching strategy/policy is also initialized here. * Before the cache can be used, the size of the cache has to be set. * Depending on the chosen caching policy, AppManager will call the * appropriate function in the CacheStore class. */ @Slf4j public class AppManager { /** * Caching Policy. */ private CachingPolicy cachingPolicy; /** * Database Manager. */ private final DbManager dbManager; /** * Cache Store. */ private final CacheStore cacheStore; /** * Constructor. * * @param newDbManager database manager */ public AppManager(final DbManager newDbManager) { this.dbManager = newDbManager; this.cacheStore = new CacheStore(newDbManager); } /** * Developer/Tester is able to choose whether the application should use * MongoDB as its underlying data storage or a simple Java data structure * to (temporarily) store the data/objects during runtime. */ public void initDb() { dbManager.connect(); } /** * Initialize caching policy. * * @param policy is a {@link CachingPolicy} */ public void initCachingPolicy(final CachingPolicy policy) { cachingPolicy = policy; if (cachingPolicy == CachingPolicy.BEHIND) { Runtime.getRuntime().addShutdownHook(new Thread(cacheStore::flushCache)); } cacheStore.clearCache(); } /** * Find user account. * * @param userId String * @return {@link UserAccount} */ public UserAccount find(final String userId) { LOGGER.info("Trying to find {} in cache", userId); if (cachingPolicy == CachingPolicy.THROUGH || cachingPolicy == CachingPolicy.AROUND) { return cacheStore.readThrough(userId); } else if (cachingPolicy == CachingPolicy.BEHIND) { return cacheStore.readThroughWithWriteBackPolicy(userId); } else if (cachingPolicy == CachingPolicy.ASIDE) { return findAside(userId); } return null; } /** * Save user account. * * @param userAccount {@link UserAccount} */ public void save(final UserAccount userAccount) { LOGGER.info("Save record!"); if (cachingPolicy == CachingPolicy.THROUGH) { cacheStore.writeThrough(userAccount); } else if (cachingPolicy == CachingPolicy.AROUND) { cacheStore.writeAround(userAccount); } else if (cachingPolicy == CachingPolicy.BEHIND) { cacheStore.writeBehind(userAccount); } else if (cachingPolicy == CachingPolicy.ASIDE) { saveAside(userAccount); } } /** * Returns String. * * @return String */ public String printCacheContent() { return cacheStore.print(); } /** * Cache-Aside save user account helper. * * @param userAccount {@link UserAccount} */ private void saveAside(final UserAccount userAccount) { dbManager.updateDb(userAccount); cacheStore.invalidate(userAccount.getUserId()); } /** * Cache-Aside find user account helper. * * @param userId String * @return {@link UserAccount} */ private UserAccount findAside(final String userId) { return Optional.ofNullable(cacheStore.get(userId)) .or(() -> { Optional<UserAccount> userAccount = Optional.ofNullable(dbManager.readFromDb(userId)); userAccount.ifPresent(account -> cacheStore.set(userId, account)); return userAccount; }) .orElse(null); } }
5,021
30.584906
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/CacheStore.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.caching; import com.iluwatar.caching.database.DbManager; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; /** * The caching strategies are implemented in this class. */ @Slf4j public class CacheStore { /** * Cache capacity. */ private static final int CAPACITY = 3; /** * Lru cache see {@link LruCache}. */ private LruCache cache; /** * DbManager. */ private final DbManager dbManager; /** * Cache Store. * @param dataBaseManager {@link DbManager} */ public CacheStore(final DbManager dataBaseManager) { this.dbManager = dataBaseManager; initCapacity(CAPACITY); } /** * Init cache capacity. * @param capacity int */ public void initCapacity(final int capacity) { if (cache == null) { cache = new LruCache(capacity); } else { cache.setCapacity(capacity); } } /** * Get user account using read-through cache. * @param userId {@link String} * @return {@link UserAccount} */ public UserAccount readThrough(final String userId) { if (cache.contains(userId)) { LOGGER.info("# Found in Cache!"); return cache.get(userId); } LOGGER.info("# Not found in cache! Go to DB!!"); UserAccount userAccount = dbManager.readFromDb(userId); cache.set(userId, userAccount); return userAccount; } /** * Get user account using write-through cache. * @param userAccount {@link UserAccount} */ public void writeThrough(final UserAccount userAccount) { if (cache.contains(userAccount.getUserId())) { dbManager.updateDb(userAccount); } else { dbManager.writeToDb(userAccount); } cache.set(userAccount.getUserId(), userAccount); } /** * Get user account using write-around cache. * @param userAccount {@link UserAccount} */ public void writeAround(final UserAccount userAccount) { if (cache.contains(userAccount.getUserId())) { dbManager.updateDb(userAccount); // Cache data has been updated -- remove older cache.invalidate(userAccount.getUserId()); // version from cache. } else { dbManager.writeToDb(userAccount); } } /** * Get user account using read-through cache with write-back policy. * @param userId {@link String} * @return {@link UserAccount} */ public UserAccount readThroughWithWriteBackPolicy(final String userId) { if (cache.contains(userId)) { LOGGER.info("# Found in cache!"); return cache.get(userId); } LOGGER.info("# Not found in Cache!"); UserAccount userAccount = dbManager.readFromDb(userId); if (cache.isFull()) { LOGGER.info("# Cache is FULL! Writing LRU data to DB..."); UserAccount toBeWrittenToDb = cache.getLruData(); dbManager.upsertDb(toBeWrittenToDb); } cache.set(userId, userAccount); return userAccount; } /** * Set user account. * @param userAccount {@link UserAccount} */ public void writeBehind(final UserAccount userAccount) { if (cache.isFull() && !cache.contains(userAccount.getUserId())) { LOGGER.info("# Cache is FULL! Writing LRU data to DB..."); UserAccount toBeWrittenToDb = cache.getLruData(); dbManager.upsertDb(toBeWrittenToDb); } cache.set(userAccount.getUserId(), userAccount); } /** * Clears cache. */ public void clearCache() { if (cache != null) { cache.clear(); } } /** * Writes remaining content in the cache into the DB. */ public void flushCache() { LOGGER.info("# flushCache..."); Optional.ofNullable(cache) .map(LruCache::getCacheDataInListForm) .orElse(List.of()) .forEach(dbManager::updateDb); dbManager.disconnect(); } /** * Print user accounts. * @return {@link String} */ public String print() { return Optional.ofNullable(cache) .map(LruCache::getCacheDataInListForm) .orElse(List.of()) .stream() .map(userAccount -> userAccount.toString() + "\n") .collect(Collectors.joining("", "\n--CACHE CONTENT--\n", "----")); } /** * Delegate to backing cache store. * @param userId {@link String} * @return {@link UserAccount} */ public UserAccount get(final String userId) { return cache.get(userId); } /** * Delegate to backing cache store. * @param userId {@link String} * @param userAccount {@link UserAccount} */ public void set(final String userId, final UserAccount userAccount) { cache.set(userId, userAccount); } /** * Delegate to backing cache store. * @param userId {@link String} */ public void invalidate(final String userId) { cache.invalidate(userId); } }
6,060
27.725118
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/LruCache.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.caching; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; /** * Data structure/implementation of the application's cache. The data structure * consists of a hash table attached with a doubly linked-list. The linked-list * helps in capturing and maintaining the LRU data in the cache. When a data is * queried (from the cache), added (to the cache), or updated, the data is * moved to the front of the list to depict itself as the most-recently-used * data. The LRU data is always at the end of the list. */ @Slf4j public class LruCache { /** * Static class Node. */ static class Node { /** * user id. */ private final String userId; /** * User Account. */ private UserAccount userAccount; /** * previous. */ private Node previous; /** * next. */ private Node next; /** * Node definition. * * @param id String * @param account {@link UserAccount} */ Node(final String id, final UserAccount account) { this.userId = id; this.userAccount = account; } } /** * Capacity of Cache. */ private int capacity; /** * Cache {@link HashMap}. */ private Map<String, Node> cache = new HashMap<>(); /** * Head. */ private Node head; /** * End. */ private Node end; /** * Constructor. * * @param cap Integer. */ public LruCache(final int cap) { this.capacity = cap; } /** * Get user account. * * @param userId String * @return {@link UserAccount} */ public UserAccount get(final String userId) { if (cache.containsKey(userId)) { var node = cache.get(userId); remove(node); setHead(node); return node.userAccount; } return null; } /** * Remove node from linked list. * * @param node {@link Node} */ public void remove(final Node node) { if (node.previous != null) { node.previous.next = node.next; } else { head = node.next; } if (node.next != null) { node.next.previous = node.previous; } else { end = node.previous; } } /** * Move node to the front of the list. * * @param node {@link Node} */ public void setHead(final Node node) { node.next = head; node.previous = null; if (head != null) { head.previous = node; } head = node; if (end == null) { end = head; } } /** * Set user account. * * @param userAccount {@link UserAccount} * @param userId {@link String} */ public void set(final String userId, final UserAccount userAccount) { if (cache.containsKey(userId)) { var old = cache.get(userId); old.userAccount = userAccount; remove(old); setHead(old); } else { var newNode = new Node(userId, userAccount); if (cache.size() >= capacity) { LOGGER.info("# Cache is FULL! Removing {} from cache...", end.userId); cache.remove(end.userId); // remove LRU data from cache. remove(end); setHead(newNode); } else { setHead(newNode); } cache.put(userId, newNode); } } /** * Check if Cache contains the userId. * * @param userId {@link String} * @return boolean */ public boolean contains(final String userId) { return cache.containsKey(userId); } /** * Invalidate cache for user. * * @param userId {@link String} */ public void invalidate(final String userId) { var toBeRemoved = cache.remove(userId); if (toBeRemoved != null) { LOGGER.info("# {} has been updated! " + "Removing older version from cache...", userId); remove(toBeRemoved); } } /** * Check if the cache is full. * @return boolean */ public boolean isFull() { return cache.size() >= capacity; } /** * Get LRU data. * * @return {@link UserAccount} */ public UserAccount getLruData() { return end.userAccount; } /** * Clear cache. */ public void clear() { head = null; end = null; cache.clear(); } /** * Returns cache data in list form. * * @return {@link List} */ public List<UserAccount> getCacheDataInListForm() { var listOfCacheData = new ArrayList<UserAccount>(); var temp = head; while (temp != null) { listOfCacheData.add(temp.userAccount); temp = temp.next; } return listOfCacheData; } /** * Set cache capacity. * * @param newCapacity int */ public void setCapacity(final int newCapacity) { if (capacity > newCapacity) { // Behavior can be modified to accommodate // for decrease in cache size. For now, we'll clear(); // just clear the cache. } else { this.capacity = newCapacity; } } }
6,218
22.827586
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/CachingPolicy.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.caching; import lombok.AllArgsConstructor; import lombok.Getter; /** * Enum class containing the four caching strategies implemented in the pattern. */ @AllArgsConstructor @Getter public enum CachingPolicy { /** * Through. */ THROUGH("through"), /** * AROUND. */ AROUND("around"), /** * BEHIND. */ BEHIND("behind"), /** * ASIDE. */ ASIDE("aside"); /** * Policy value. */ private final String policy; }
1,762
29.396552
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/UserAccount.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.caching; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Entity class (stored in cache and DB) used in the application. */ @Data @AllArgsConstructor @ToString @EqualsAndHashCode public class UserAccount { /** * User Id. */ private String userId; /** * User Name. */ private String userName; /** * Additional Info. */ private String additionalInfo; }
1,758
32.188679
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/database/package-info.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. */ /** * Database classes. */ package com.iluwatar.caching.database;
1,352
45.655172
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/database/DbManager.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.caching.database; import com.iluwatar.caching.UserAccount; /** * <p>DBManager handles the communication with the underlying data store i.e. * Database. It contains the implemented methods for querying, inserting, * and updating data. MongoDB was used as the database for the application.</p> */ public interface DbManager { /** * Connect to DB. */ void connect(); /** * Disconnect from DB. */ void disconnect(); /** * Read from DB. * * @param userId {@link String} * @return {@link UserAccount} */ UserAccount readFromDb(String userId); /** * Write to DB. * * @param userAccount {@link UserAccount} * @return {@link UserAccount} */ UserAccount writeToDb(UserAccount userAccount); /** * Update record. * * @param userAccount {@link UserAccount} * @return {@link UserAccount} */ UserAccount updateDb(UserAccount userAccount); /** * Update record or Insert if not exists. * * @param userAccount {@link UserAccount} * @return {@link UserAccount} */ UserAccount upsertDb(UserAccount userAccount); }
2,406
30.25974
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/database/VirtualDb.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.caching.database; import com.iluwatar.caching.UserAccount; import java.util.HashMap; import java.util.Map; /** * Implementation of DatabaseManager. * implements base methods to work with hashMap as database. */ public class VirtualDb implements DbManager { /** * Virtual DataBase. */ private Map<String, UserAccount> db; /** * Creates new HashMap. */ @Override public void connect() { db = new HashMap<>(); } @Override public void disconnect() { db = null; } /** * Read from Db. * * @param userId {@link String} * @return {@link UserAccount} */ @Override public UserAccount readFromDb(final String userId) { if (db.containsKey(userId)) { return db.get(userId); } return null; } /** * Write to DB. * * @param userAccount {@link UserAccount} * @return {@link UserAccount} */ @Override public UserAccount writeToDb(final UserAccount userAccount) { db.put(userAccount.getUserId(), userAccount); return userAccount; } /** * Update reecord in DB. * * @param userAccount {@link UserAccount} * @return {@link UserAccount} */ @Override public UserAccount updateDb(final UserAccount userAccount) { return writeToDb(userAccount); } /** * Update. * * @param userAccount {@link UserAccount} * @return {@link UserAccount} */ @Override public UserAccount upsertDb(final UserAccount userAccount) { return updateDb(userAccount); } }
2,796
26.421569
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/database/DbManagerFactory.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.caching.database; /** * Creates the database connection accroding the input parameter. */ public final class DbManagerFactory { /** * Private constructor. */ private DbManagerFactory() { } /** * Init database. * * @param isMongo boolean * @return {@link DbManager} */ public static DbManager initDb(final boolean isMongo) { if (isMongo) { return new MongoDb(); } return new VirtualDb(); } }
1,751
34.04
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/database/MongoDb.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.caching.database; import static com.iluwatar.caching.constants.CachingConstants.ADD_INFO; import static com.iluwatar.caching.constants.CachingConstants.USER_ACCOUNT; import static com.iluwatar.caching.constants.CachingConstants.USER_ID; import static com.iluwatar.caching.constants.CachingConstants.USER_NAME; import com.iluwatar.caching.UserAccount; import com.iluwatar.caching.constants.CachingConstants; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; import lombok.extern.slf4j.Slf4j; import org.bson.Document; /** * Implementation of DatabaseManager. * implements base methods to work with MongoDb. */ @Slf4j public class MongoDb implements DbManager { private static final String DATABASE_NAME = "admin"; private static final String MONGO_USER = "root"; private static final String MONGO_PASSWORD = "rootpassword"; private MongoClient client; private MongoDatabase db; void setDb(MongoDatabase db) { this.db = db; } /** * Connect to Db. Check th connection */ @Override public void connect() { MongoCredential mongoCredential = MongoCredential.createCredential(MONGO_USER, DATABASE_NAME, MONGO_PASSWORD.toCharArray()); MongoClientOptions options = MongoClientOptions.builder().build(); client = new MongoClient(new ServerAddress(), mongoCredential, options); db = client.getDatabase(DATABASE_NAME); } @Override public void disconnect() { client.close(); } /** * Read data from DB. * * @param userId {@link String} * @return {@link UserAccount} */ @Override public UserAccount readFromDb(final String userId) { var iterable = db .getCollection(CachingConstants.USER_ACCOUNT) .find(new Document(USER_ID, userId)); if (iterable.first() == null) { return null; } Document doc = iterable.first(); if (doc != null) { String userName = doc.getString(USER_NAME); String appInfo = doc.getString(ADD_INFO); return new UserAccount(userId, userName, appInfo); } else { return null; } } /** * Write data to DB. * * @param userAccount {@link UserAccount} * @return {@link UserAccount} */ @Override public UserAccount writeToDb(final UserAccount userAccount) { db.getCollection(USER_ACCOUNT).insertOne( new Document(USER_ID, userAccount.getUserId()) .append(USER_NAME, userAccount.getUserName()) .append(ADD_INFO, userAccount.getAdditionalInfo()) ); return userAccount; } /** * Update DB. * * @param userAccount {@link UserAccount} * @return {@link UserAccount} */ @Override public UserAccount updateDb(final UserAccount userAccount) { Document id = new Document(USER_ID, userAccount.getUserId()); Document dataSet = new Document(USER_NAME, userAccount.getUserName()) .append(ADD_INFO, userAccount.getAdditionalInfo()); db.getCollection(CachingConstants.USER_ACCOUNT) .updateOne(id, new Document("$set", dataSet)); return userAccount; } /** * Update data if exists. * * @param userAccount {@link UserAccount} * @return {@link UserAccount} */ @Override public UserAccount upsertDb(final UserAccount userAccount) { String userId = userAccount.getUserId(); String userName = userAccount.getUserName(); String additionalInfo = userAccount.getAdditionalInfo(); db.getCollection(CachingConstants.USER_ACCOUNT).updateOne( new Document(USER_ID, userId), new Document("$set", new Document(USER_ID, userId) .append(USER_NAME, userName) .append(ADD_INFO, additionalInfo) ), new UpdateOptions().upsert(true) ); return userAccount; } }
5,337
33.217949
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.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.caching.constants; /** * Constant class for defining constants. */ public final class CachingConstants { /** * User Account. */ public static final String USER_ACCOUNT = "user_accounts"; /** * User ID. */ public static final String USER_ID = "userID"; /** * User Name. */ public static final String USER_NAME = "userName"; /** * Additional Info. */ public static final String ADD_INFO = "additionalInfo"; /** * Constructor. */ private CachingConstants() { } }
1,821
32.740741
140
java
java-design-patterns
java-design-patterns-master/caching/src/main/java/com/iluwatar/caching/constants/package-info.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. */ /** * Constants. */ package com.iluwatar.caching.constants;
1,346
45.448276
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.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.threadpool; import static java.time.Duration.ofMillis; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTimeout; import java.util.ArrayList; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; /** * Date: 12/30/15 - 18:22 PM Test for Tasks using a Thread Pool * * @param <T> Type of Task * @author Jeroen Meulemeester */ public abstract class TaskTest<T extends Task> { /** * The number of tasks used during the concurrency test */ private static final int TASK_COUNT = 128 * 1024; /** * The number of threads used during the concurrency test */ private static final int THREAD_COUNT = 8; /** * The task factory, used to create new test items */ private final IntFunction<T> factory; /** * The expected time needed to run the task 1 single time, in milli seconds */ private final int expectedExecutionTime; /** * Create a new test instance * * @param factory The task factory, used to create new test items * @param expectedExecutionTime The expected time needed to run the task 1 time, in milli seconds */ public TaskTest(final IntFunction<T> factory, final int expectedExecutionTime) { this.factory = factory; this.expectedExecutionTime = expectedExecutionTime; } /** * Verify if the generated id is unique for each task, even if the tasks are created in separate * threads */ @Test void testIdGeneration() throws Exception { assertTimeout(ofMillis(10000), () -> { final var service = Executors.newFixedThreadPool(THREAD_COUNT); final var tasks = IntStream.range(0, TASK_COUNT) .<Callable<Integer>>mapToObj(i -> () -> factory.apply(1).getId()) .collect(Collectors.toCollection(ArrayList::new)); final var ids = service.invokeAll(tasks) .stream() .map(TaskTest::get) .filter(Objects::nonNull) .toList(); service.shutdownNow(); final var uniqueIdCount = ids.stream() .distinct() .count(); assertEquals(TASK_COUNT, ids.size()); assertEquals(TASK_COUNT, uniqueIdCount); }); } /** * Verify if the time per execution of a task matches the actual time required to execute the task * a given number of times */ @Test void testTimeMs() { for (var i = 0; i < 10; i++) { assertEquals(this.expectedExecutionTime * i, this.factory.apply(i).getTimeMs()); } } /** * Verify if the task has some sort of {@link T#toString()}, different from 'null' */ @Test void testToString() { assertNotNull(this.factory.apply(0).toString()); } /** * Extract the result from a future or returns 'null' when an exception occurred * * @param future The future we want the result from * @param <O> The result type * @return The result or 'null' when a checked exception occurred */ private static <O> O get(Future<O> future) { try { return future.get(); } catch (InterruptedException | ExecutionException e) { return null; } } }
4,761
31.394558
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.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.threadpool; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; /** * Date: 12/30/15 - 18:21 PM * * @author Jeroen Meulemeester */ class WorkerTest { /** * Verify if a worker does the actual job */ @Test void testRun() { final var task = mock(Task.class); final var worker = new Worker(task); verifyNoMoreInteractions(task); worker.run(); verify(task).getTimeMs(); verifyNoMoreInteractions(task); } }
1,878
33.796296
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/test/java/com/iluwatar/threadpool/CoffeeMakingTaskTest.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.threadpool; /** * Date: 12/30/15 - 18:23 PM * * @author Jeroen Meulemeester */ class CoffeeMakingTaskTest extends TaskTest<CoffeeMakingTask> { /** * Create a new test instance */ public CoffeeMakingTaskTest() { super(CoffeeMakingTask::new, 100); } }
1,578
36.595238
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/test/java/com/iluwatar/threadpool/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.threadpool; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test * * @author ilkka */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,598
36.186047
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/test/java/com/iluwatar/threadpool/PotatoPeelingTaskTest.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.threadpool; /** * Date: 12/30/15 - 18:23 PM * * @author Jeroen Meulemeester */ class PotatoPeelingTaskTest extends TaskTest<PotatoPeelingTask> { /** * Create a new test instance */ public PotatoPeelingTaskTest() { super(PotatoPeelingTask::new, 200); } }
1,581
37.585366
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/main/java/com/iluwatar/threadpool/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.threadpool; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import lombok.extern.slf4j.Slf4j; /** * Thread Pool pattern is where a number of threads are created to perform a number of tasks, which * are usually organized in a queue. The results from the tasks being executed might also be placed * in a queue, or the tasks might return no result. Typically, there are many more tasks than * threads. As soon as a thread completes its task, it will request the next task from the queue * until all tasks have been completed. The thread can then terminate, or sleep until there are new * tasks available. * * <p>In this example we create a list of tasks presenting work to be done. Each task is then * wrapped into a {@link Worker} object that implements {@link Runnable}. We create an {@link * ExecutorService} with fixed number of threads (Thread Pool) and use them to execute the {@link * Worker}s. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { LOGGER.info("Program started"); // Create a list of tasks to be executed var tasks = List.of( new PotatoPeelingTask(3), new PotatoPeelingTask(6), new CoffeeMakingTask(2), new CoffeeMakingTask(6), new PotatoPeelingTask(4), new CoffeeMakingTask(2), new PotatoPeelingTask(4), new CoffeeMakingTask(9), new PotatoPeelingTask(3), new CoffeeMakingTask(2), new PotatoPeelingTask(4), new CoffeeMakingTask(2), new CoffeeMakingTask(7), new PotatoPeelingTask(4), new PotatoPeelingTask(5)); // Creates a thread pool that reuses a fixed number of threads operating off a shared // unbounded queue. At any point, at most nThreads threads will be active processing // tasks. If additional tasks are submitted when all threads are active, they will wait // in the queue until a thread is available. var executor = Executors.newFixedThreadPool(3); // Allocate new worker for each task // The worker is executed when a thread becomes // available in the thread pool tasks.stream().map(Worker::new).forEach(executor::execute); // All tasks were executed, now shutdown executor.shutdown(); while (!executor.isTerminated()) { Thread.yield(); } LOGGER.info("Program finished"); } }
3,788
39.741935
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/main/java/com/iluwatar/threadpool/CoffeeMakingTask.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.threadpool; /** * CoffeeMakingTask is a concrete task. */ public class CoffeeMakingTask extends Task { private static final int TIME_PER_CUP = 100; public CoffeeMakingTask(int numCups) { super(numCups * TIME_PER_CUP); } @Override public String toString() { return String.format("%s %s", this.getClass().getSimpleName(), super.toString()); } }
1,674
37.953488
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/main/java/com/iluwatar/threadpool/Task.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.threadpool; import java.util.concurrent.atomic.AtomicInteger; /** * Abstract base class for tasks. */ public abstract class Task { private static final AtomicInteger ID_GENERATOR = new AtomicInteger(); private final int id; private final int timeMs; public Task(final int timeMs) { this.id = ID_GENERATOR.incrementAndGet(); this.timeMs = timeMs; } public int getId() { return id; } public int getTimeMs() { return timeMs; } @Override public String toString() { return String.format("id=%d timeMs=%d", id, timeMs); } }
1,877
31.947368
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/main/java/com/iluwatar/threadpool/PotatoPeelingTask.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.threadpool; /** * PotatoPeelingTask is a concrete task. */ public class PotatoPeelingTask extends Task { private static final int TIME_PER_POTATO = 200; public PotatoPeelingTask(int numPotatoes) { super(numPotatoes * TIME_PER_POTATO); } @Override public String toString() { return String.format("%s %s", this.getClass().getSimpleName(), super.toString()); } }
1,691
38.348837
140
java
java-design-patterns
java-design-patterns-master/thread-pool/src/main/java/com/iluwatar/threadpool/Worker.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.threadpool; import lombok.extern.slf4j.Slf4j; /** * Worker implements {@link Runnable} and thus can be executed by {@link * java.util.concurrent.ExecutorService}. */ @Slf4j public class Worker implements Runnable { private final Task task; public Worker(final Task task) { this.task = task; } @Override public void run() { LOGGER.info("{} processing {}", Thread.currentThread().getName(), task.toString()); try { Thread.sleep(task.getTimeMs()); } catch (InterruptedException e) { e.printStackTrace(); } } }
1,864
34.865385
140
java
java-design-patterns
java-design-patterns-master/repository/src/test/java/com/iluwatar/repository/RepositoryTest.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.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import javax.annotation.Resource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query * by {@link org.springframework.data.jpa.domain.Specification} are also test. */ @ExtendWith(SpringExtension.class) @SpringBootTest(properties = {"locations=classpath:applicationContext.xml"}) class RepositoryTest { @Resource private PersonRepository repository; private final Person peter = new Person("Peter", "Sagan", 17); private final Person nasta = new Person("Nasta", "Kuzminova", 25); private final Person john = new Person("John", "lawrence", 35); private final Person terry = new Person("Terry", "Law", 36); private final List<Person> persons = List.of(peter, nasta, john, terry); /** * Prepare data for test */ @BeforeEach void setup() { repository.saveAll(persons); } @Test void testFindAll() { var actuals = repository.findAll(); assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals)); } @Test void testSave() { var terry = repository.findByName("Terry"); terry.setSurname("Lee"); terry.setAge(47); repository.save(terry); terry = repository.findByName("Terry"); assertEquals(terry.getSurname(), "Lee"); assertEquals(47, terry.getAge()); } @Test void testDelete() { var terry = repository.findByName("Terry"); repository.delete(terry); assertEquals(3, repository.count()); assertNull(repository.findByName("Terry")); } @Test void testCount() { assertEquals(4, repository.count()); } @Test void testFindAllByAgeBetweenSpec() { var persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); assertEquals(3, persons.size()); assertTrue(persons.stream().allMatch(item -> item.getAge() > 20 && item.getAge() < 40)); } @Test void testFindOneByNameEqualSpec() { var actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); assertTrue(actual.isPresent()); assertEquals(terry, actual.get()); } @AfterEach void cleanup() { repository.deleteAll(); } }
3,948
32.184874
140
java
java-design-patterns
java-design-patterns-master/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.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.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import javax.annotation.Resource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query * by {@link org.springframework.data.jpa.domain.Specification} are also test. */ @ExtendWith(SpringExtension.class) @SpringBootTest(classes = {AppConfig.class}) class AnnotationBasedRepositoryTest { @Resource private PersonRepository repository; private final Person peter = new Person("Peter", "Sagan", 17); private final Person nasta = new Person("Nasta", "Kuzminova", 25); private final Person john = new Person("John", "lawrence", 35); private final Person terry = new Person("Terry", "Law", 36); private final List<Person> persons = List.of(peter, nasta, john, terry); /** * Prepare data for test */ @BeforeEach void setup() { repository.saveAll(persons); } @Test void testFindAll() { var actuals = repository.findAll(); assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals)); } @Test void testSave() { var terry = repository.findByName("Terry"); terry.setSurname("Lee"); terry.setAge(47); repository.save(terry); terry = repository.findByName("Terry"); assertEquals(terry.getSurname(), "Lee"); assertEquals(47, terry.getAge()); } @Test void testDelete() { var terry = repository.findByName("Terry"); repository.delete(terry); assertEquals(3, repository.count()); assertNull(repository.findByName("Terry")); } @Test void testCount() { assertEquals(4, repository.count()); } @Test void testFindAllByAgeBetweenSpec() { var persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); assertEquals(3, persons.size()); assertTrue(persons.stream().allMatch((item) -> item.getAge() > 20 && item.getAge() < 40)); } @Test void testFindOneByNameEqualSpec() { var actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); assertTrue(actual.isPresent()); assertEquals(terry, actual.get()); } @AfterEach void cleanup() { repository.deleteAll(); } }
3,933
32.058824
140
java
java-design-patterns
java-design-patterns-master/repository/src/test/java/com/iluwatar/repository/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.repository; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that Repository example runs without errors. */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,612
38.341463
140
java
java-design-patterns
java-design-patterns-master/repository/src/test/java/com/iluwatar/repository/AppConfigTest.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.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; /** * This case is Just for test the Annotation Based configuration */ @ExtendWith(SpringExtension.class) @SpringBootTest(classes = {AppConfig.class}) class AppConfigTest { @Autowired DataSource dataSource; /** * Test for bean instance */ @Test void testDataSource() { assertNotNull(dataSource); } /** * Test for correct query execution */ @Test @Transactional void testQuery() throws SQLException { var resultSet = dataSource.getConnection().createStatement().executeQuery("SELECT 1"); var expected = "1"; String result = null; while (resultSet.next()) { result = resultSet.getString(1); } assertEquals(expected, result); } }
2,549
33.931507
140
java
java-design-patterns
java-design-patterns-master/repository/src/main/java/com/iluwatar/repository/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.repository; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Repository pattern mediates between the domain and data mapping layers using a collection-like * interface for accessing domain objects. A system with complex domain model often benefits from a * layer that isolates domain objects from the details of the database access code and in such * systems it can be worthwhile to build another layer of abstraction over the mapping layer where * query construction code is concentrated. This becomes more important when there are a large * number of domain classes or heavy querying. In these cases particularly, adding this layer helps * minimize duplicate query logic. * * <p>In this example we utilize Spring Data to automatically generate a repository for us from the * {@link Person} domain object. Using the {@link PersonRepository} we perform CRUD operations on * the entity, moreover, the query by {@link org.springframework.data.jpa.domain.Specification} are * also performed. Underneath we have configured in-memory H2 database for which schema is created * and dropped on each run. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var context = new ClassPathXmlApplicationContext("applicationContext.xml"); var repository = context.getBean(PersonRepository.class); var peter = new Person("Peter", "Sagan", 17); var nasta = new Person("Nasta", "Kuzminova", 25); var john = new Person("John", "lawrence", 35); var terry = new Person("Terry", "Law", 36); // Add new Person records repository.save(peter); repository.save(nasta); repository.save(john); repository.save(terry); // Count Person records LOGGER.info("Count Person records: {}", repository.count()); // Print all records var persons = (List<Person>) repository.findAll(); persons.stream().map(Person::toString).forEach(LOGGER::info); // Update Person nasta.setName("Barbora"); nasta.setSurname("Spotakova"); repository.save(nasta); repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p)); // Remove record from Person repository.deleteById(2L); // count records LOGGER.info("Count Person records: {}", repository.count()); // find by name repository .findOne(new PersonSpecifications.NameEqualSpec("John")) .ifPresent(p -> LOGGER.info("Find by John is {}", p)); // find by age persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); LOGGER.info("Find Person with age between 20,40: "); persons.stream().map(Person::toString).forEach(LOGGER::info); repository.deleteAll(); context.close(); } }
4,184
38.11215
140
java
java-design-patterns
java-design-patterns-master/repository/src/main/java/com/iluwatar/repository/AppConfig.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.repository; import java.util.List; import java.util.Properties; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.apache.commons.dbcp.BasicDataSource; import org.hibernate.jpa.HibernatePersistenceProvider; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; /** * This is the same example as in {@link App} but with annotations based configuration for Spring. */ @EnableJpaRepositories @SpringBootConfiguration @Slf4j public class AppConfig { /** * Creation of H2 db. * * @return A new Instance of DataSource */ @Bean(destroyMethod = "close") public DataSource dataSource() { var basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName("org.h2.Driver"); basicDataSource.setUrl("jdbc:h2:~/databases/person"); basicDataSource.setUsername("sa"); basicDataSource.setPassword("sa"); return basicDataSource; } /** * Factory to create a especific instance of Entity Manager. */ @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { var entityManager = new LocalContainerEntityManagerFactoryBean(); entityManager.setDataSource(dataSource()); entityManager.setPackagesToScan("com.iluwatar"); entityManager.setPersistenceProvider(new HibernatePersistenceProvider()); entityManager.setJpaProperties(jpaProperties()); return entityManager; } /** * Properties for Jpa. */ private static Properties jpaProperties() { var properties = new Properties(); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); return properties; } /** * Get transaction manager. */ @Bean public JpaTransactionManager transactionManager() { var transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var context = new AnnotationConfigApplicationContext(AppConfig.class); var repository = context.getBean(PersonRepository.class); var peter = new Person("Peter", "Sagan", 17); var nasta = new Person("Nasta", "Kuzminova", 25); var john = new Person("John", "lawrence", 35); var terry = new Person("Terry", "Law", 36); // Add new Person records repository.save(peter); repository.save(nasta); repository.save(john); repository.save(terry); // Count Person records LOGGER.info("Count Person records: {}", repository.count()); // Print all records var persons = (List<Person>) repository.findAll(); persons.stream().map(Person::toString).forEach(LOGGER::info); // Update Person nasta.setName("Barbora"); nasta.setSurname("Spotakova"); repository.save(nasta); repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p)); // Remove record from Person repository.deleteById(2L); // count records LOGGER.info("Count Person records: {}", repository.count()); // find by name repository .findOne(new PersonSpecifications.NameEqualSpec("John")) .ifPresent(p -> LOGGER.info("Find by John is {}", p)); // find by age persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); LOGGER.info("Find Person with age between 20,40: "); persons.stream().map(Person::toString).forEach(LOGGER::info); context.close(); } }
5,239
33.473684
140
java
java-design-patterns
java-design-patterns-master/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.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.repository; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.data.jpa.domain.Specification; /** * Helper class, includes vary Specification as the abstraction of sql query criteria. */ public class PersonSpecifications { /** * Specifications stating the Between (From - To) Age Specification. */ public static class AgeBetweenSpec implements Specification<Person> { private final int from; private final int to; public AgeBetweenSpec(int from, int to) { this.from = from; this.to = to; } @Override public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.between(root.get("age"), from, to); } } /** * Name specification. */ public static class NameEqualSpec implements Specification<Person> { public final String name; public NameEqualSpec(String name) { this.name = name; } /** * Get predicate. */ public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.equal(root.get("name"), this.name); } } }
2,591
31.810127
140
java
java-design-patterns
java-design-patterns-master/repository/src/main/java/com/iluwatar/repository/Person.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.repository; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; /** * Person entity. */ @ToString @EqualsAndHashCode @Setter @Getter @Entity @NoArgsConstructor public class Person { @Id @GeneratedValue private Long id; private String name; private String surname; private int age; /** * Constructor. */ public Person(String name, String surname, int age) { this.name = name; this.surname = surname; this.age = age; } }
1,952
29.515625
140
java
java-design-patterns
java-design-patterns-master/repository/src/main/java/com/iluwatar/repository/PersonRepository.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.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * Person repository. */ @Repository public interface PersonRepository extends CrudRepository<Person, Long>, JpaSpecificationExecutor<Person> { Person findByName(String name); List<Person> findAll(); }
1,741
39.511628
140
java
java-design-patterns
java-design-patterns-master/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.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.reader.writer.lock; import static org.junit.jupiter.api.Assertions.assertTrue; import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author hongshuwei@gmail.com */ class ReaderAndWriterTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } private static final Logger LOGGER = LoggerFactory.getLogger(ReaderAndWriterTest.class); /** * Verify reader and writer can only get the lock to read and write orderly */ @Test void testReadAndWrite() throws Exception { var lock = new ReaderWriterLock(); var reader1 = new Reader("Reader 1", lock.readLock()); var writer1 = new Writer("Writer 1", lock.writeLock()); var executeService = Executors.newFixedThreadPool(2); executeService.submit(reader1); // Let reader1 execute first Thread.sleep(150); executeService.submit(writer1); executeService.shutdown(); try { executeService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.error("Error waiting for ExecutorService shutdown", e); } assertTrue(appender.logContains("Reader 1 begin")); assertTrue(appender.logContains("Reader 1 finish")); assertTrue(appender.logContains("Writer 1 begin")); assertTrue(appender.logContains("Writer 1 finish")); } /** * Verify reader and writer can only get the lock to read and write orderly */ @Test void testWriteAndRead() throws Exception { var executeService = Executors.newFixedThreadPool(2); var lock = new ReaderWriterLock(); var reader1 = new Reader("Reader 1", lock.readLock()); var writer1 = new Writer("Writer 1", lock.writeLock()); executeService.submit(writer1); // Let writer1 execute first Thread.sleep(150); executeService.submit(reader1); executeService.shutdown(); try { executeService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.error("Error waiting for ExecutorService shutdown", e); } assertTrue(appender.logContains("Writer 1 begin")); assertTrue(appender.logContains("Writer 1 finish")); assertTrue(appender.logContains("Reader 1 begin")); assertTrue(appender.logContains("Reader 1 finish")); } }
3,913
32.169492
140
java
java-design-patterns
java-design-patterns-master/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.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.reader.writer.lock; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.spy; import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author hongshuwei@gmail.com */ class ReaderTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(Reader.class); } @AfterEach void tearDown() { appender.stop(); } private static final Logger LOGGER = LoggerFactory.getLogger(ReaderTest.class); /** * Verify that multiple readers can get the read lock concurrently */ @Test void testRead() throws Exception { var executeService = Executors.newFixedThreadPool(2); var lock = new ReaderWriterLock(); var reader1 = spy(new Reader("Reader 1", lock.readLock())); var reader2 = spy(new Reader("Reader 2", lock.readLock())); executeService.submit(reader1); Thread.sleep(150); executeService.submit(reader2); executeService.shutdown(); try { executeService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.error("Error waiting for ExecutorService shutdown", e); } // Read operation will hold the read lock 250 milliseconds, so here we prove that multiple reads // can be performed in the same time. assertTrue(appender.logContains("Reader 1 begin")); assertTrue(appender.logContains("Reader 2 begin")); assertTrue(appender.logContains("Reader 1 finish")); assertTrue(appender.logContains("Reader 2 finish")); } }
3,108
33.932584
140
java
java-design-patterns
java-design-patterns-master/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.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.reader.writer.lock; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.spy; import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author hongshuwei@gmail.com */ class WriterTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(Writer.class); } @AfterEach void tearDown() { appender.stop(); } private static final Logger LOGGER = LoggerFactory.getLogger(WriterTest.class); /** * Verify that multiple writers will get the lock in order. */ @Test void testWrite() throws Exception { var executeService = Executors.newFixedThreadPool(2); var lock = new ReaderWriterLock(); var writer1 = spy(new Writer("Writer 1", lock.writeLock())); var writer2 = spy(new Writer("Writer 2", lock.writeLock())); executeService.submit(writer1); // Let write1 execute first Thread.sleep(150); executeService.submit(writer2); executeService.shutdown(); try { executeService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.error("Error waiting for ExecutorService shutdown", e); } // Write operation will hold the write lock 250 milliseconds, so here we verify that when two // writer execute concurrently, the second writer can only writes only when the first one is // finished. assertTrue(appender.logContains("Writer 1 begin")); assertTrue(appender.logContains("Writer 1 finish")); assertTrue(appender.logContains("Writer 2 begin")); assertTrue(appender.logContains("Writer 2 finish")); } }
3,204
34.611111
140
java
java-design-patterns
java-design-patterns-master/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/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.reader.writer.lock; 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,587
36.809524
140
java