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/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.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.event.sourcing.state; import com.iluwatar.event.sourcing.domain.Account; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * This is the static accounts map holder class. This class holds the state of the accounts. * * <p>Created by Serdar Hamzaogullari on 06.08.2017. */ public class AccountAggregate { private static Map<Integer, Account> accounts = new HashMap<>(); private AccountAggregate() { } /** * Put account. * * @param account the account */ public static void putAccount(Account account) { accounts.put(account.getAccountNo(), account); } /** * Gets account. * * @param accountNo the account no * @return the copy of the account or null if not found */ public static Account getAccount(int accountNo) { return Optional.of(accountNo) .map(accounts::get) .map(Account::copy) .orElse(null); } /** * Reset state. */ public static void resetState() { accounts = new HashMap<>(); } }
2,328
30.90411
140
java
java-design-patterns
java-design-patterns-master/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.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.event.sourcing.event; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.iluwatar.event.sourcing.state.AccountAggregate; import java.math.BigDecimal; import java.util.Optional; import lombok.Getter; /** * This is the class that implements money transfer event. Holds the necessary info for a money * transfer event. Implements the process function that finds the event-related domain objects and * calls the related domain object's handle event functions * * <p>Created by Serdar Hamzaogullari on 06.08.2017. */ @Getter public class MoneyTransferEvent extends DomainEvent { private final BigDecimal money; private final int accountNoFrom; private final int accountNoTo; /** * Instantiates a new Money transfer event. * * @param sequenceId the sequence id * @param createdTime the created time * @param money the money * @param accountNoFrom the account no from * @param accountNoTo the account no to */ @JsonCreator public MoneyTransferEvent(@JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, @JsonProperty("money") BigDecimal money, @JsonProperty("accountNoFrom") int accountNoFrom, @JsonProperty("accountNoTo") int accountNoTo) { super(sequenceId, createdTime, "MoneyTransferEvent"); this.money = money; this.accountNoFrom = accountNoFrom; this.accountNoTo = accountNoTo; } @Override public void process() { var accountFrom = Optional.ofNullable(AccountAggregate.getAccount(accountNoFrom)) .orElseThrow(() -> new RuntimeException("Account not found " + accountNoFrom)); var accountTo = Optional.ofNullable(AccountAggregate.getAccount(accountNoTo)) .orElseThrow(() -> new RuntimeException("Account not found " + accountNoTo)); accountFrom.handleTransferFromEvent(this); accountTo.handleTransferToEvent(this); } }
3,263
40.846154
140
java
java-design-patterns
java-design-patterns-master/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.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.event.sourcing.event; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.iluwatar.event.sourcing.state.AccountAggregate; import java.math.BigDecimal; import java.util.Optional; import lombok.Getter; /** * This is the class that implements money deposit event. Holds the necessary info for a money * deposit event. Implements the process function that finds the event-related domain objects and * calls the related domain object's handle event functions * * <p>Created by Serdar Hamzaogullari on 06.08.2017. */ @Getter public class MoneyDepositEvent extends DomainEvent { private final BigDecimal money; private final int accountNo; /** * Instantiates a new Money deposit event. * * @param sequenceId the sequence id * @param createdTime the created time * @param accountNo the account no * @param money the money */ @JsonCreator public MoneyDepositEvent(@JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, @JsonProperty("accountNo") int accountNo, @JsonProperty("money") BigDecimal money) { super(sequenceId, createdTime, "MoneyDepositEvent"); this.money = money; this.accountNo = accountNo; } @Override public void process() { var account = Optional.ofNullable(AccountAggregate.getAccount(accountNo)) .orElseThrow(() -> new RuntimeException("Account not found")); account.handleEvent(this); } }
2,807
38.549296
140
java
java-design-patterns
java-design-patterns-master/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.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.event.sourcing.event; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.iluwatar.event.sourcing.domain.Account; import com.iluwatar.event.sourcing.state.AccountAggregate; import lombok.Getter; /** * This is the class that implements account created event. Holds the necessary info for an account * created event. Implements the process function that finds the event-related domain objects and * calls the related domain object's handle event functions * * <p>Created by Serdar Hamzaogullari on 06.08.2017. */ @Getter public class AccountCreateEvent extends DomainEvent { private final int accountNo; private final String owner; /** * Instantiates a new Account created event. * * @param sequenceId the sequence id * @param createdTime the created time * @param accountNo the account no * @param owner the owner */ @JsonCreator public AccountCreateEvent(@JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, @JsonProperty("accountNo") int accountNo, @JsonProperty("owner") String owner) { super(sequenceId, createdTime, "AccountCreateEvent"); this.accountNo = accountNo; this.owner = owner; } @Override public void process() { var account = AccountAggregate.getAccount(accountNo); if (account != null) { throw new RuntimeException("Account already exists"); } account = new Account(accountNo, owner); account.handleEvent(this); } }
2,851
38.068493
140
java
java-design-patterns
java-design-patterns-master/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/DomainEvent.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.event.sourcing.event; import java.io.Serializable; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; /** * This is the base class for domain events. All events must extend this class. * * <p>Created by Serdar Hamzaogullari on 06.08.2017. */ @Setter @Getter @RequiredArgsConstructor public abstract class DomainEvent implements Serializable { private final long sequenceId; private final long createdTime; private final String eventClassName; private boolean realTime = true; /** * Process. */ public abstract void process(); }
1,892
34.716981
140
java
java-design-patterns
java-design-patterns-master/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.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.event.sourcing.domain; import com.iluwatar.event.sourcing.event.AccountCreateEvent; import com.iluwatar.event.sourcing.event.MoneyDepositEvent; import com.iluwatar.event.sourcing.event.MoneyTransferEvent; import com.iluwatar.event.sourcing.state.AccountAggregate; import java.math.BigDecimal; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * This is the Account class that holds the account info, the account number, account owner name and * money of the account. Account class also have the business logic of events that effects this * account. * * <p>Created by Serdar Hamzaogullari on 06.08.2017. */ @Setter @Getter @RequiredArgsConstructor @Slf4j public class Account { private final int accountNo; private final String owner; private BigDecimal money = BigDecimal.ZERO; private static final String MSG = "Some external api for only realtime execution could be called here."; /** * Copy account. * * @return the account */ public Account copy() { var account = new Account(accountNo, owner); account.setMoney(money); return account; } @Override public String toString() { return "Account{" + "accountNo=" + accountNo + ", owner='" + owner + '\'' + ", money=" + money + '}'; } private void depositMoney(BigDecimal money) { this.money = this.money.add(money); } private void withdrawMoney(BigDecimal money) { this.money = this.money.subtract(money); } private void handleDeposit(BigDecimal money, boolean realTime) { depositMoney(money); AccountAggregate.putAccount(this); if (realTime) { LOGGER.info(MSG); } } private void handleWithdrawal(BigDecimal money, boolean realTime) { if (this.money.compareTo(money) < 0) { throw new RuntimeException("Insufficient Account Balance"); } withdrawMoney(money); AccountAggregate.putAccount(this); if (realTime) { LOGGER.info(MSG); } } /** * Handles the MoneyDepositEvent. * * @param moneyDepositEvent the money deposit event */ public void handleEvent(MoneyDepositEvent moneyDepositEvent) { handleDeposit(moneyDepositEvent.getMoney(), moneyDepositEvent.isRealTime()); } /** * Handles the AccountCreateEvent. * * @param accountCreateEvent the account created event */ public void handleEvent(AccountCreateEvent accountCreateEvent) { AccountAggregate.putAccount(this); if (accountCreateEvent.isRealTime()) { LOGGER.info(MSG); } } /** * Handles transfer from account event. * * @param moneyTransferEvent the money transfer event */ public void handleTransferFromEvent(MoneyTransferEvent moneyTransferEvent) { handleWithdrawal(moneyTransferEvent.getMoney(), moneyTransferEvent.isRealTime()); } /** * Handles transfer to account event. * * @param moneyTransferEvent the money transfer event */ public void handleTransferToEvent(MoneyTransferEvent moneyTransferEvent) { handleDeposit(moneyTransferEvent.getMoney(), moneyTransferEvent.isRealTime()); } }
4,462
29.360544
140
java
java-design-patterns
java-design-patterns-master/active-object/src/test/java/com/iluwatar/activeobject/ActiveCreatureTest.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.activeobject; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class ActiveCreatureTest { @Test void executionTest() throws InterruptedException { ActiveCreature orc = new Orc("orc1"); assertEquals("orc1",orc.name()); assertEquals(0,orc.getStatus()); orc.eat(); orc.roam(); orc.kill(0); } }
1,665
36.863636
140
java
java-design-patterns
java-design-patterns-master/active-object/src/test/java/com/iluwatar/activeobject/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.activeobject; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,568
39.230769
140
java
java-design-patterns
java-design-patterns-master/active-object/src/main/java/com/iluwatar/activeobject/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.activeobject; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Active Object pattern helps to solve synchronization difficulties without using * 'synchronized' methods. The active object will contain a thread-safe data structure * (such as BlockingQueue) and use to synchronize method calls by moving the logic of the method * into an invocator(usually a Runnable) and store it in the DSA. * * <p>In this example, we fire 20 threads to modify a value in the target class. */ public class App implements Runnable { private static final Logger logger = LoggerFactory.getLogger(App.class.getName()); private static final int NUM_CREATURES = 3; /** * Program entry point. * * @param args command line arguments. */ public static void main(String[] args) { var app = new App(); app.run(); } @Override public void run() { List<ActiveCreature> creatures = new ArrayList<>(); try { for (int i = 0; i < NUM_CREATURES; i++) { creatures.add(new Orc(Orc.class.getSimpleName() + i)); creatures.get(i).eat(); creatures.get(i).roam(); } Thread.sleep(1000); } catch (InterruptedException e) { logger.error(e.getMessage()); Thread.currentThread().interrupt(); } finally { for (int i = 0; i < NUM_CREATURES; i++) { creatures.get(i).kill(0); } } } }
2,759
35.315789
140
java
java-design-patterns
java-design-patterns-master/active-object/src/main/java/com/iluwatar/activeobject/ActiveCreature.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.activeobject; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ActiveCreature class is the base of the active object example. * @author Noam Greenshtain * */ public abstract class ActiveCreature { private static final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); private BlockingQueue<Runnable> requests; private String name; private Thread thread; // Thread of execution. private int status; // status of the thread of execution. /** * Constructor and initialization. */ protected ActiveCreature(String name) { this.name = name; this.status = 0; this.requests = new LinkedBlockingQueue<>(); thread = new Thread(() -> { boolean infinite = true; while (infinite) { try { requests.take().run(); } catch (InterruptedException e) { if (this.status != 0) { logger.error("Thread was interrupted. --> {}", e.getMessage()); } infinite = false; Thread.currentThread().interrupt(); } } }); thread.start(); } /** * Eats the porridge. * @throws InterruptedException due to firing a new Runnable. */ public void eat() throws InterruptedException { requests.put(() -> { logger.info("{} is eating!", name()); logger.info("{} has finished eating!", name()); }); } /** * Roam the wastelands. * @throws InterruptedException due to firing a new Runnable. */ public void roam() throws InterruptedException { requests.put(() -> logger.info("{} has started to roam in the wastelands.", name()) ); } /** * Returns the name of the creature. * @return the name of the creature. */ public String name() { return this.name; } /** * Kills the thread of execution. * @param status of the thread of execution. 0 == OK, the rest is logging an error. */ public void kill(int status) { this.status = status; this.thread.interrupt(); } /** * Returns the status of the thread of execution. * @return the status of the thread of execution. */ public int getStatus() { return this.status; } }
3,604
29.294118
140
java
java-design-patterns
java-design-patterns-master/active-object/src/main/java/com/iluwatar/activeobject/Orc.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.activeobject; /** * An implementation of the ActiveCreature class. * @author Noam Greenshtain * */ public class Orc extends ActiveCreature { public Orc(String name) { super(name); } }
1,504
37.589744
140
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java
package com.iluwatar.model.view.intent; import com.iluwatar.model.view.intent.actions.*; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; public class CalculatorViewModelTest { private CalculatorModel modelAfterExecutingActions(List<CalculatorAction> actions) { CalculatorViewModel viewModel = new CalculatorViewModel(); for (CalculatorAction action : actions) { viewModel.handleAction(action); } return viewModel.getCalculatorModel(); } @Test void testSetup() { CalculatorModel model = modelAfterExecutingActions(new ArrayList<>()); assert model.getVariable() == 0 && model.getOutput() == 0; } @Test void testSetVariable() { List<CalculatorAction> actions = List.of( new SetVariableCalculatorAction(10.0) ); CalculatorModel model = modelAfterExecutingActions(actions); assert model.getVariable() == 10.0 && model.getOutput() == 0; } @Test void testAddition() { List<CalculatorAction> actions = List.of( new SetVariableCalculatorAction(2.0), new AdditionCalculatorAction(), new AdditionCalculatorAction(), new SetVariableCalculatorAction(7.0), new AdditionCalculatorAction() ); CalculatorModel model = modelAfterExecutingActions(actions); assert model.getVariable() == 7.0 && model.getOutput() == 11.0; } @Test void testSubtraction() { List<CalculatorAction> actions = List.of( new SetVariableCalculatorAction(2.0), new AdditionCalculatorAction(), new AdditionCalculatorAction(), new SubtractionCalculatorAction() ); CalculatorModel model = modelAfterExecutingActions(actions); assert model.getVariable() == 2.0 && model.getOutput() == 2.0; } @Test void testMultiplication() { List<CalculatorAction> actions = List.of( new SetVariableCalculatorAction(2.0), new AdditionCalculatorAction(), new AdditionCalculatorAction(), new MultiplicationCalculatorAction() ); CalculatorModel model = modelAfterExecutingActions(actions); assert model.getVariable() == 2.0 && model.getOutput() == 8.0; } @Test void testDivision() { List<CalculatorAction> actions = List.of( new SetVariableCalculatorAction(2.0), new AdditionCalculatorAction(), new AdditionCalculatorAction(), new SetVariableCalculatorAction(2.0), new DivisionCalculatorAction() ); CalculatorModel model = modelAfterExecutingActions(actions); assert model.getVariable() == 2.0 && model.getOutput() == 2.0; } }
2,607
30.421687
86
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/test/java/com/iluwatar/model/view/intent/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.intent; 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,596
37.95122
140
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/package-info.java
/** * Define Model, View and ViewModel. * Use them in {@link com.iluwatar.model.view.intent.App} */ package com.iluwatar.model.view.intent;
144
19.714286
57
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/App.java
/* * This project is licensed under the MIT license. * Module model-view-viewmodel is using ZK framework licensed under LGPL * (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.intent; /** * Model-View-Intent is a pattern for implementing user interfaces. * Its main advantage over MVVM which it closely mirrors is a * minimal public api with which user events can be exposed to the ViewModel. * In case of the MVI every event is exposed by using a single method * with 1 argument which implements UserEvent interface. * Specific parameters can be expressed as its parameters. In this case, * we'll be using MVI to implement a simple calculator * with +, -, /, * operations and the ability to set the variable. * It's important to note, that every user action happens through the * view, we never interact with the ViewModel directly. */ public final class App { /** * To avoid magic value lint error. */ private static final double RANDOM_VARIABLE = 10.0; /** * Program entry point. * * @param args command line args */ public static void main(final String[] args) { // create model, view and controller // initialize calculator view, output and variable = 0 var view = new CalculatorView(new CalculatorViewModel()); var variable1 = RANDOM_VARIABLE; // calculator variable = RANDOM_VARIABLE -> 10.0 view.setVariable(variable1); // add calculator variable to output -> calculator output = 10.0 view.add(); view.displayTotal(); // display output variable1 = 2.0; view.setVariable(variable1); // calculator variable = 2.0 // subtract calculator variable from output -> calculator output = 8 view.subtract(); // divide calculator output by variable -> calculator output = 4.0 view.divide(); // multiply calculator output by variable -> calculator output = 8.0 view.multiply(); view.displayTotal(); } /** * Avoid default constructor lint error. */ private App() { } }
3,147
34.772727
80
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java
package com.iluwatar.model.view.intent; import com.iluwatar.model.view.intent.actions.AdditionCalculatorAction; import com.iluwatar.model.view.intent.actions.CalculatorAction; import com.iluwatar.model.view.intent.actions.DivisionCalculatorAction; import com.iluwatar.model.view.intent.actions.MultiplicationCalculatorAction; import com.iluwatar.model.view.intent.actions.SetVariableCalculatorAction; import com.iluwatar.model.view.intent.actions.SubtractionCalculatorAction; /** * Handle transformations to {@link CalculatorModel} * based on intercepted {@link CalculatorAction}. */ public final class CalculatorViewModel { /** * Current calculator model (can be changed). */ private CalculatorModel model = new CalculatorModel(0.0, 0.0); /** * Handle calculator action. * * @param action -> transforms calculator model. */ void handleAction(final CalculatorAction action) { switch (action.tag()) { case AdditionCalculatorAction.TAG -> add(); case SubtractionCalculatorAction.TAG -> subtract(); case MultiplicationCalculatorAction.TAG -> multiply(); case DivisionCalculatorAction.TAG -> divide(); case SetVariableCalculatorAction.TAG -> { SetVariableCalculatorAction setVariableAction = (SetVariableCalculatorAction) action; setVariable(setVariableAction.getVariable()); } default -> { } } } /** * Getter. * * @return current calculator model. */ public CalculatorModel getCalculatorModel() { return model; } /** * Set new calculator model variable. * * @param variable -> value of new calculator model variable. */ private void setVariable(final Double variable) { model = new CalculatorModel( variable, model.getOutput() ); } /** * Add variable to model output. */ private void add() { model = new CalculatorModel( model.getVariable(), model.getOutput() + model.getVariable() ); } /** * Subtract variable from model output. */ private void subtract() { model = new CalculatorModel( model.getVariable(), model.getOutput() - model.getVariable() ); } /** * Multiply model output by variable. */ private void multiply() { model = new CalculatorModel( model.getVariable(), model.getOutput() * model.getVariable() ); } /** * Divide model output by variable. */ private void divide() { model = new CalculatorModel( model.getVariable(), model.getOutput() / model.getVariable() ); } }
2,622
24.221154
77
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorModel.java
package com.iluwatar.model.view.intent; import lombok.Data; import lombok.Getter; /** * Current state of calculator. */ @Data public class CalculatorModel { /** * Current calculator variable used for operations. **/ @Getter private final Double variable; /** * Current calculator output -> is affected by operations. **/ @Getter private final Double output; }
390
15.291667
60
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorView.java
package com.iluwatar.model.view.intent; import com.iluwatar.model.view.intent.actions.AdditionCalculatorAction; import com.iluwatar.model.view.intent.actions.DivisionCalculatorAction; import com.iluwatar.model.view.intent.actions.MultiplicationCalculatorAction; import com.iluwatar.model.view.intent.actions.SetVariableCalculatorAction; import com.iluwatar.model.view.intent.actions.SubtractionCalculatorAction; import lombok.Data; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * Exposes changes to the state of calculator * to {@link CalculatorViewModel} through * {@link com.iluwatar.model.view.intent.actions.CalculatorAction} * and displays its updated {@link CalculatorModel}. */ @Slf4j @Data public class CalculatorView { /** * View model param handling the operations. */ @Getter private final CalculatorViewModel viewModel; /** * Display current view model output with logger. */ void displayTotal() { LOGGER.info( "Total value = {}", viewModel.getCalculatorModel().getOutput().toString() ); } /** * Handle addition action. */ void add() { viewModel.handleAction(new AdditionCalculatorAction()); } /** * Handle subtraction action. */ void subtract() { viewModel.handleAction(new SubtractionCalculatorAction()); } /** * Handle multiplication action. */ void multiply() { viewModel.handleAction(new MultiplicationCalculatorAction()); } /** * Handle division action. */ void divide() { viewModel.handleAction(new DivisionCalculatorAction()); } /** * Handle setting new variable action. * * @param value -> new calculator variable. */ void setVariable(final Double value) { viewModel.handleAction(new SetVariableCalculatorAction(value)); } }
1,808
23.12
77
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java
package com.iluwatar.model.view.intent.actions; /** * Addition {@link CalculatorAction}. * */ public class AdditionCalculatorAction implements CalculatorAction { /** * Subclass tag. * */ public static final String TAG = "ADDITION"; /** * Makes checking subclass type trivial. * */ @Override public String tag() { return TAG; } }
361
17.1
67
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/package-info.java
/** * Handle actions for {@link com.iluwatar.model.view.intent.CalculatorModel} * defined by {@link com.iluwatar.model.view.intent.actions.CalculatorAction}. */ package com.iluwatar.model.view.intent.actions;
213
29.571429
78
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java
package com.iluwatar.model.view.intent.actions; /** * Multiplication {@link CalculatorAction}. * */ public class MultiplicationCalculatorAction implements CalculatorAction { /** * Subclass tag. * */ public static final String TAG = "MULTIPLICATION"; /** * Makes checking subclass type trivial. * */ @Override public String tag() { return TAG; } }
380
18.05
73
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java
package com.iluwatar.model.view.intent.actions; /** * Subtraction {@link CalculatorAction}. * */ public class SubtractionCalculatorAction implements CalculatorAction { /** * Subclass tag. * */ public static final String TAG = "SUBTRACTION"; /** * Makes checking subclass type trivial. * */ @Override public String tag() { return TAG; } }
371
17.6
70
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java
package com.iluwatar.model.view.intent.actions; import lombok.Data; import lombok.Getter; /** * SetVariable {@link CalculatorAction}. */ @Data public final class SetVariableCalculatorAction implements CalculatorAction { /** * Subclass tag. */ public static final String TAG = "SET_VARIABLE"; /** * Used by {@link com.iluwatar.model.view.intent.CalculatorViewModel}. */ @Getter private final Double variable; /** * Makes checking subclass type trivial. */ @Override public String tag() { return TAG; } }
550
16.774194
76
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java
package com.iluwatar.model.view.intent.actions; /** * Division {@link CalculatorAction}. * */ public class DivisionCalculatorAction implements CalculatorAction { /** * Subclass tag. * */ public static final String TAG = "DIVISION"; /** * Makes checking subclass type trivial. * */ @Override public String tag() { return TAG; } }
362
17.15
67
java
java-design-patterns
java-design-patterns-master/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/CalculatorAction.java
package com.iluwatar.model.view.intent.actions; /** * Defines what outside interactions can be consumed by view model. * */ public interface CalculatorAction { /** * Makes identifying action trivial. * * @return subclass tag. * */ String tag(); }
268
15.8125
67
java
java-design-patterns
java-design-patterns-master/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.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.tablemodule; import org.h2.jdbcx.JdbcDataSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import javax.sql.DataSource; import java.sql.DriverManager; import java.sql.SQLException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class UserTableModuleTest { private static final String DB_URL = "jdbc:h2:~/test"; private static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setURL(DB_URL); return dataSource; } @BeforeEach void setUp() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); var statement = connection.createStatement()) { statement.execute(UserTableModule.DELETE_SCHEMA_SQL); statement.execute(UserTableModule.CREATE_SCHEMA_SQL); } } @AfterEach void tearDown() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); var statement = connection.createStatement()) { statement.execute(UserTableModule.DELETE_SCHEMA_SQL); } } @Test void loginShouldFail() throws SQLException { var dataSource = createDataSource(); var userTableModule = new UserTableModule(dataSource); var user = new User(1, "123456", "123456"); assertEquals(0, userTableModule.login(user.getUsername(), user.getPassword())); } @Test void loginShouldSucceed() throws SQLException { var dataSource = createDataSource(); var userTableModule = new UserTableModule(dataSource); var user = new User(1, "123456", "123456"); userTableModule.registerUser(user); assertEquals(1, userTableModule.login(user.getUsername(), user.getPassword())); } @Test void registerShouldFail() throws SQLException { var dataSource = createDataSource(); var userTableModule = new UserTableModule(dataSource); var user = new User(1, "123456", "123456"); userTableModule.registerUser(user); assertThrows(SQLException.class, () -> { userTableModule.registerUser(user); }); } @Test void registerShouldSucceed() throws SQLException { var dataSource = createDataSource(); var userTableModule = new UserTableModule(dataSource); var user = new User(1, "123456", "123456"); assertEquals(1, userTableModule.registerUser(user)); } }
3,736
36
140
java
java-design-patterns
java-design-patterns-master/table-module/src/test/java/com/iluwatar/tablemodule/UserTest.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.tablemodule; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class UserTest { @Test void testCanEqual() { assertFalse((new User(1, "janedoe", "iloveyou")) .canEqual("Other")); } @Test void testCanEqual2() { var user = new User(1, "janedoe", "iloveyou"); assertTrue(user.canEqual(new User(1, "janedoe", "iloveyou"))); } @Test void testEquals1() { var user = new User(1, "janedoe", "iloveyou"); assertNotEquals("42", user); } @Test void testEquals2() { var user = new User(1, "janedoe", "iloveyou"); assertEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals3() { var user = new User(123, "janedoe", "iloveyou"); assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals4() { var user = new User(1, null, "iloveyou"); assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals5() { var user = new User(1, "iloveyou", "iloveyou"); assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals6() { var user = new User(1, "janedoe", "janedoe"); assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals7() { var user = new User(1, "janedoe", null); assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals8() { var user = new User(1, null, "iloveyou"); assertEquals(user, new User(1, null, "iloveyou")); } @Test void testEquals9() { var user = new User(1, "janedoe", null); assertEquals(user, new User(1, "janedoe", null)); } @Test void testHashCode1() { assertEquals(-1758941372, (new User(1, "janedoe", "iloveyou")).hashCode()); } @Test void testHashCode2() { assertEquals(-1332207447, (new User(1, null, "iloveyou")).hashCode()); } @Test void testHashCode3() { assertEquals(-426522485, (new User(1, "janedoe", null)).hashCode()); } @Test void testSetId() { var user = new User(1, "janedoe", "iloveyou"); user.setId(2); assertEquals(2, user.getId()); } @Test void testSetPassword() { var user = new User(1, "janedoe", "tmp"); user.setPassword("iloveyou"); assertEquals("iloveyou", user.getPassword()); } @Test void testSetUsername() { var user = new User(1, "tmp", "iloveyou"); user.setUsername("janedoe"); assertEquals("janedoe", user.getUsername()); } @Test void testToString() { var user = new User(1, "janedoe", "iloveyou"); assertEquals(String.format("User(id=%s, username=%s, password=%s)", user.getId(), user.getUsername(), user.getPassword()), user.toString()); } }
4,206
25.967949
140
java
java-design-patterns
java-design-patterns-master/table-module/src/test/java/com/iluwatar/tablemodule/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.tablemodule; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that the table module example runs without errors. */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,619
38.512195
140
java
java-design-patterns
java-design-patterns-master/table-module/src/main/java/com/iluwatar/tablemodule/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.tablemodule; import java.sql.SQLException; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.h2.jdbcx.JdbcDataSource; /** * Table Module pattern is a domain logic pattern. * In Table Module a single class encapsulates all the domain logic for all * records stored in a table or view. It's important to note that there is no * translation of data between objects and rows, as it happens in Domain Model, * hence implementation is relatively simple when compared to the Domain * Model pattern. * * <p>In this example we will use the Table Module pattern to implement register * and login methods for the records stored in the user table. The main * method will initialise an instance of {@link UserTableModule} and use it to * handle the domain logic for the user table.</p> */ @Slf4j public final class App { private static final String DB_URL = "jdbc:h2:~/test"; /** * Private constructor. */ private App() { } /** * Program entry point. * * @param args command line args. * @throws SQLException if any error occurs. */ public static void main(final String[] args) throws SQLException { // Create data source and create the user table. final var dataSource = createDataSource(); createSchema(dataSource); var userTableModule = new UserTableModule(dataSource); // Initialize two users. var user1 = new User(1, "123456", "123456"); var user2 = new User(2, "test", "password"); // Login and register using the instance of userTableModule. userTableModule.registerUser(user1); userTableModule.login(user1.getUsername(), user1.getPassword()); userTableModule.login(user2.getUsername(), user2.getPassword()); userTableModule.registerUser(user2); userTableModule.login(user2.getUsername(), user2.getPassword()); deleteSchema(dataSource); } private static void deleteSchema(final DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(UserTableModule.DELETE_SCHEMA_SQL); } } private static void createSchema(final DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(UserTableModule.CREATE_SCHEMA_SQL); } } private static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setURL(DB_URL); return dataSource; } }
3,883
35.990476
140
java
java-design-patterns
java-design-patterns-master/table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.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.tablemodule; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; /** * This class organizes domain logic with the user table in the * database. A single instance of this class contains the various * procedures that will act on the data. */ @Slf4j public class UserTableModule { /** * Public element for creating schema. */ public static final String CREATE_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS USERS (ID NUMBER, USERNAME VARCHAR(30) " + "UNIQUE,PASSWORD VARCHAR(30))"; /** * Public element for deleting schema. */ public static final String DELETE_SCHEMA_SQL = "DROP TABLE USERS IF EXISTS"; private final DataSource dataSource; /** * Public constructor. * * @param userDataSource the data source in the database */ public UserTableModule(final DataSource userDataSource) { this.dataSource = userDataSource; } /** * Login using username and password. * * @param username the username of a user * @param password the password of a user * @return the execution result of the method * @throws SQLException if any error */ public int login(final String username, final String password) throws SQLException { var sql = "select count(*) from USERS where username=? and password=?"; ResultSet resultSet = null; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql) ) { var result = 0; preparedStatement.setString(1, username); preparedStatement.setString(2, password); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { result = resultSet.getInt(1); } if (result == 1) { LOGGER.info("Login successfully!"); } else { LOGGER.info("Fail to login!"); } return result; } finally { if (resultSet != null) { resultSet.close(); } } } /** * Register a new user. * * @param user a user instance * @return the execution result of the method * @throws SQLException if any error */ public int registerUser(final User user) throws SQLException { var sql = "insert into USERS (username, password) values (?,?)"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql) ) { preparedStatement.setString(1, user.getUsername()); preparedStatement.setString(2, user.getPassword()); var result = preparedStatement.executeUpdate(); LOGGER.info("Register successfully!"); return result; } } }
4,035
32.633333
140
java
java-design-patterns
java-design-patterns-master/table-module/src/main/java/com/iluwatar/tablemodule/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.tablemodule; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * A user POJO that represents the data that will be read from the data source. */ @Setter @Getter @ToString @EqualsAndHashCode @AllArgsConstructor public class User { private int id; private String username; private String password; }
1,704
34.520833
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.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.gameloop; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class GameControllerTest { private GameController controller; @BeforeEach void setup() { controller = new GameController(); } @AfterEach void tearDown() { controller = null; } @Test void testMoveBullet() { controller.moveBullet(1.5f); assertEquals(1.5f, controller.bullet.getPosition(), 0); } @Test void testGetBulletPosition() { assertEquals(controller.bullet.getPosition(), controller.getBulletPosition(), 0); } }
1,963
32.288136
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.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.gameloop; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * FrameBasedGameLoop unit test class. */ class FrameBasedGameLoopTest { private FrameBasedGameLoop gameLoop; @BeforeEach void setup() { gameLoop = new FrameBasedGameLoop(); } @AfterEach void tearDown() { gameLoop = null; } @Test void testUpdate() { gameLoop.update(); assertEquals(0.5f, gameLoop.controller.getBulletPosition(), 0); } }
1,877
32.535714
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.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.gameloop; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; /** * FixedStepGameLoop unit test class. */ class FixedStepGameLoopTest { private FixedStepGameLoop gameLoop; @BeforeEach void setup() { gameLoop = new FixedStepGameLoop(); } @AfterEach void tearDown() { gameLoop = null; } @Test void testUpdate() { gameLoop.update(); assertEquals(0.01f, gameLoop.controller.getBulletPosition(), 0); } }
1,875
31.912281
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.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.gameloop; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * GameLoop unit test class. */ class GameLoopTest { private GameLoop gameLoop; /** * Create mock implementation of GameLoop. */ @BeforeEach void setup() { gameLoop = new GameLoop() { @Override protected void processGameLoop() { } }; } @AfterEach void tearDown() { gameLoop = null; } @Test void testRun() { gameLoop.run(); Assertions.assertEquals(GameStatus.RUNNING, gameLoop.status); } @Test void testStop() { gameLoop.stop(); Assertions.assertEquals(GameStatus.STOPPED, gameLoop.status); } @Test void testIsGameRunning() { assertFalse(gameLoop.isGameRunning()); } }
2,204
28.4
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/test/java/com/iluwatar/gameloop/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.gameloop; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * App unit test class. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,592
36.928571
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.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.gameloop; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * VariableStepGameLoop unit test class. */ class VariableStepGameLoopTest { private VariableStepGameLoop gameLoop; @BeforeEach void setup() { gameLoop = new VariableStepGameLoop(); } @AfterEach void tearDown() { gameLoop = null; } @Test void testUpdate() { gameLoop.update(20L); Assertions.assertEquals(0.01f, gameLoop.controller.getBulletPosition(), 0); } }
1,879
33.181818
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/main/java/com/iluwatar/gameloop/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.gameloop; import lombok.extern.slf4j.Slf4j; /** * A game loop runs continuously during gameplay. Each turn of the loop, it processes * user input without blocking, updates the game state, and renders the game. It tracks * the passage of time to control the rate of gameplay. */ @Slf4j public class App { /** * Each type of game loop will run for 2 seconds. */ private static final int GAME_LOOP_DURATION_TIME = 2000; /** * Program entry point. * @param args runtime arguments */ public static void main(String[] args) { try { LOGGER.info("Start frame-based game loop:"); var frameBasedGameLoop = new FrameBasedGameLoop(); frameBasedGameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); frameBasedGameLoop.stop(); LOGGER.info("Stop frame-based game loop."); LOGGER.info("Start variable-step game loop:"); var variableStepGameLoop = new VariableStepGameLoop(); variableStepGameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); variableStepGameLoop.stop(); LOGGER.info("Stop variable-step game loop."); LOGGER.info("Start fixed-step game loop:"); var fixedStepGameLoop = new FixedStepGameLoop(); fixedStepGameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); fixedStepGameLoop.stop(); LOGGER.info("Stop variable-step game loop."); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } } }
2,771
35.473684
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.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.gameloop; import java.security.SecureRandom; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract class for GameLoop implementation class. */ public abstract class GameLoop { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected volatile GameStatus status; protected final GameController controller; private Thread gameThread; /** * Initialize game status to be stopped. */ public GameLoop() { controller = new GameController(); status = GameStatus.STOPPED; } /** * Run game loop. */ public void run() { status = GameStatus.RUNNING; gameThread = new Thread(this::processGameLoop); gameThread.start(); } /** * Stop game loop. */ public void stop() { status = GameStatus.STOPPED; } /** * Check if game is running or not. * * @return {@code true} if the game is running. */ public boolean isGameRunning() { return status == GameStatus.RUNNING; } /** * Handle any user input that has happened since the last call. In order to * simulate the situation in real-life game, here we add a random time lag. * The time lag ranges from 50 ms to 250 ms. */ protected void processInput() { try { var lag = new SecureRandom().nextInt(200) + 50; Thread.sleep(lag); } catch (InterruptedException e) { logger.error(e.getMessage()); } } /** * Render game frames to screen. Here we print bullet position to simulate * this process. */ protected void render() { var position = controller.getBulletPosition(); logger.info("Current bullet position: " + position); } /** * execute game loop logic. */ protected abstract void processGameLoop(); }
3,063
27.90566
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.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.gameloop; /** * For fixed-step game loop, a certain amount of real time has elapsed since the * last turn of the game loop. This is how much game time need to be simulated for * the game’s “now” to catch up with the player’s. */ public class FixedStepGameLoop extends GameLoop { /** * 20 ms per frame = 50 FPS. */ private static final long MS_PER_FRAME = 20; @Override protected void processGameLoop() { var previousTime = System.currentTimeMillis(); var lag = 0L; while (isGameRunning()) { var currentTime = System.currentTimeMillis(); var elapsedTime = currentTime - previousTime; previousTime = currentTime; lag += elapsedTime; processInput(); while (lag >= MS_PER_FRAME) { update(); lag -= MS_PER_FRAME; } render(); } } protected void update() { controller.moveBullet(0.5f * MS_PER_FRAME / 1000); } }
2,225
33.78125
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.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.gameloop; /** * Enum class for game status. */ public enum GameStatus { RUNNING, STOPPED }
1,403
39.114286
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/main/java/com/iluwatar/gameloop/GameController.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.gameloop; /** * Update and render objects in the game. Here we add a Bullet object to the * game system to show how the game loop works. */ public class GameController { protected final Bullet bullet; /** * Initialize Bullet instance. */ public GameController() { bullet = new Bullet(); } /** * Move bullet position by the provided offset. * * @param offset moving offset */ public void moveBullet(float offset) { var currentPosition = bullet.getPosition(); bullet.setPosition(currentPosition + offset); } /** * Get current position of the bullet. * * @return position of bullet */ public float getBulletPosition() { return bullet.getPosition(); } }
2,031
31.253968
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.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.gameloop; /** * Bullet object class. */ public class Bullet { private float position; public Bullet() { position = 0.0f; } public float getPosition() { return position; } public void setPosition(float position) { this.position = position; } }
1,581
33.391304
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.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.gameloop; /** * Frame-based game loop is the easiest implementation. The loop always keeps spinning * for the following three processes: processInput, update and render. The problem with * it is you have no control over how fast the game runs. On a fast machine, that loop * will spin so fast users won’t be able to see what’s going on. On a slow machine, the * game will crawl. If you have a part of the game that’s content-heavy or does more AI * or physics, the game will actually play slower there. */ public class FrameBasedGameLoop extends GameLoop { @Override protected void processGameLoop() { while (isGameRunning()) { processInput(); update(); render(); } } /** * Each time when update() is invoked, a new frame is created, and the bullet will be * moved 0.5f away from the current position. */ protected void update() { controller.moveBullet(0.5f); } }
2,231
39.581818
140
java
java-design-patterns
java-design-patterns-master/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.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.gameloop; /** * The variable-step game loop chooses a time step to advance based on how much * real time passed since the last frame. The longer the frame takes, the bigger * steps the game takes. It always keeps up with real time because it will take * bigger and bigger steps to get there. */ public class VariableStepGameLoop extends GameLoop { @Override protected void processGameLoop() { var lastFrameTime = System.currentTimeMillis(); while (isGameRunning()) { processInput(); var currentFrameTime = System.currentTimeMillis(); var elapsedTime = currentFrameTime - lastFrameTime; update(elapsedTime); lastFrameTime = currentFrameTime; render(); } } protected void update(Long elapsedTime) { controller.moveBullet(0.5f * elapsedTime / 1000); } }
2,127
39.150943
140
java
java-design-patterns
java-design-patterns-master/bridge/src/test/java/com/iluwatar/bridge/SwordTest.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.bridge; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import org.junit.jupiter.api.Test; /** * Tests for sword */ class SwordTest extends WeaponTest { /** * Invoke all possible actions on the weapon and check if the actions are executed on the actual * underlying weapon implementation. */ @Test void testSword() { final var sword = spy(new Sword(mock(FlyingEnchantment.class))); testBasicWeaponActions(sword); } }
1,783
37.782609
140
java
java-design-patterns
java-design-patterns-master/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.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.bridge; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Base class for weapon tests */ abstract class WeaponTest { /** * Invoke the basic actions of the given weapon, and test if the underlying enchantment * implementation is invoked */ final void testBasicWeaponActions(final Weapon weapon) { assertNotNull(weapon); var enchantment = weapon.getEnchantment(); assertNotNull(enchantment); assertNotNull(weapon.getEnchantment()); weapon.swing(); verify(enchantment).apply(); verifyNoMoreInteractions(enchantment); weapon.wield(); verify(enchantment).onActivate(); verifyNoMoreInteractions(enchantment); weapon.unwield(); verify(enchantment).onDeactivate(); verifyNoMoreInteractions(enchantment); } }
2,201
35.7
140
java
java-design-patterns
java-design-patterns-master/bridge/src/test/java/com/iluwatar/bridge/HammerTest.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.bridge; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import org.junit.jupiter.api.Test; /** * Tests for hammer */ class HammerTest extends WeaponTest { /** * Invoke all possible actions on the weapon and check if the actions are executed on the actual * underlying weapon implementation. */ @Test void testHammer() { final var hammer = spy(new Hammer(mock(FlyingEnchantment.class))); testBasicWeaponActions(hammer); } }
1,789
37.913043
140
java
java-design-patterns
java-design-patterns-master/bridge/src/test/java/com/iluwatar/bridge/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.bridge; 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,786
36.229167
140
java
java-design-patterns
java-design-patterns-master/bridge/src/main/java/com/iluwatar/bridge/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.bridge; import lombok.extern.slf4j.Slf4j; /** * Composition over inheritance. The Bridge pattern can also be thought of as two layers of * abstraction. With Bridge, you can decouple an abstraction from its implementation so that the two * can vary independently. * * <p>In Bridge pattern both abstraction ({@link Weapon}) and implementation ( {@link Enchantment}) * have their own class hierarchies. The interface of the implementations can be changed without * affecting the clients. * * <p>In this example we have two class hierarchies. One of weapons and another one of * enchantments. We can easily combine any weapon with any enchantment using composition instead of * creating deep class hierarchy. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { LOGGER.info("The knight receives an enchanted sword."); var enchantedSword = new Sword(new SoulEatingEnchantment()); enchantedSword.wield(); enchantedSword.swing(); enchantedSword.unwield(); LOGGER.info("The valkyrie receives an enchanted hammer."); var hammer = new Hammer(new FlyingEnchantment()); hammer.wield(); hammer.swing(); hammer.unwield(); } }
2,572
39.203125
140
java
java-design-patterns
java-design-patterns-master/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.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.bridge; import lombok.extern.slf4j.Slf4j; /** * FlyingEnchantment. */ @Slf4j public class FlyingEnchantment implements Enchantment { @Override public void onActivate() { LOGGER.info("The item begins to glow faintly."); } @Override public void apply() { LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand."); } @Override public void onDeactivate() { LOGGER.info("The item's glow fades."); } }
1,769
34.4
140
java
java-design-patterns
java-design-patterns-master/bridge/src/main/java/com/iluwatar/bridge/Sword.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.bridge; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Sword. */ @Slf4j @AllArgsConstructor public class Sword implements Weapon { private final Enchantment enchantment; @Override public void wield() { LOGGER.info("The sword is wielded."); enchantment.onActivate(); } @Override public void swing() { LOGGER.info("The sword is swung."); enchantment.apply(); } @Override public void unwield() { LOGGER.info("The sword is unwielded."); enchantment.onDeactivate(); } @Override public Enchantment getEnchantment() { return enchantment; } }
1,930
30.145161
140
java
java-design-patterns
java-design-patterns-master/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.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.bridge; import lombok.extern.slf4j.Slf4j; /** * SoulEatingEnchantment. */ @Slf4j public class SoulEatingEnchantment implements Enchantment { @Override public void onActivate() { LOGGER.info("The item spreads bloodlust."); } @Override public void apply() { LOGGER.info("The item eats the soul of enemies."); } @Override public void onDeactivate() { LOGGER.info("Bloodlust slowly disappears."); } }
1,739
33.8
140
java
java-design-patterns
java-design-patterns-master/bridge/src/main/java/com/iluwatar/bridge/Hammer.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.bridge; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Hammer. */ @Slf4j @AllArgsConstructor public class Hammer implements Weapon { private final Enchantment enchantment; @Override public void wield() { LOGGER.info("The hammer is wielded."); enchantment.onActivate(); } @Override public void swing() { LOGGER.info("The hammer is swung."); enchantment.apply(); } @Override public void unwield() { LOGGER.info("The hammer is unwielded."); enchantment.onDeactivate(); } @Override public Enchantment getEnchantment() { return enchantment; } }
1,935
30.225806
140
java
java-design-patterns
java-design-patterns-master/bridge/src/main/java/com/iluwatar/bridge/Enchantment.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.bridge; /** * Enchantment. */ public interface Enchantment { void onActivate(); void apply(); void onDeactivate(); }
1,434
36.763158
140
java
java-design-patterns
java-design-patterns-master/bridge/src/main/java/com/iluwatar/bridge/Weapon.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.bridge; /** * Weapon. */ public interface Weapon { void wield(); void swing(); void unwield(); Enchantment getEnchantment(); }
1,447
35.2
140
java
java-design-patterns
java-design-patterns-master/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.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.multiton; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.api.Test; /** * Date: 12/22/15 - 22:28 AM * * @author Jeroen Meulemeester */ class NazgulTest { /** * Verify if {@link Nazgul#getInstance(NazgulName)} returns the correct Nazgul multiton instance */ @Test void testGetInstance() { for (final var name : NazgulName.values()) { final var nazgul = Nazgul.getInstance(name); assertNotNull(nazgul); assertSame(nazgul, Nazgul.getInstance(name)); assertEquals(name, nazgul.getName()); } } }
2,009
36.924528
140
java
java-design-patterns
java-design-patterns-master/multiton/src/test/java/com/iluwatar/multiton/NazgulEnumTest.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.multiton; import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; /** * @author anthony * */ class NazgulEnumTest { /** * Check that multiple calls to any one of the instances in the multiton returns * only that one particular instance, and do that for all instances in multiton */ @ParameterizedTest @EnumSource void testTheSameObjectIsReturnedWithMultipleCalls(NazgulEnum nazgulEnum) { var instance1 = nazgulEnum; var instance2 = nazgulEnum; var instance3 = nazgulEnum; assertSame(instance1, instance2); assertSame(instance1, instance3); assertSame(instance2, instance3); } }
2,040
37.509434
140
java
java-design-patterns
java-design-patterns-master/multiton/src/test/java/com/iluwatar/multiton/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.multiton; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * Test if the application starts without throwing an exception. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,633
37.904762
140
java
java-design-patterns
java-design-patterns-master/multiton/src/main/java/com/iluwatar/multiton/NazgulName.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.multiton; /** * Each Nazgul has different {@link NazgulName}. */ public enum NazgulName { KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA }
1,497
35.536585
140
java
java-design-patterns
java-design-patterns-master/multiton/src/main/java/com/iluwatar/multiton/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.multiton; import lombok.extern.slf4j.Slf4j; /** * Whereas Singleton design pattern introduces single globally accessible object, the Multiton * pattern defines many globally accessible objects. The client asks for the correct instance from * the Multiton by passing an enumeration as a parameter. * * <p>There is more than one way to implement the multiton design pattern. In the first example * {@link Nazgul} is the Multiton and we can ask single {@link Nazgul} from it using {@link * NazgulName}. The {@link Nazgul}s are statically initialized and stored in a concurrent hash map. * * <p>In the enum implementation {@link NazgulEnum} is the multiton. It is static and mutable * because of the way java supports enums. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // eagerly initialized multiton LOGGER.info("Printing out eagerly initialized multiton contents"); LOGGER.info("KHAMUL={}", Nazgul.getInstance(NazgulName.KHAMUL)); LOGGER.info("MURAZOR={}", Nazgul.getInstance(NazgulName.MURAZOR)); LOGGER.info("DWAR={}", Nazgul.getInstance(NazgulName.DWAR)); LOGGER.info("JI_INDUR={}", Nazgul.getInstance(NazgulName.JI_INDUR)); LOGGER.info("AKHORAHIL={}", Nazgul.getInstance(NazgulName.AKHORAHIL)); LOGGER.info("HOARMURATH={}", Nazgul.getInstance(NazgulName.HOARMURATH)); LOGGER.info("ADUNAPHEL={}", Nazgul.getInstance(NazgulName.ADUNAPHEL)); LOGGER.info("REN={}", Nazgul.getInstance(NazgulName.REN)); LOGGER.info("UVATHA={}", Nazgul.getInstance(NazgulName.UVATHA)); // enum multiton LOGGER.info("Printing out enum-based multiton contents"); LOGGER.info("KHAMUL={}", NazgulEnum.KHAMUL); LOGGER.info("MURAZOR={}", NazgulEnum.MURAZOR); LOGGER.info("DWAR={}", NazgulEnum.DWAR); LOGGER.info("JI_INDUR={}", NazgulEnum.JI_INDUR); LOGGER.info("AKHORAHIL={}", NazgulEnum.AKHORAHIL); LOGGER.info("HOARMURATH={}", NazgulEnum.HOARMURATH); LOGGER.info("ADUNAPHEL={}", NazgulEnum.ADUNAPHEL); LOGGER.info("REN={}", NazgulEnum.REN); LOGGER.info("UVATHA={}", NazgulEnum.UVATHA); } }
3,481
45.426667
140
java
java-design-patterns
java-design-patterns-master/multiton/src/main/java/com/iluwatar/multiton/Nazgul.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.multiton; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Nazgul is a Multiton class. Nazgul instances can be queried using {@link #getInstance} method. */ public final class Nazgul { private static final Map<NazgulName, Nazgul> nazguls; private final NazgulName name; static { nazguls = new ConcurrentHashMap<>(); nazguls.put(NazgulName.KHAMUL, new Nazgul(NazgulName.KHAMUL)); nazguls.put(NazgulName.MURAZOR, new Nazgul(NazgulName.MURAZOR)); nazguls.put(NazgulName.DWAR, new Nazgul(NazgulName.DWAR)); nazguls.put(NazgulName.JI_INDUR, new Nazgul(NazgulName.JI_INDUR)); nazguls.put(NazgulName.AKHORAHIL, new Nazgul(NazgulName.AKHORAHIL)); nazguls.put(NazgulName.HOARMURATH, new Nazgul(NazgulName.HOARMURATH)); nazguls.put(NazgulName.ADUNAPHEL, new Nazgul(NazgulName.ADUNAPHEL)); nazguls.put(NazgulName.REN, new Nazgul(NazgulName.REN)); nazguls.put(NazgulName.UVATHA, new Nazgul(NazgulName.UVATHA)); } private Nazgul(NazgulName name) { this.name = name; } public static Nazgul getInstance(NazgulName name) { return nazguls.get(name); } public NazgulName getName() { return name; } }
2,495
38
140
java
java-design-patterns
java-design-patterns-master/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.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.multiton; /** * enum based multiton implementation. */ public enum NazgulEnum { KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA }
1,487
35.292683
140
java
java-design-patterns
java-design-patterns-master/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.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.dao; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; /** * Tests {@link InMemoryCustomerDao}. */ class InMemoryCustomerDaoTest { private InMemoryCustomerDao dao; private static final Customer CUSTOMER = new Customer(1, "Freddy", "Krueger"); @BeforeEach void setUp() { dao = new InMemoryCustomerDao(); assertTrue(dao.add(CUSTOMER)); } /** * Represents the scenario when the DAO operations are being performed on a non existent * customer. */ @Nested class NonExistingCustomer { @Test void addingShouldResultInSuccess() throws Exception { try (var allCustomers = dao.getAll()) { assumeTrue(allCustomers.count() == 1); } final var nonExistingCustomer = new Customer(2, "Robert", "Englund"); var result = dao.add(nonExistingCustomer); assertTrue(result); assertCustomerCountIs(2); assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); } @Test void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { final var nonExistingCustomer = new Customer(2, "Robert", "Englund"); var result = dao.delete(nonExistingCustomer); assertFalse(result); assertCustomerCountIs(1); } @Test void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { final var nonExistingId = getNonExistingCustomerId(); final var newFirstname = "Douglas"; final var newLastname = "MacArthur"; final var customer = new Customer(nonExistingId, newFirstname, newLastname); var result = dao.update(customer); assertFalse(result); assertFalse(dao.getById(nonExistingId).isPresent()); } @Test void retrieveShouldReturnNoCustomer() throws Exception { assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); } } /** * Represents the scenario when the DAO operations are being performed on an already existing * customer. */ @Nested class ExistingCustomer { @Test void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { var result = dao.add(CUSTOMER); assertFalse(result); assertCustomerCountIs(1); assertEquals(CUSTOMER, dao.getById(CUSTOMER.getId()).get()); } @Test void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { var result = dao.delete(CUSTOMER); assertTrue(result); assertCustomerCountIs(0); assertFalse(dao.getById(CUSTOMER.getId()).isPresent()); } @Test void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { final var newFirstname = "Bernard"; final var newLastname = "Montgomery"; final var customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname); var result = dao.update(customer); assertTrue(result); final var cust = dao.getById(CUSTOMER.getId()).get(); assertEquals(newFirstname, cust.getFirstName()); assertEquals(newLastname, cust.getLastName()); } @Test void retriveShouldReturnTheCustomer() { var optionalCustomer = dao.getById(CUSTOMER.getId()); assertTrue(optionalCustomer.isPresent()); assertEquals(CUSTOMER, optionalCustomer.get()); } } /** * An arbitrary number which does not correspond to an active Customer id. * * @return an int of a customer id which doesn't exist */ private int getNonExistingCustomerId() { return 999; } private void assertCustomerCountIs(int count) throws Exception { try (var allCustomers = dao.getAll()) { assertEquals(count, allCustomers.count()); } } }
5,332
31.919753
140
java
java-design-patterns
java-design-patterns-master/dao/src/test/java/com/iluwatar/dao/CustomerTest.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.dao; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests {@link Customer}. */ class CustomerTest { private Customer customer; private static final int ID = 1; private static final String FIRSTNAME = "Winston"; private static final String LASTNAME = "Churchill"; @BeforeEach void setUp() { customer = new Customer(ID, FIRSTNAME, LASTNAME); } @Test void getAndSetId() { final var newId = 2; customer.setId(newId); assertEquals(newId, customer.getId()); } @Test void getAndSetFirstname() { final var newFirstname = "Bill"; customer.setFirstName(newFirstname); assertEquals(newFirstname, customer.getFirstName()); } @Test void getAndSetLastname() { final var newLastname = "Clinton"; customer.setLastName(newLastname); assertEquals(newLastname, customer.getLastName()); } @Test void notEqualWithDifferentId() { final var newId = 2; final var otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME); assertNotEquals(customer, otherCustomer); assertNotEquals(customer.hashCode(), otherCustomer.hashCode()); } @Test void equalsWithSameObjectValues() { final var otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME); assertEquals(customer, otherCustomer); assertEquals(customer.hashCode(), otherCustomer.hashCode()); } @Test void equalsWithSameObjects() { assertEquals(customer, customer); assertEquals(customer.hashCode(), customer.hashCode()); } @Test void testToString() { assertEquals(String.format("Customer(id=%s, firstName=%s, lastName=%s)", customer.getId(), customer.getFirstName(), customer.getLastName()), customer.toString()); } }
3,161
31.9375
140
java
java-design-patterns
java-design-patterns-master/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.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.dao; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** * Tests {@link DbCustomerDao}. */ class DbCustomerDaoTest { private static final String DB_URL = "jdbc:h2:~/dao"; private DbCustomerDao dao; private final Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); /** * Creates customers schema. * * @throws SQLException if there is any error while creating schema. */ @BeforeEach void createSchema() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); var statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); } } /** * Represents the scenario where DB connectivity is present. */ @Nested class ConnectionSuccess { /** * Setup for connection success scenario. * * @throws Exception if any error occurs. */ @BeforeEach void setUp() throws Exception { var dataSource = new JdbcDataSource(); dataSource.setURL(DB_URL); dao = new DbCustomerDao(dataSource); var result = dao.add(existingCustomer); assertTrue(result); } /** * Represents the scenario when DAO operations are being performed on a non existing customer. */ @Nested class NonExistingCustomer { @Test void addingShouldResultInSuccess() throws Exception { try (var allCustomers = dao.getAll()) { assumeTrue(allCustomers.count() == 1); } final var nonExistingCustomer = new Customer(2, "Robert", "Englund"); var result = dao.add(nonExistingCustomer); assertTrue(result); assertCustomerCountIs(2); assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); } @Test void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { final var nonExistingCustomer = new Customer(2, "Robert", "Englund"); var result = dao.delete(nonExistingCustomer); assertFalse(result); assertCustomerCountIs(1); } @Test void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { final var nonExistingId = getNonExistingCustomerId(); final var newFirstname = "Douglas"; final var newLastname = "MacArthur"; final var customer = new Customer(nonExistingId, newFirstname, newLastname); var result = dao.update(customer); assertFalse(result); assertFalse(dao.getById(nonExistingId).isPresent()); } @Test void retrieveShouldReturnNoCustomer() throws Exception { assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); } } /** * Represents a scenario where DAO operations are being performed on an already existing * customer. */ @Nested class ExistingCustomer { @Test void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { var existingCustomer = new Customer(1, "Freddy", "Krueger"); var result = dao.add(existingCustomer); assertFalse(result); assertCustomerCountIs(1); assertEquals(existingCustomer, dao.getById(existingCustomer.getId()).get()); } @Test void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { var result = dao.delete(existingCustomer); assertTrue(result); assertCustomerCountIs(0); assertFalse(dao.getById(existingCustomer.getId()).isPresent()); } @Test void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { final var newFirstname = "Bernard"; final var newLastname = "Montgomery"; final var customer = new Customer(existingCustomer.getId(), newFirstname, newLastname); var result = dao.update(customer); assertTrue(result); final var cust = dao.getById(existingCustomer.getId()).get(); assertEquals(newFirstname, cust.getFirstName()); assertEquals(newLastname, cust.getLastName()); } } } /** * Represents a scenario where DB connectivity is not present due to network issue, or DB service * unavailable. */ @Nested class ConnectivityIssue { private static final String EXCEPTION_CAUSE = "Connection not available"; /** * setup a connection failure scenario. * * @throws SQLException if any error occurs. */ @BeforeEach void setUp() throws SQLException { dao = new DbCustomerDao(mockedDatasource()); } private DataSource mockedDatasource() throws SQLException { var mockedDataSource = mock(DataSource.class); var mockedConnection = mock(Connection.class); var exception = new SQLException(EXCEPTION_CAUSE); doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString()); doReturn(mockedConnection).when(mockedDataSource).getConnection(); return mockedDataSource; } @Test void addingACustomerFailsWithExceptionAsFeedbackToClient() { assertThrows(Exception.class, () -> { dao.add(new Customer(2, "Bernard", "Montgomery")); }); } @Test void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() { assertThrows(Exception.class, () -> { dao.delete(existingCustomer); }); } @Test void updatingACustomerFailsWithFeedbackToTheClient() { final var newFirstname = "Bernard"; final var newLastname = "Montgomery"; assertThrows(Exception.class, () -> { dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname)); }); } @Test void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() { assertThrows(Exception.class, () -> { dao.getById(existingCustomer.getId()); }); } @Test void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() { assertThrows(Exception.class, () -> { dao.getAll(); }); } } /** * Delete customer schema for fresh setup per test. * * @throws SQLException if any error occurs. */ @AfterEach void deleteSchema() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); var statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); } } private void assertCustomerCountIs(int count) throws Exception { try (var allCustomers = dao.getAll()) { assertEquals(count, allCustomers.count()); } } /** * An arbitrary number which does not correspond to an active Customer id. * * @return an int of a customer id which doesn't exist */ private int getNonExistingCustomerId() { return 999; } }
8,865
31.357664
140
java
java-design-patterns
java-design-patterns-master/dao/src/test/java/com/iluwatar/dao/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.dao; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that DAO example runs without errors. */ 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 shouldExecuteDaoWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,817
36.875
140
java
java-design-patterns
java-design-patterns-master/dao/src/main/java/com/iluwatar/dao/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.dao; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.h2.jdbcx.JdbcDataSource; /** * Data Access Object (DAO) is an object that provides an abstract interface to some type of * database or other persistence mechanism. By mapping application calls to the persistence layer, * DAO provide some specific data operations without exposing details of the database. This * isolation supports the Single responsibility principle. It separates what data accesses the * application needs, in terms of domain-specific objects and data types (the public interface of * the DAO), from how these needs can be satisfied with a specific DBMS. * * <p>With the DAO pattern, we can use various method calls to retrieve/add/delete/update data * without directly interacting with the data source. The below example demonstrates basic CRUD * operations: select, add, update, and delete. */ @Slf4j public class App { private static final String DB_URL = "jdbc:h2:~/dao"; private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): "; /** * Program entry point. * * @param args command line args. * @throws Exception if any error occurs. */ public static void main(final String[] args) throws Exception { final var inMemoryDao = new InMemoryCustomerDao(); performOperationsUsing(inMemoryDao); final var dataSource = createDataSource(); createSchema(dataSource); final var dbDao = new DbCustomerDao(dataSource); performOperationsUsing(dbDao); deleteSchema(dataSource); } private static void deleteSchema(DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); } } private static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setURL(DB_URL); return dataSource; } private static void performOperationsUsing(final CustomerDao customerDao) throws Exception { addCustomers(customerDao); LOGGER.info(ALL_CUSTOMERS); try (var customerStream = customerDao.getAll()) { customerStream.forEach(customer -> LOGGER.info(customer.toString())); } LOGGER.info("customerDao.getCustomerById(2): " + customerDao.getById(2)); final var customer = new Customer(4, "Dan", "Danson"); customerDao.add(customer); LOGGER.info(ALL_CUSTOMERS + customerDao.getAll()); customer.setFirstName("Daniel"); customer.setLastName("Danielson"); customerDao.update(customer); LOGGER.info(ALL_CUSTOMERS); try (var customerStream = customerDao.getAll()) { customerStream.forEach(cust -> LOGGER.info(cust.toString())); } customerDao.delete(customer); LOGGER.info(ALL_CUSTOMERS + customerDao.getAll()); } private static void addCustomers(CustomerDao customerDao) throws Exception { for (var customer : generateSampleCustomers()) { customerDao.add(customer); } } /** * Generate customers. * * @return list of customers. */ public static List<Customer> generateSampleCustomers() { final var customer1 = new Customer(1, "Adam", "Adamson"); final var customer2 = new Customer(2, "Bob", "Bobson"); final var customer3 = new Customer(3, "Carl", "Carlson"); return List.of(customer1, customer2, customer3); } }
5,026
38.896825
140
java
java-design-patterns
java-design-patterns-master/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.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.dao; /** * Customer Schema SQL Class. */ public final class CustomerSchemaSql { private CustomerSchemaSql() { } public static final String CREATE_SCHEMA_SQL = "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), " + "LNAME VARCHAR(100))"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE CUSTOMERS"; }
1,651
38.333333
140
java
java-design-patterns
java-design-patterns-master/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.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.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Optional; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.sql.DataSource; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * An implementation of {@link CustomerDao} that persists customers in RDBMS. */ @Slf4j @RequiredArgsConstructor public class DbCustomerDao implements CustomerDao { private final DataSource dataSource; /** * Get all customers as Java Stream. * * @return a lazily populated stream of customers. Note the stream returned must be closed to free * all the acquired resources. The stream keeps an open connection to the database till it is * complete or is closed manually. */ @Override public Stream<Customer> getAll() throws Exception { try { var connection = getConnection(); var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR var resultSet = statement.executeQuery(); // NOSONAR return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public boolean tryAdvance(Consumer<? super Customer> action) { try { if (!resultSet.next()) { return false; } action.accept(createCustomer(resultSet)); return true; } catch (SQLException e) { throw new RuntimeException(e); // NOSONAR } } }, false).onClose(() -> mutedClose(connection, statement, resultSet)); } catch (SQLException e) { throw new CustomException(e.getMessage(), e); } } private Connection getConnection() throws SQLException { return dataSource.getConnection(); } private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) { try { resultSet.close(); statement.close(); connection.close(); } catch (SQLException e) { LOGGER.info("Exception thrown " + e.getMessage()); } } private Customer createCustomer(ResultSet resultSet) throws SQLException { return new Customer(resultSet.getInt("ID"), resultSet.getString("FNAME"), resultSet.getString("LNAME")); } /** * {@inheritDoc} */ @Override public Optional<Customer> getById(int id) throws Exception { ResultSet resultSet = null; try (var connection = getConnection(); var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) { statement.setInt(1, id); resultSet = statement.executeQuery(); if (resultSet.next()) { return Optional.of(createCustomer(resultSet)); } else { return Optional.empty(); } } catch (SQLException ex) { throw new CustomException(ex.getMessage(), ex); } finally { if (resultSet != null) { resultSet.close(); } } } /** * {@inheritDoc} */ @Override public boolean add(Customer customer) throws Exception { if (getById(customer.getId()).isPresent()) { return false; } try (var connection = getConnection(); var statement = connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) { statement.setInt(1, customer.getId()); statement.setString(2, customer.getFirstName()); statement.setString(3, customer.getLastName()); statement.execute(); return true; } catch (SQLException ex) { throw new CustomException(ex.getMessage(), ex); } } /** * {@inheritDoc} */ @Override public boolean update(Customer customer) throws Exception { try (var connection = getConnection(); var statement = connection .prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) { statement.setString(1, customer.getFirstName()); statement.setString(2, customer.getLastName()); statement.setInt(3, customer.getId()); return statement.executeUpdate() > 0; } catch (SQLException ex) { throw new CustomException(ex.getMessage(), ex); } } /** * {@inheritDoc} */ @Override public boolean delete(Customer customer) throws Exception { try (var connection = getConnection(); var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) { statement.setInt(1, customer.getId()); return statement.executeUpdate() > 0; } catch (SQLException ex) { throw new CustomException(ex.getMessage(), ex); } } }
6,082
32.059783
140
java
java-design-patterns
java-design-patterns-master/dao/src/main/java/com/iluwatar/dao/CustomerDao.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.dao; import java.util.Optional; import java.util.stream.Stream; /** * In an application the Data Access Object (DAO) is a part of Data access layer. It is an object * that provides an interface to some type of persistence mechanism. By mapping application calls to * the persistence layer, DAO provides some specific data operations without exposing details of the * database. This isolation supports the Single responsibility principle. It separates what data * accesses the application needs, in terms of domain-specific objects and data types (the public * interface of the DAO), from how these needs can be satisfied with a specific DBMS, database * schema, etc. * * <p>Any change in the way data is stored and retrieved will not change the client code as the * client will be using interface and need not worry about exact source. * * @see InMemoryCustomerDao * @see DbCustomerDao */ public interface CustomerDao { /** * Get all customers. * * @return all the customers as a stream. The stream may be lazily or eagerly evaluated based on * the implementation. The stream must be closed after use. * @throws Exception if any error occurs. */ Stream<Customer> getAll() throws Exception; /** * Get customer as Optional by id. * * @param id unique identifier of the customer. * @return an optional with customer if a customer with unique identifier <code>id</code> exists, * empty optional otherwise. * @throws Exception if any error occurs. */ Optional<Customer> getById(int id) throws Exception; /** * Add a customer. * * @param customer the customer to be added. * @return true if customer is successfully added, false if customer already exists. * @throws Exception if any error occurs. */ boolean add(Customer customer) throws Exception; /** * Update a customer. * * @param customer the customer to be updated. * @return true if customer exists and is successfully updated, false otherwise. * @throws Exception if any error occurs. */ boolean update(Customer customer) throws Exception; /** * Delete a customer. * * @param customer the customer to be deleted. * @return true if customer exists and is successfully deleted, false otherwise. * @throws Exception if any error occurs. */ boolean delete(Customer customer) throws Exception; }
3,691
38.698925
140
java
java-design-patterns
java-design-patterns-master/dao/src/main/java/com/iluwatar/dao/Customer.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.dao; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * A customer POJO that represents the data that will be read from the data source. */ @Setter @Getter @ToString @EqualsAndHashCode(onlyExplicitlyIncluded = true) @AllArgsConstructor public class Customer { @EqualsAndHashCode.Include private int id; private String firstName; private String lastName; }
1,765
35.040816
140
java
java-design-patterns
java-design-patterns-master/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.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.dao; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; /** * An in memory implementation of {@link CustomerDao}, which stores the customers in JVM memory and * data is lost when the application exits. * <br> * This implementation is useful as temporary database or for testing. */ public class InMemoryCustomerDao implements CustomerDao { private final Map<Integer, Customer> idToCustomer = new HashMap<>(); /** * An eagerly evaluated stream of customers stored in memory. */ @Override public Stream<Customer> getAll() { return idToCustomer.values().stream(); } @Override public Optional<Customer> getById(final int id) { return Optional.ofNullable(idToCustomer.get(id)); } @Override public boolean add(final Customer customer) { if (getById(customer.getId()).isPresent()) { return false; } idToCustomer.put(customer.getId(), customer); return true; } @Override public boolean update(final Customer customer) { return idToCustomer.replace(customer.getId(), customer) != null; } @Override public boolean delete(final Customer customer) { return idToCustomer.remove(customer.getId()) != null; } }
2,549
33
140
java
java-design-patterns
java-design-patterns-master/dao/src/main/java/com/iluwatar/dao/CustomException.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.dao; /** * Custom exception. */ public class CustomException extends Exception { private static final long serialVersionUID = 1L; public CustomException() { } public CustomException(String message) { super(message); } public CustomException(String message, Throwable cause) { super(message, cause); } }
1,637
35.4
140
java
java-design-patterns
java-design-patterns-master/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.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.specification.creature; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; import java.util.Collection; import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Date: 12/29/15 - 7:47 PM * * @author Jeroen Meulemeester */ class CreatureTest { /** * @return The tested {@link Creature} instance and its expected specs */ public static Collection<Object[]> dataProvider() { return List.of( new Object[]{new Dragon(), "Dragon", Size.LARGE, Movement.FLYING, Color.RED, new Mass(39300.0)}, new Object[]{new Goblin(), "Goblin", Size.SMALL, Movement.WALKING, Color.GREEN, new Mass(30.0)}, new Object[]{new KillerBee(), "KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT, new Mass(6.7)}, new Object[]{new Octopus(), "Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK, new Mass(12.0)}, new Object[]{new Shark(), "Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT, new Mass(500.0)}, new Object[]{new Troll(), "Troll", Size.LARGE, Movement.WALKING, Color.DARK, new Mass(4000.0)} ); } @ParameterizedTest @MethodSource("dataProvider") void testGetName(Creature testedCreature, String name) { assertEquals(name, testedCreature.getName()); } @ParameterizedTest @MethodSource("dataProvider") void testGetSize(Creature testedCreature, String name, Size size) { assertEquals(size, testedCreature.getSize()); } @ParameterizedTest @MethodSource("dataProvider") void testGetMovement(Creature testedCreature, String name, Size size, Movement movement) { assertEquals(movement, testedCreature.getMovement()); } @ParameterizedTest @MethodSource("dataProvider") void testGetColor(Creature testedCreature, String name, Size size, Movement movement, Color color) { assertEquals(color, testedCreature.getColor()); } @ParameterizedTest @MethodSource("dataProvider") void testGetMass(Creature testedCreature, String name, Size size, Movement movement, Color color, Mass mass) { assertEquals(mass, testedCreature.getMass()); } @ParameterizedTest @MethodSource("dataProvider") void testToString(Creature testedCreature, String name, Size size, Movement movement, Color color, Mass mass) { final var toString = testedCreature.toString(); assertNotNull(toString); assertEquals(String .format("%s [size=%s, movement=%s, color=%s, mass=%s]", name, size, movement, color, mass), toString); } }
4,220
38.448598
140
java
java-design-patterns
java-design-patterns-master/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.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.specification.selector; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Color; import org.junit.jupiter.api.Test; /** * Date: 12/29/15 - 7:35 PM * * @author Jeroen Meulemeester */ class ColorSelectorTest { /** * Verify if the color selector gives the correct results */ @Test void testColor() { final var greenCreature = mock(Creature.class); when(greenCreature.getColor()).thenReturn(Color.GREEN); final var redCreature = mock(Creature.class); when(redCreature.getColor()).thenReturn(Color.RED); final var greenSelector = new ColorSelector(Color.GREEN); assertTrue(greenSelector.test(greenCreature)); assertFalse(greenSelector.test(redCreature)); } }
2,257
36.633333
140
java
java-design-patterns
java-design-patterns-master/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.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.specification.selector; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Mass; import org.junit.jupiter.api.Test; class MassSelectorTest { /** * Verify if the mass selector gives the correct results. */ @Test void testMass() { final var lightCreature = mock(Creature.class); when(lightCreature.getMass()).thenReturn(new Mass(50.0)); final var heavyCreature = mock(Creature.class); when(heavyCreature.getMass()).thenReturn(new Mass(2500.0)); final var lightSelector = new MassSmallerThanOrEqSelector(500.0); assertTrue(lightSelector.test(lightCreature)); assertFalse(lightSelector.test(heavyCreature)); } }
2,205
39.851852
140
java
java-design-patterns
java-design-patterns-master/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.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.specification.selector; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import org.junit.jupiter.api.Test; class CompositeSelectorsTest { /** * Verify if the conjunction selector gives the correct results. */ @Test void testAndComposition() { final var swimmingHeavyCreature = mock(Creature.class); when(swimmingHeavyCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingHeavyCreature.getMass()).thenReturn(new Mass(100.0)); final var swimmingLightCreature = mock(Creature.class); when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); final var lightAndSwimmingSelector = new MassSmallerThanOrEqSelector(50.0) .and(new MovementSelector(Movement.SWIMMING)); assertFalse(lightAndSwimmingSelector.test(swimmingHeavyCreature)); assertTrue(lightAndSwimmingSelector.test(swimmingLightCreature)); } /** * Verify if the disjunction selector gives the correct results. */ @Test void testOrComposition() { final var swimmingHeavyCreature = mock(Creature.class); when(swimmingHeavyCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingHeavyCreature.getMass()).thenReturn(new Mass(100.0)); final var swimmingLightCreature = mock(Creature.class); when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); final var lightOrSwimmingSelector = new MassSmallerThanOrEqSelector(50.0) .or(new MovementSelector(Movement.SWIMMING)); assertTrue(lightOrSwimmingSelector.test(swimmingHeavyCreature)); assertTrue(lightOrSwimmingSelector.test(swimmingLightCreature)); } /** * Verify if the negation selector gives the correct results. */ @Test void testNotComposition() { final var swimmingHeavyCreature = mock(Creature.class); when(swimmingHeavyCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingHeavyCreature.getMass()).thenReturn(new Mass(100.0)); final var swimmingLightCreature = mock(Creature.class); when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); final var heavySelector = new MassSmallerThanOrEqSelector(50.0).not(); assertTrue(heavySelector.test(swimmingHeavyCreature)); assertFalse(heavySelector.test(swimmingLightCreature)); } }
4,106
42.231579
140
java
java-design-patterns
java-design-patterns-master/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.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.specification.selector; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Size; import org.junit.jupiter.api.Test; /** * Date: 12/29/15 - 7:43 PM * * @author Jeroen Meulemeester */ class SizeSelectorTest { /** * Verify if the size selector gives the correct results */ @Test void testMovement() { final var normalCreature = mock(Creature.class); when(normalCreature.getSize()).thenReturn(Size.NORMAL); final var smallCreature = mock(Creature.class); when(smallCreature.getSize()).thenReturn(Size.SMALL); final var normalSelector = new SizeSelector(Size.NORMAL); assertTrue(normalSelector.test(normalCreature)); assertFalse(normalSelector.test(smallCreature)); } }
2,267
36.8
140
java
java-design-patterns
java-design-patterns-master/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.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.specification.selector; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Movement; import org.junit.jupiter.api.Test; /** * Date: 12/29/15 - 7:37 PM * * @author Jeroen Meulemeester */ class MovementSelectorTest { /** * Verify if the movement selector gives the correct results. */ @Test void testMovement() { final var swimmingCreature = mock(Creature.class); when(swimmingCreature.getMovement()).thenReturn(Movement.SWIMMING); final var flyingCreature = mock(Creature.class); when(flyingCreature.getMovement()).thenReturn(Movement.FLYING); final var swimmingSelector = new MovementSelector(Movement.SWIMMING); assertTrue(swimmingSelector.test(swimmingCreature)); assertFalse(swimmingSelector.test(flyingCreature)); } }
2,324
37.75
140
java
java-design-patterns
java-design-patterns-master/specification/src/test/java/com/iluwatar/specification/app/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.specification.app; 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,585
37.682927
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.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.specification.creature; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; /** * Base class for concrete creatures. */ public abstract class AbstractCreature implements Creature { private final String name; private final Size size; private final Movement movement; private final Color color; private final Mass mass; /** * Constructor. */ public AbstractCreature(String name, Size size, Movement movement, Color color, Mass mass) { this.name = name; this.size = size; this.movement = movement; this.color = color; this.mass = mass; } @Override public String toString() { return String.format("%s [size=%s, movement=%s, color=%s, mass=%s]", name, size, movement, color, mass); } @Override public String getName() { return name; } @Override public Size getSize() { return size; } @Override public Movement getMovement() { return movement; } @Override public Color getColor() { return color; } @Override public Mass getMass() { return mass; } }
2,519
28.647059
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/creature/Troll.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.specification.creature; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; /** * Troll creature. */ public class Troll extends AbstractCreature { public Troll() { this(new Mass(4000.0)); } public Troll(Mass mass) { super("Troll", Size.LARGE, Movement.WALKING, Color.DARK, mass); } }
1,760
38.133333
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/creature/Dragon.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.specification.creature; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; /** * Dragon creature. */ public class Dragon extends AbstractCreature { public Dragon() { this(new Mass(39300.0)); } public Dragon(Mass mass) { super("Dragon", Size.LARGE, Movement.FLYING, Color.RED, mass); } }
1,764
38.222222
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/creature/Creature.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.specification.creature; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; /** * Creature interface. */ public interface Creature { String getName(); Size getSize(); Movement getMovement(); Color getColor(); Mass getMass(); }
1,700
35.191489
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.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.specification.creature; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; /** * KillerBee creature. */ public class KillerBee extends AbstractCreature { public KillerBee() { this(new Mass(6.7)); } public KillerBee(Mass mass) { super("KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT, mass); } }
1,777
38.511111
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/creature/Shark.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.specification.creature; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; /** * Shark creature. */ public class Shark extends AbstractCreature { public Shark() { this(new Mass(500.0)); } public Shark(Mass mass) { super("Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT, mass); } }
1,762
38.177778
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/creature/Octopus.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.specification.creature; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; /** * Octopus creature. */ public class Octopus extends AbstractCreature { public Octopus() { this(new Mass(12.0)); } public Octopus(Mass mass) { super("Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK, mass); } }
1,770
38.355556
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/creature/Goblin.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.specification.creature; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; /** * Goblin creature. */ public class Goblin extends AbstractCreature { public Goblin() { this(new Mass(30.0)); } public Goblin(Mass mass) { super("Goblin", Size.SMALL, Movement.WALKING, Color.GREEN, mass); } }
1,764
38.222222
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.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.specification.selector; import java.util.List; /** * A Selector defined as the conjunction (AND) of other (leaf) selectors. */ public class ConjunctionSelector<T> extends AbstractSelector<T> { private final List<AbstractSelector<T>> leafComponents; @SafeVarargs ConjunctionSelector(AbstractSelector<T>... selectors) { this.leafComponents = List.of(selectors); } /** * Tests if *all* selectors pass the test. */ @Override public boolean test(T t) { return leafComponents.stream().allMatch(comp -> (comp.test(t))); } }
1,859
36.959184
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.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.specification.selector; /** * A Selector defined as the negation (NOT) of a (leaf) selectors. This is of course only useful * when used in combination with other composite selectors. */ public class NegationSelector<T> extends AbstractSelector<T> { private final AbstractSelector<T> component; NegationSelector(AbstractSelector<T> selector) { this.component = selector; } /** * Tests if the selector fails the test (yes). */ @Override public boolean test(T t) { return !(component.test(t)); } }
1,836
37.270833
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/MassSmallerThanOrEqSelector.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.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Mass; /** * Mass selector for values smaller or equal to the parameter. */ public class MassSmallerThanOrEqSelector extends AbstractSelector<Creature> { private final Mass mass; /** * The use of a double as a parameter will spare some typing when instantiating this class. */ public MassSmallerThanOrEqSelector(double mass) { this.mass = new Mass(mass); } @Override public boolean test(Creature t) { return t.getMass().smallerThanOrEq(mass); } }
1,906
37.918367
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.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.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Movement; /** * Movement selector. */ public class MovementSelector extends AbstractSelector<Creature> { private final Movement movement; public MovementSelector(Movement m) { this.movement = m; } @Override public boolean test(Creature t) { return t.getMovement().equals(movement); } }
1,738
36.804348
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.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.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Color; /** * Color selector. */ public class ColorSelector extends AbstractSelector<Creature> { private final Color color; public ColorSelector(Color c) { this.color = c; } @Override public boolean test(Creature t) { return t.getColor().equals(color); } }
1,708
36.152174
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.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.specification.selector; import java.util.List; /** * A Selector defined as the disjunction (OR) of other (leaf) selectors. */ public class DisjunctionSelector<T> extends AbstractSelector<T> { private final List<AbstractSelector<T>> leafComponents; @SafeVarargs DisjunctionSelector(AbstractSelector<T>... selectors) { this.leafComponents = List.of(selectors); } /** * Tests if *at least one* selector passes the test. */ @Override public boolean test(T t) { return leafComponents.stream().anyMatch(comp -> comp.test(t)); } }
1,866
37.102041
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.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.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Size; /** * Size selector. */ public class SizeSelector extends AbstractSelector<Creature> { private final Size size; public SizeSelector(Size s) { this.size = s; } @Override public boolean test(Creature t) { return t.getSize().equals(size); } }
1,698
35.934783
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/AbstractSelector.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.specification.selector; import java.util.function.Predicate; /** * Base class for selectors. */ public abstract class AbstractSelector<T> implements Predicate<T> { public AbstractSelector<T> and(AbstractSelector<T> other) { return new ConjunctionSelector<>(this, other); } public AbstractSelector<T> or(AbstractSelector<T> other) { return new DisjunctionSelector<>(this, other); } public AbstractSelector<T> not() { return new NegationSelector<>(this); } }
1,793
38
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/MassEqualSelector.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.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Mass; /** * Mass selector for values exactly equal than the parameter. */ public class MassEqualSelector extends AbstractSelector<Creature> { private final Mass mass; /** * The use of a double as a parameter will spare some typing when instantiating this class. */ public MassEqualSelector(double mass) { this.mass = new Mass(mass); } @Override public boolean test(Creature t) { return t.getMass().equals(mass); } }
1,876
37.306122
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/selector/MassGreaterThanSelector.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.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Mass; /** * Mass selector for values greater than the parameter. */ public class MassGreaterThanSelector extends AbstractSelector<Creature> { private final Mass mass; /** * The use of a double as a parameter will spare some typing when instantiating this class. */ public MassGreaterThanSelector(double mass) { this.mass = new Mass(mass); } @Override public boolean test(Creature t) { return t.getMass().greaterThan(mass); } }
1,887
37.530612
140
java
java-design-patterns
java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/app/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.specification.app; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.creature.Dragon; import com.iluwatar.specification.creature.Goblin; import com.iluwatar.specification.creature.KillerBee; import com.iluwatar.specification.creature.Octopus; import com.iluwatar.specification.creature.Shark; import com.iluwatar.specification.creature.Troll; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.selector.ColorSelector; import com.iluwatar.specification.selector.MassEqualSelector; import com.iluwatar.specification.selector.MassGreaterThanSelector; import com.iluwatar.specification.selector.MassSmallerThanOrEqSelector; import com.iluwatar.specification.selector.MovementSelector; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import lombok.extern.slf4j.Slf4j; /** * <p>The central idea of the Specification pattern is to separate the statement of how to match a * candidate, from the candidate object that it is matched against. As well as its usefulness in * selection, it is also valuable for validation and for building to order.</p> * * <p>In this example we have a pool of creatures with different properties. We then have defined * separate selection rules (Specifications) that we apply to the collection and as output receive * only the creatures that match the selection criteria.</p> * * <p>http://martinfowler.com/apsupp/spec.pdf</p> */ @Slf4j public class App { /** * Program entry point. */ public static void main(String[] args) { // initialize creatures list var creatures = List.of( new Goblin(), new Octopus(), new Dragon(), new Shark(), new Troll(), new KillerBee() ); // so-called "hard-coded" specification LOGGER.info("Demonstrating hard-coded specification :"); // find all walking creatures LOGGER.info("Find all walking creatures"); print(creatures, new MovementSelector(Movement.WALKING)); // find all dark creatures LOGGER.info("Find all dark creatures"); print(creatures, new ColorSelector(Color.DARK)); LOGGER.info("\n"); // so-called "parameterized" specification LOGGER.info("Demonstrating parameterized specification :"); // find all creatures heavier than 500kg LOGGER.info("Find all creatures heavier than 600kg"); print(creatures, new MassGreaterThanSelector(600.0)); // find all creatures heavier than 500kg LOGGER.info("Find all creatures lighter than or weighing exactly 500kg"); print(creatures, new MassSmallerThanOrEqSelector(500.0)); LOGGER.info("\n"); // so-called "composite" specification LOGGER.info("Demonstrating composite specification :"); // find all red and flying creatures LOGGER.info("Find all red and flying creatures"); var redAndFlying = new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)); print(creatures, redAndFlying); // find all creatures dark or red, non-swimming, and heavier than or equal to 400kg LOGGER.info("Find all scary creatures"); var scaryCreaturesSelector = new ColorSelector(Color.DARK) .or(new ColorSelector(Color.RED)).and(new MovementSelector(Movement.SWIMMING).not()) .and(new MassGreaterThanSelector(400.0).or(new MassEqualSelector(400.0))); print(creatures, scaryCreaturesSelector); } private static void print(List<? extends Creature> creatures, Predicate<Creature> selector) { creatures.stream().filter(selector).map(Objects::toString).forEach(LOGGER::info); } }
4,959
44.504587
140
java