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/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.reader.writer.lock.utils; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import org.slf4j.LoggerFactory; /** * InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public boolean logContains(String message) { return log.stream().anyMatch(event -> event.getFormattedMessage().contains(message)); } }
2,192
36.169492
140
java
java-design-patterns
java-design-patterns-master/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/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.reader.writer.lock; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; /** * In a multiple thread applications, the threads may try to synchronize the shared resources * regardless of read or write operation. It leads to a low performance especially in a "read more * write less" system as indeed the read operations are thread-safe to another read operation. * * <p>Reader writer lock is a synchronization primitive that try to resolve this problem. This * pattern allows concurrent access for read-only operations, while write operations require * exclusive access. This means that multiple threads can read the data in parallel but an exclusive * lock is needed for writing or modifying data. When a writer is writing the data, all other * writers or readers will be blocked until the writer is finished writing. * * <p>This example use two mutex to demonstrate the concurrent access of multiple readers and * writers. * * @author hongshuwei@gmail.com */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var executeService = Executors.newFixedThreadPool(10); var lock = new ReaderWriterLock(); // Start writers for (var i = 0; i < 5; i++) { var writingTime = ThreadLocalRandom.current().nextLong(5000); executeService.submit(new Writer("Writer " + i, lock.writeLock(), writingTime)); } LOGGER.info("Writers added..."); // Start readers for (var i = 0; i < 5; i++) { var readingTime = ThreadLocalRandom.current().nextLong(10); executeService.submit(new Reader("Reader " + i, lock.readLock(), readingTime)); } LOGGER.info("Readers added..."); try { Thread.sleep(5000L); } catch (InterruptedException e) { LOGGER.error("Error sleeping before adding more readers", e); Thread.currentThread().interrupt(); } // Start readers for (var i = 6; i < 10; i++) { var readingTime = ThreadLocalRandom.current().nextLong(10); executeService.submit(new Reader("Reader " + i, lock.readLock(), readingTime)); } LOGGER.info("More readers added..."); // In the system console, it can see that the read operations are executed concurrently while // write operations are exclusive. executeService.shutdown(); try { executeService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.error("Error waiting for ExecutorService shutdown", e); Thread.currentThread().interrupt(); } } }
3,993
37.776699
140
java
java-design-patterns
java-design-patterns-master/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.reader.writer.lock; import java.util.concurrent.locks.Lock; import lombok.extern.slf4j.Slf4j; /** * Writer class, write when it acquired the write lock. */ @Slf4j public class Writer implements Runnable { private final Lock writeLock; private final String name; private final long writingTime; /** * Create new Writer who writes for 250ms. * * @param name - Name of the thread owning the writer * @param writeLock - Lock for this writer */ public Writer(String name, Lock writeLock) { this(name, writeLock, 250L); } /** * Create new Writer. * * @param name - Name of the thread owning the writer * @param writeLock - Lock for this writer * @param writingTime - amount of time (in milliseconds) for this reader to engage writing */ public Writer(String name, Lock writeLock, long writingTime) { this.name = name; this.writeLock = writeLock; this.writingTime = writingTime; } @Override public void run() { writeLock.lock(); try { write(); } catch (InterruptedException e) { LOGGER.info("InterruptedException when writing", e); Thread.currentThread().interrupt(); } finally { writeLock.unlock(); } } /** * Simulate the write operation. */ public void write() throws InterruptedException { LOGGER.info("{} begin", name); Thread.sleep(writingTime); LOGGER.info("{} finished after writing {}ms", name, writingTime); } }
2,786
30.670455
140
java
java-design-patterns
java-design-patterns-master/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.reader.writer.lock; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import lombok.extern.slf4j.Slf4j; /** * Class responsible for control the access for reader or writer * * <p>Allows multiple readers to hold the lock at same time, but if any writer holds the lock then * readers wait. If reader holds the lock then writer waits. This lock is not fair. */ @Slf4j public class ReaderWriterLock implements ReadWriteLock { private final Object readerMutex = new Object(); private int currentReaderCount; /** * Global mutex is used to indicate that whether reader or writer gets the lock in the moment. * * <p>1. When it contains the reference of {@link #readerLock}, it means that the lock is * acquired by the reader, another reader can also do the read operation concurrently. <br> 2. * When it contains the reference of reference of {@link #writerLock}, it means that the lock is * acquired by the writer exclusively, no more reader or writer can get the lock. * * <p>This is the most important field in this class to control the access for reader/writer. */ private final Set<Object> globalMutex = new HashSet<>(); private final ReadLock readerLock = new ReadLock(); private final WriteLock writerLock = new WriteLock(); @Override public Lock readLock() { return readerLock; } @Override public Lock writeLock() { return writerLock; } /** * return true when globalMutex hold the reference of writerLock. */ private boolean doesWriterOwnThisLock() { return globalMutex.contains(writerLock); } /** * Nobody get the lock when globalMutex contains nothing. */ private boolean isLockFree() { return globalMutex.isEmpty(); } /** * Reader Lock, can be access for more than one reader concurrently if no writer get the lock. */ private class ReadLock implements Lock { @Override public void lock() { synchronized (readerMutex) { currentReaderCount++; if (currentReaderCount == 1) { acquireForReaders(); } } } /** * Acquire the globalMutex lock on behalf of current and future concurrent readers. Make sure no * writers currently owns the lock. */ private void acquireForReaders() { // Try to get the globalMutex lock for the first reader synchronized (globalMutex) { // If the no one get the lock or the lock is locked by reader, just set the reference // to the globalMutex to indicate that the lock is locked by Reader. while (doesWriterOwnThisLock()) { try { globalMutex.wait(); } catch (InterruptedException e) { var message = "InterruptedException while waiting for globalMutex in acquireForReaders"; LOGGER.info(message, e); Thread.currentThread().interrupt(); } } globalMutex.add(this); } } @Override public void unlock() { synchronized (readerMutex) { currentReaderCount--; // Release the lock only when it is the last reader, it is ensure that the lock is released // when all reader is completely. if (currentReaderCount == 0) { synchronized (globalMutex) { // Notify the waiter, mostly the writer globalMutex.remove(this); globalMutex.notifyAll(); } } } } @Override public void lockInterruptibly() { throw new UnsupportedOperationException(); } @Override public boolean tryLock() { throw new UnsupportedOperationException(); } @Override public boolean tryLock(long time, TimeUnit unit) { throw new UnsupportedOperationException(); } @Override public Condition newCondition() { throw new UnsupportedOperationException(); } } /** * Writer Lock, can only be accessed by one writer concurrently. */ private class WriteLock implements Lock { @Override public void lock() { synchronized (globalMutex) { // Wait until the lock is free. while (!isLockFree()) { try { globalMutex.wait(); } catch (InterruptedException e) { LOGGER.info("InterruptedException while waiting for globalMutex to begin writing", e); Thread.currentThread().interrupt(); } } // When the lock is free, acquire it by placing an entry in globalMutex globalMutex.add(this); } } @Override public void unlock() { synchronized (globalMutex) { globalMutex.remove(this); // Notify the waiter, other writer or reader globalMutex.notifyAll(); } } @Override public void lockInterruptibly() { throw new UnsupportedOperationException(); } @Override public boolean tryLock() { throw new UnsupportedOperationException(); } @Override public boolean tryLock(long time, TimeUnit unit) { throw new UnsupportedOperationException(); } @Override public Condition newCondition() { throw new UnsupportedOperationException(); } } }
6,665
29.577982
140
java
java-design-patterns
java-design-patterns-master/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.reader.writer.lock; import java.util.concurrent.locks.Lock; import lombok.extern.slf4j.Slf4j; /** * Reader class, read when it acquired the read lock. */ @Slf4j public class Reader implements Runnable { private final Lock readLock; private final String name; private final long readingTime; /** * Create new Reader. * * @param name - Name of the thread owning the reader * @param readLock - Lock for this reader * @param readingTime - amount of time (in milliseconds) for this reader to engage reading */ public Reader(String name, Lock readLock, long readingTime) { this.name = name; this.readLock = readLock; this.readingTime = readingTime; } /** * Create new Reader who reads for 250ms. * * @param name - Name of the thread owning the reader * @param readLock - Lock for this reader */ public Reader(String name, Lock readLock) { this(name, readLock, 250L); } @Override public void run() { readLock.lock(); try { read(); } catch (InterruptedException e) { LOGGER.info("InterruptedException when reading", e); Thread.currentThread().interrupt(); } finally { readLock.unlock(); } } /** * Simulate the read operation. */ public void read() throws InterruptedException { LOGGER.info("{} begin", name); Thread.sleep(readingTime); LOGGER.info("{} finish after reading {}ms", name, readingTime); } }
2,767
30.816092
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.asynchronous; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Application test */ class EventAsynchronousTest { private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class); @Test void testAsynchronousEvent() { var eventManager = new EventManager(); try { var aEventId = eventManager.createAsync(60); eventManager.start(aEventId); assertEquals(1, eventManager.getEventPool().size()); assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); assertEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); eventManager.cancel(aEventId); assertTrue(eventManager.getEventPool().isEmpty()); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } @Test void testSynchronousEvent() { var eventManager = new EventManager(); try { var sEventId = eventManager.create(60); eventManager.start(sEventId); assertEquals(1, eventManager.getEventPool().size()); assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); assertNotEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); eventManager.cancel(sEventId); assertTrue(eventManager.getEventPool().isEmpty()); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException | InvalidOperationException e) { LOGGER.error(e.getMessage()); } } @Test void testUnsuccessfulSynchronousEvent() { assertThrows(InvalidOperationException.class, () -> { var eventManager = new EventManager(); try { var sEventId = eventManager.create(60); eventManager.start(sEventId); sEventId = eventManager.create(60); eventManager.start(sEventId); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } }); } @Test void testFullSynchronousEvent() { var eventManager = new EventManager(); try { var eventTime = 1; var sEventId = eventManager.create(eventTime); assertEquals(1, eventManager.getEventPool().size()); eventManager.start(sEventId); var currentTime = System.currentTimeMillis(); // +2 to give a bit of buffer time for event to complete properly. var endTime = currentTime + (eventTime + 2 * 1000); while (System.currentTimeMillis() < endTime) ; assertTrue(eventManager.getEventPool().isEmpty()); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException | InvalidOperationException e) { LOGGER.error(e.getMessage()); } } @Test void testFullAsynchronousEvent() { var eventManager = new EventManager(); try { var eventTime = 1; var aEventId1 = eventManager.createAsync(eventTime); var aEventId2 = eventManager.createAsync(eventTime); var aEventId3 = eventManager.createAsync(eventTime); assertEquals(3, eventManager.getEventPool().size()); eventManager.start(aEventId1); eventManager.start(aEventId2); eventManager.start(aEventId3); var currentTime = System.currentTimeMillis(); // +2 to give a bit of buffer time for event to complete properly. var endTime = currentTime + (eventTime + 2 * 1000); while (System.currentTimeMillis() < endTime) ; assertTrue(eventManager.getEventPool().isEmpty()); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } @Test void testLongRunningEventException(){ assertThrows(LongRunningEventException.class, () -> { var eventManager = new EventManager(); eventManager.createAsync(2000); }); } @Test void testMaxNumOfEventsAllowedException(){ assertThrows(MaxNumOfEventsAllowedException.class, () -> { final var eventManager = new EventManager(); for(int i=0;i<1100;i++){ eventManager.createAsync(i); } }); } }
5,783
34.925466
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/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.event.asynchronous; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that EventAsynchronous 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 shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,854
37.645833
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.asynchronous; /** * Type of Exception raised when the Operation being invoked is Long Running. */ public class LongRunningEventException extends Exception { private static final long serialVersionUID = -483423544320148809L; public LongRunningEventException(String message) { super(message); } }
1,621
41.684211
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.asynchronous; /** * Type of Exception raised when the Operation being invoked is Invalid. */ public class InvalidOperationException extends Exception { private static final long serialVersionUID = -6191545255213410803L; public InvalidOperationException(String message) { super(message); } }
1,618
40.512821
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.asynchronous; /** * Interface with listener behaviour related to Thread Completion. */ public interface ThreadCompleteListener { void completedEventHandler(final int eventId); }
1,494
44.30303
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/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.event.asynchronous; import java.io.IOException; import java.util.Properties; import java.util.Scanner; import lombok.extern.slf4j.Slf4j; /** * This application demonstrates the <b>Event-based Asynchronous</b> pattern. Essentially, users (of * the pattern) may choose to run events in an Asynchronous or Synchronous mode. There can be * multiple Asynchronous events running at once but only one Synchronous event can run at a time. * Asynchronous events are synonymous to multi-threads. The key point here is that the threads run * in the background and the user is free to carry on with other processes. Once an event is * complete, the appropriate listener/callback method will be called. The listener then proceeds to * carry out further processing depending on the needs of the user. * * <p>The {@link EventManager} manages the events/threads that the user creates. Currently, the * supported event operations are: <code>start</code>, <code>stop</code>, <code>getStatus</code>. * For Synchronous events, the user is unable to start another (Synchronous) event if one is already * running at the time. The running event would have to either be stopped or completed before a new * event can be started. * * <p>The Event-based Asynchronous Pattern makes available the advantages of multithreaded * applications while hiding many of the complex issues inherent in multithreaded design. Using a * class that supports this pattern can allow you to:- (1) Perform time-consuming tasks, such as * downloads and database operations, "in the background," without interrupting your application. * (2) Execute multiple operations simultaneously, receiving notifications when each completes. (3) * Wait for resources to become available without stopping ("hanging") your application. (4) * Communicate with pending asynchronous operations using the familiar events-and-delegates model. * * @see EventManager * @see AsyncEvent */ @Slf4j public class App { public static final String PROP_FILE_NAME = "config.properties"; boolean interactiveMode = false; /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var app = new App(); app.setUp(); app.run(); } /** * App can run in interactive mode or not. Interactive mode == Allow user interaction with command * line. Non-interactive is a quick sequential run through the available {@link EventManager} * operations. */ public void setUp() { var prop = new Properties(); var inputStream = App.class.getClassLoader().getResourceAsStream(PROP_FILE_NAME); if (inputStream != null) { try { prop.load(inputStream); } catch (IOException e) { LOGGER.error("{} was not found. Defaulting to non-interactive mode.", PROP_FILE_NAME, e); } var property = prop.getProperty("INTERACTIVE_MODE"); if (property.equalsIgnoreCase("YES")) { interactiveMode = true; } } } /** * Run program in either interactive mode or not. */ public void run() { if (interactiveMode) { runInteractiveMode(); } else { quickRun(); } } /** * Run program in non-interactive mode. */ public void quickRun() { var eventManager = new EventManager(); try { // Create an Asynchronous event. var asyncEventId = eventManager.createAsync(60); LOGGER.info("Async Event [{}] has been created.", asyncEventId); eventManager.start(asyncEventId); LOGGER.info("Async Event [{}] has been started.", asyncEventId); // Create a Synchronous event. var syncEventId = eventManager.create(60); LOGGER.info("Sync Event [{}] has been created.", syncEventId); eventManager.start(syncEventId); LOGGER.info("Sync Event [{}] has been started.", syncEventId); eventManager.status(asyncEventId); eventManager.status(syncEventId); eventManager.cancel(asyncEventId); LOGGER.info("Async Event [{}] has been stopped.", asyncEventId); eventManager.cancel(syncEventId); LOGGER.info("Sync Event [{}] has been stopped.", syncEventId); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException | InvalidOperationException e) { LOGGER.error(e.getMessage()); } } /** * Run program in interactive mode. */ public void runInteractiveMode() { var eventManager = new EventManager(); var s = new Scanner(System.in); var option = -1; while (option != 4) { LOGGER.info("Hello. Would you like to boil some eggs?"); LOGGER.info("(1) BOIL AN EGG \n(2) STOP BOILING THIS EGG \n(3) HOW ARE MY EGGS? \n(4) EXIT"); LOGGER.info("Choose [1,2,3,4]: "); option = s.nextInt(); if (option == 1) { processOption1(eventManager, s); } else if (option == 2) { processOption2(eventManager, s); } else if (option == 3) { processOption3(eventManager, s); } else if (option == 4) { eventManager.shutdown(); } } s.close(); } private void processOption3(EventManager eventManager, Scanner s) { s.nextLine(); LOGGER.info("Just one egg (O) OR all of them (A) ?: "); var eggChoice = s.nextLine(); if (eggChoice.equalsIgnoreCase("O")) { LOGGER.info("Which egg?: "); int eventId = s.nextInt(); try { eventManager.status(eventId); } catch (EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } else if (eggChoice.equalsIgnoreCase("A")) { eventManager.statusOfAllEvents(); } } private void processOption2(EventManager eventManager, Scanner s) { LOGGER.info("Which egg?: "); var eventId = s.nextInt(); try { eventManager.cancel(eventId); LOGGER.info("Egg [{}] is removed from boiler.", eventId); } catch (EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } private void processOption1(EventManager eventManager, Scanner s) { s.nextLine(); LOGGER.info("Boil multiple eggs at once (A) or boil them one-by-one (S)?: "); var eventType = s.nextLine(); LOGGER.info("How long should this egg be boiled for (in seconds)?: "); var eventTime = s.nextInt(); if (eventType.equalsIgnoreCase("A")) { try { var eventId = eventManager.createAsync(eventTime); eventManager.start(eventId); LOGGER.info("Egg [{}] is being boiled.", eventId); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } else if (eventType.equalsIgnoreCase("S")) { try { var eventId = eventManager.create(eventTime); eventManager.start(eventId); LOGGER.info("Egg [{}] is being boiled.", eventId); } catch (MaxNumOfEventsAllowedException | InvalidOperationException | LongRunningEventException | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } else { LOGGER.info("Unknown event type."); } } }
8,447
35.730435
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.asynchronous; /** * Events that fulfill the start stop and list out current status behaviour follow this interface. */ public interface Event { void start(); void stop(); void status(); }
1,512
37.794872
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.asynchronous; import java.security.SecureRandom; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * EventManager handles and maintains a pool of event threads. {@link AsyncEvent} threads are created * upon user request. Thre are two types of events; Asynchronous and Synchronous. There can be * multiple Asynchronous events running at once but only one Synchronous event running at a time. * Currently supported event operations are: start, stop, and getStatus. Once an event is complete, * it then notifies EventManager through a listener. The EventManager then takes the event out of * the pool. */ public class EventManager implements ThreadCompleteListener { public static final int MAX_RUNNING_EVENTS = 1000; // Just don't wanna have too many running events. :) public static final int MIN_ID = 1; public static final int MAX_ID = MAX_RUNNING_EVENTS; public static final int MAX_EVENT_TIME = 1800; // in seconds / 30 minutes. private int currentlyRunningSyncEvent = -1; private final SecureRandom rand; private final Map<Integer, AsyncEvent> eventPool; private static final String DOES_NOT_EXIST = " does not exist."; /** * EventManager constructor. */ public EventManager() { rand = new SecureRandom(); eventPool = new ConcurrentHashMap<>(MAX_RUNNING_EVENTS); } /** * Create a Synchronous event. * * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. * @throws InvalidOperationException No new synchronous events can be created when one is * already running. * @throws LongRunningEventException Long running events are not allowed in the app. */ public int create(int eventTime) throws MaxNumOfEventsAllowedException, InvalidOperationException, LongRunningEventException { if (currentlyRunningSyncEvent != -1) { throw new InvalidOperationException("Event [" + currentlyRunningSyncEvent + "] is still" + " running. Please wait until it finishes and try again."); } var eventId = createEvent(eventTime, true); currentlyRunningSyncEvent = eventId; return eventId; } /** * Create an Asynchronous event. * * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. * @throws LongRunningEventException Long running events are not allowed in the app. */ public int createAsync(int eventTime) throws MaxNumOfEventsAllowedException, LongRunningEventException { return createEvent(eventTime, false); } private int createEvent(int eventTime, boolean isSynchronous) throws MaxNumOfEventsAllowedException, LongRunningEventException { if (eventPool.size() == MAX_RUNNING_EVENTS) { throw new MaxNumOfEventsAllowedException("Too many events are running at the moment." + " Please try again later."); } if (eventTime >= MAX_EVENT_TIME) { throw new LongRunningEventException( "Maximum event time allowed is " + MAX_EVENT_TIME + " seconds. Please try again."); } var newEventId = generateId(); var newEvent = new AsyncEvent(newEventId, eventTime, isSynchronous); newEvent.addListener(this); eventPool.put(newEventId, newEvent); return newEventId; } /** * Starts event. * * @param eventId The event that needs to be started. * @throws EventDoesNotExistException If event does not exist in our eventPool. */ public void start(int eventId) throws EventDoesNotExistException { if (!eventPool.containsKey(eventId)) { throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST); } eventPool.get(eventId).start(); } /** * Stops event. * * @param eventId The event that needs to be stopped. * @throws EventDoesNotExistException If event does not exist in our eventPool. */ public void cancel(int eventId) throws EventDoesNotExistException { if (!eventPool.containsKey(eventId)) { throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST); } if (eventId == currentlyRunningSyncEvent) { currentlyRunningSyncEvent = -1; } eventPool.get(eventId).stop(); eventPool.remove(eventId); } /** * Get status of a running event. * * @param eventId The event to inquire status of. * @throws EventDoesNotExistException If event does not exist in our eventPool. */ public void status(int eventId) throws EventDoesNotExistException { if (!eventPool.containsKey(eventId)) { throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST); } eventPool.get(eventId).status(); } /** * Gets status of all running events. */ @SuppressWarnings("rawtypes") public void statusOfAllEvents() { eventPool.entrySet().forEach(entry -> ((AsyncEvent) ((Map.Entry) entry).getValue()).status()); } /** * Stop all running events. */ @SuppressWarnings("rawtypes") public void shutdown() { eventPool.entrySet().forEach(entry -> ((AsyncEvent) ((Map.Entry) entry).getValue()).stop()); } /** * Returns a pseudo-random number between min and max, inclusive. The difference between min and * max can be at most * <code>Integer.MAX_VALUE - 1</code>. */ private int generateId() { // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive var randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID; while (eventPool.containsKey(randomNum)) { randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID; } return randomNum; } /** * Callback from an {@link AsyncEvent} (once it is complete). The Event is then removed from the pool. */ @Override public void completedEventHandler(int eventId) { eventPool.get(eventId).status(); if (eventPool.get(eventId).isSynchronous()) { currentlyRunningSyncEvent = -1; } eventPool.remove(eventId); } /** * Getter method for event pool. */ public Map<Integer, AsyncEvent> getEventPool() { return eventPool; } /** * Get number of currently running Synchronous events. */ public int numOfCurrentlyRunningSyncEvent() { return currentlyRunningSyncEvent; } }
7,686
33.470852
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.asynchronous; /** * Type of Exception raised when the max number of allowed events is exceeded. */ public class MaxNumOfEventsAllowedException extends Exception { private static final long serialVersionUID = -8430876973516292695L; public MaxNumOfEventsAllowedException(String message) { super(message); } }
1,633
42
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.asynchronous; /** * Custom Exception Class for Non Existent Event. */ public class EventDoesNotExistException extends Exception { private static final long serialVersionUID = -3398463738273811509L; public EventDoesNotExistException(String message) { super(message); } }
1,596
41.026316
140
java
java-design-patterns
java-design-patterns-master/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.asynchronous; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Each Event runs as a separate/individual thread. */ @Slf4j @RequiredArgsConstructor public class AsyncEvent implements Event, Runnable { private final int eventId; private final int eventTime; @Getter private final boolean synchronous; private Thread thread; private boolean isComplete = false; private ThreadCompleteListener eventListener; @Override public void start() { thread = new Thread(this); thread.start(); } @Override public void stop() { if (null == thread) { return; } thread.interrupt(); } @Override public void status() { if (!isComplete) { LOGGER.info("[{}] is not done.", eventId); } else { LOGGER.info("[{}] is done.", eventId); } } @Override public void run() { var currentTime = System.currentTimeMillis(); var endTime = currentTime + (eventTime * 1000); while (System.currentTimeMillis() < endTime) { try { Thread.sleep(1000); // Sleep for 1 second. } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } isComplete = true; completed(); } public final void addListener(final ThreadCompleteListener listener) { this.eventListener = listener; } public final void removeListener() { this.eventListener = null; } private void completed() { if (eventListener != null) { eventListener.completedEventHandler(eventId); } } }
2,892
27.93
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Circuit Breaker test */ class DefaultCircuitBreakerTest { //long timeout, int failureThreshold, long retryTimePeriod @Test void testEvaluateState() { var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 100); //Right now, failureCount<failureThreshold, so state should be closed assertEquals(circuitBreaker.getState(), "CLOSED"); circuitBreaker.failureCount = 4; circuitBreaker.lastFailureTime = System.nanoTime(); circuitBreaker.evaluateState(); //Since failureCount>failureThreshold, and lastFailureTime is nearly equal to current time, //state should be half-open assertEquals(circuitBreaker.getState(), "HALF_OPEN"); //Since failureCount>failureThreshold, and lastFailureTime is much lesser current time, //state should be open circuitBreaker.lastFailureTime = System.nanoTime() - 1000 * 1000 * 1000 * 1000; circuitBreaker.evaluateState(); assertEquals(circuitBreaker.getState(), "OPEN"); //Now set it back again to closed to test idempotency circuitBreaker.failureCount = 0; circuitBreaker.evaluateState(); assertEquals(circuitBreaker.getState(), "CLOSED"); } @Test void testSetStateForBypass() { var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 2000 * 1000 * 1000); //Right now, failureCount<failureThreshold, so state should be closed //Bypass it and set it to open circuitBreaker.setState(State.OPEN); assertEquals(circuitBreaker.getState(), "OPEN"); } @Test void testApiResponses() throws RemoteServiceException { RemoteService mockService = new RemoteService() { @Override public String call() throws RemoteServiceException { return "Remote Success"; } }; var circuitBreaker = new DefaultCircuitBreaker(mockService, 1, 1, 100); //Call with the paramater start_time set to huge amount of time in past so that service //replies with "Ok". Also, state is CLOSED in start var serviceStartTime = System.nanoTime() - 60 * 1000 * 1000 * 1000; var response = circuitBreaker.attemptRequest(); assertEquals(response, "Remote Success"); } }
3,557
41.357143
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Monitoring Service test */ class MonitoringServiceTest { //long timeout, int failureThreshold, long retryTimePeriod @Test void testLocalResponse() { var monitoringService = new MonitoringService(null,null); var response = monitoringService.localResourceResponse(); assertEquals(response, "Local Service is working"); } @Test void testDelayedRemoteResponseSuccess() { var delayedService = new DelayedRemoteService(System.nanoTime()-2*1000*1000*1000, 2); var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null); //Set time in past to make the server work var response = monitoringService.delayedServiceResponse(); assertEquals(response, "Delayed service is working"); } @Test void testDelayedRemoteResponseFailure() { var delayedService = new DelayedRemoteService(System.nanoTime(), 2); var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null); //Set time as current time as initially server fails var response = monitoringService.delayedServiceResponse(); assertEquals(response, "Delayed service is down"); } @Test void testQuickRemoteServiceResponse() { var delayedService = new QuickRemoteService(); var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null); //Set time as current time as initially server fails var response = monitoringService.delayedServiceResponse(); assertEquals(response, "Quick Service is working"); } }
3,324
40.049383
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DelayedRemoteServiceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Monitoring Service test */ class DelayedRemoteServiceTest { /** * Testing immediate response of the delayed service. * * @throws RemoteServiceException */ @Test void testDefaultConstructor() throws RemoteServiceException { Assertions.assertThrows(RemoteServiceException.class, () -> { var obj = new DelayedRemoteService(); obj.call(); }); } /** * Testing server started in past (2 seconds ago) and with a simulated delay of 1 second. * * @throws RemoteServiceException */ @Test void testParameterizedConstructor() throws RemoteServiceException { var obj = new DelayedRemoteService(System.nanoTime()-2000*1000*1000,1); assertEquals("Delayed service is working",obj.call()); } }
2,220
35.409836
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/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.circuitbreaker; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * App Test showing usage of circuit breaker. */ class AppTest { private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class); //Startup delay for delayed service (in seconds) private static final int STARTUP_DELAY = 4; //Number of failed requests for circuit breaker to open private static final int FAILURE_THRESHOLD = 1; //Time period in seconds for circuit breaker to retry service private static final int RETRY_PERIOD = 2; private MonitoringService monitoringService; private CircuitBreaker delayedServiceCircuitBreaker; private CircuitBreaker quickServiceCircuitBreaker; /** * Setup the circuit breakers and services, where {@link DelayedRemoteService} will be start with * a delay of 4 seconds and a {@link QuickRemoteService} responding healthy. Both services are * wrapped in a {@link DefaultCircuitBreaker} implementation with failure threshold of 1 failure * and retry time period of 2 seconds. */ @BeforeEach void setupCircuitBreakers() { var delayedService = new DelayedRemoteService(System.nanoTime(), STARTUP_DELAY); //Set the circuit Breaker parameters delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, FAILURE_THRESHOLD, RETRY_PERIOD * 1000 * 1000 * 1000); var quickService = new QuickRemoteService(); //Set the circuit Breaker parameters quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, FAILURE_THRESHOLD, RETRY_PERIOD * 1000 * 1000 * 1000); monitoringService = new MonitoringService(delayedServiceCircuitBreaker, quickServiceCircuitBreaker); } @Test void testFailure_OpenStateTransition() { //Calling delayed service, which will be unhealthy till 4 seconds assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); //As failure threshold is "1", the circuit breaker is changed to OPEN assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); //As circuit state is OPEN, we expect a quick fallback response from circuit breaker. assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); //Meanwhile, the quick service is responding and the circuit state is CLOSED assertEquals("Quick Service is working", monitoringService.quickServiceResponse()); assertEquals("CLOSED", quickServiceCircuitBreaker.getState()); } @Test void testFailure_HalfOpenStateTransition() { //Calling delayed service, which will be unhealthy till 4 seconds assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); //As failure threshold is "1", the circuit breaker is changed to OPEN assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); //Waiting for recovery period of 2 seconds for circuit breaker to retry service. try { LOGGER.info("Waiting 2s for delayed service to become responsive"); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //After 2 seconds, the circuit breaker should move to "HALF_OPEN" state and retry fetching response from service again assertEquals("HALF_OPEN", delayedServiceCircuitBreaker.getState()); } @Test void testRecovery_ClosedStateTransition() { //Calling delayed service, which will be unhealthy till 4 seconds assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); //As failure threshold is "1", the circuit breaker is changed to OPEN assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); //Waiting for 4 seconds, which is enough for DelayedService to become healthy and respond successfully. try { LOGGER.info("Waiting 4s for delayed service to become responsive"); Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } //As retry period is 2 seconds (<4 seconds of wait), hence the circuit breaker should be back in HALF_OPEN state. assertEquals("HALF_OPEN", delayedServiceCircuitBreaker.getState()); //Check the success response from delayed service. assertEquals("Delayed service is working", monitoringService.delayedServiceResponse()); //As the response is success, the state should be CLOSED assertEquals("CLOSED", delayedServiceCircuitBreaker.getState()); } }
5,888
41.985401
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; /** * This simulates the remote service It responds only after a certain timeout period (default set to * 20 seconds). */ public class DelayedRemoteService implements RemoteService { private final long serverStartTime; private final int delay; /** * Constructor to create an instance of DelayedService, which is down for first few seconds. * * @param delay the delay after which service would behave properly, in seconds */ public DelayedRemoteService(long serverStartTime, int delay) { this.serverStartTime = serverStartTime; this.delay = delay; } public DelayedRemoteService() { this.serverStartTime = System.nanoTime(); this.delay = 20; } /** * Responds based on delay, current time and server start time if the service is down / working. * * @return The state of the service */ @Override public String call() throws RemoteServiceException { var currentTime = System.nanoTime(); //Since currentTime and serverStartTime are both in nanoseconds, we convert it to //seconds by diving by 10e9 and ensure floating point division by multiplying it //with 1.0 first. We then check if it is greater or less than specified delay and then //send the reply if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000) < delay) { //Can use Thread.sleep() here to block and simulate a hung server throw new RemoteServiceException("Delayed service is down"); } return "Delayed service is working"; } }
2,830
39.442857
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/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.circuitbreaker; import lombok.extern.slf4j.Slf4j; /** * <p> * The intention of the Circuit Builder pattern is to handle remote failures robustly, which is to * mean that if a service is dependant on n number of other services, and m of them fail, we should * be able to recover from that failure by ensuring that the user can still use the services that * are actually functional, and resources are not tied up by uselessly by the services which are not * working. However, we should also be able to detect when any of the m failing services become * operational again, so that we can use it * </p> * <p> * In this example, the circuit breaker pattern is demonstrated by using three services: {@link * DelayedRemoteService}, {@link QuickRemoteService} and {@link MonitoringService}. The monitoring * service is responsible for calling three services: a local service, a quick remove service * {@link QuickRemoteService} and a delayed remote service {@link DelayedRemoteService} , and by * using the circuit breaker construction we ensure that if the call to remote service is going to * fail, we are going to save our resources and not make the function call at all, by wrapping our * call to the remote services in the {@link DefaultCircuitBreaker} implementation object. * </p> * <p> * This works as follows: The {@link DefaultCircuitBreaker} object can be in one of three states: * <b>Open</b>, <b>Closed</b> and <b>Half-Open</b>, which represents the real world circuits. If * the state is closed (initial), we assume everything is alright and perform the function call. * However, every time the call fails, we note it and once it crosses a threshold, we set the state * to Open, preventing any further calls to the remote server. Then, after a certain retry period * (during which we expect thee service to recover), we make another call to the remote server and * this state is called the Half-Open state, where it stays till the service is down, and once it * recovers, it goes back to the closed state and the cycle continues. * </p> */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var serverStartTime = System.nanoTime(); var delayedService = new DelayedRemoteService(serverStartTime, 5); var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2, 2000 * 1000 * 1000); var quickService = new QuickRemoteService(); var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2, 2000 * 1000 * 1000); //Create an object of monitoring service which makes both local and remote calls var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, quickServiceCircuitBreaker); //Fetch response from local resource LOGGER.info(monitoringService.localResourceResponse()); //Fetch response from delayed service 2 times, to meet the failure threshold LOGGER.info(monitoringService.delayedServiceResponse()); LOGGER.info(monitoringService.delayedServiceResponse()); //Fetch current state of delayed service circuit breaker after crossing failure threshold limit //which is OPEN now LOGGER.info(delayedServiceCircuitBreaker.getState()); //Meanwhile, the delayed service is down, fetch response from the healthy quick service LOGGER.info(monitoringService.quickServiceResponse()); LOGGER.info(quickServiceCircuitBreaker.getState()); //Wait for the delayed service to become responsive try { LOGGER.info("Waiting for delayed service to become responsive"); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } //Check the state of delayed circuit breaker, should be HALF_OPEN LOGGER.info(delayedServiceCircuitBreaker.getState()); //Fetch response from delayed service, which should be healthy by now LOGGER.info(monitoringService.delayedServiceResponse()); //As successful response is fetched, it should be CLOSED again. LOGGER.info(delayedServiceCircuitBreaker.getState()); } }
5,463
47.353982
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteServiceException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; /** * Exception thrown when {@link RemoteService} does not respond successfully. */ public class RemoteServiceException extends Exception { public RemoteServiceException(String message) { super(message); } }
1,541
41.833333
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; /** * The Remote service interface, used by {@link CircuitBreaker} for fetching response from remote * services. */ public interface RemoteService { //Fetch response from remote service. String call() throws RemoteServiceException; }
1,564
42.472222
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; /** * The delay based Circuit breaker implementation that works in a * CLOSED->OPEN-(retry_time_period)->HALF_OPEN->CLOSED flow with some retry time period for failed * services and a failure threshold for service to open circuit. */ public class DefaultCircuitBreaker implements CircuitBreaker { private final long timeout; private final long retryTimePeriod; private final RemoteService service; long lastFailureTime; private String lastFailureResponse; int failureCount; private final int failureThreshold; private State state; private final long futureTime = 1000L * 1000 * 1000 * 1000; /** * Constructor to create an instance of Circuit Breaker. * * @param timeout Timeout for the API request. Not necessary for this simple example * @param failureThreshold Number of failures we receive from the depended on service before * changing state to 'OPEN' * @param retryTimePeriod Time, in nanoseconds, period after which a new request is made to * remote service for status check. */ DefaultCircuitBreaker(RemoteService serviceToCall, long timeout, int failureThreshold, long retryTimePeriod) { this.service = serviceToCall; // We start in a closed state hoping that everything is fine this.state = State.CLOSED; this.failureThreshold = failureThreshold; // Timeout for the API request. // Used to break the calls made to remote resource if it exceeds the limit this.timeout = timeout; this.retryTimePeriod = retryTimePeriod; //An absurd amount of time in future which basically indicates the last failure never happened this.lastFailureTime = System.nanoTime() + futureTime; this.failureCount = 0; } // Reset everything to defaults @Override public void recordSuccess() { this.failureCount = 0; this.lastFailureTime = System.nanoTime() + futureTime; this.state = State.CLOSED; } @Override public void recordFailure(String response) { failureCount = failureCount + 1; this.lastFailureTime = System.nanoTime(); // Cache the failure response for returning on open state this.lastFailureResponse = response; } // Evaluate the current state based on failureThreshold, failureCount and lastFailureTime. protected void evaluateState() { if (failureCount >= failureThreshold) { //Then something is wrong with remote service if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { //We have waited long enough and should try checking if service is up state = State.HALF_OPEN; } else { //Service would still probably be down state = State.OPEN; } } else { //Everything is working fine state = State.CLOSED; } } @Override public String getState() { evaluateState(); return state.name(); } /** * Break the circuit beforehand if it is known service is down Or connect the circuit manually if * service comes online before expected. * * @param state State at which circuit is in */ @Override public void setState(State state) { this.state = state; switch (state) { case OPEN -> { this.failureCount = failureThreshold; this.lastFailureTime = System.nanoTime(); } case HALF_OPEN -> { this.failureCount = failureThreshold; this.lastFailureTime = System.nanoTime() - retryTimePeriod; } default -> this.failureCount = 0; } } /** * Executes service call. * * @return Value from the remote resource, stale response or a custom exception */ @Override public String attemptRequest() throws RemoteServiceException { evaluateState(); if (state == State.OPEN) { // return cached response if the circuit is in OPEN state return this.lastFailureResponse; } else { // Make the API request if the circuit is not OPEN try { //In a real application, this would be run in a thread and the timeout //parameter of the circuit breaker would be utilized to know if service //is working. Here, we simulate that based on server response itself var response = service.call(); // Yay!! the API responded fine. Let's reset everything. recordSuccess(); return response; } catch (RemoteServiceException ex) { recordFailure(ex.getMessage()); throw ex; } } } }
5,791
36.128205
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/QuickRemoteService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; /** * A quick response remote service, that responds healthy without any delay or failure. */ public class QuickRemoteService implements RemoteService { @Override public String call() throws RemoteServiceException { return "Quick Service is working"; } }
1,590
42
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; /** * Enumeration for states the circuit breaker could be in. */ public enum State { CLOSED, OPEN, HALF_OPEN }
1,440
41.382353
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; /** * The Circuit breaker interface. */ public interface CircuitBreaker { // Success response. Reset everything to defaults void recordSuccess(); // Failure response. Handle accordingly with response and change state if required. void recordFailure(String response); // Get the current state of circuit breaker String getState(); // Set the specific state manually. void setState(State state); // Attempt to fetch response from the remote service. String attemptRequest() throws RemoteServiceException; }
1,854
38.468085
140
java
java-design-patterns
java-design-patterns-master/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.circuitbreaker; /** * The service class which makes local and remote calls Uses {@link DefaultCircuitBreaker} object to * ensure remote calls don't use up resources. */ public class MonitoringService { private final CircuitBreaker delayedService; private final CircuitBreaker quickService; public MonitoringService(CircuitBreaker delayedService, CircuitBreaker quickService) { this.delayedService = delayedService; this.quickService = quickService; } //Assumption: Local service won't fail, no need to wrap it in a circuit breaker logic public String localResourceResponse() { return "Local Service is working"; } /** * Fetch response from the delayed service (with some simulated startup time). * * @return response string */ public String delayedServiceResponse() { try { return this.delayedService.attemptRequest(); } catch (RemoteServiceException e) { return e.getMessage(); } } /** * Fetches response from a healthy service without any failure. * * @return response string */ public String quickServiceResponse() { try { return this.quickService.attemptRequest(); } catch (RemoteServiceException e) { return e.getMessage(); } } }
2,559
34.555556
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/test/java/com/iluwatar/identitymap/PersonDbSimulatorImplementationTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class PersonDbSimulatorImplementationTest { @Test void testInsert(){ // DataBase initialization. PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Assertions.assertEquals(0,db.size(),"Size of null database should be 0"); // Dummy persons. Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); Person person3 = new Person(3, "Arthur", 27489171); db.insert(person1); db.insert(person2); db.insert(person3); // Test size after insertion. Assertions.assertEquals(3,db.size(),"Incorrect size for database."); Person person4 = new Person(4, "Finn", 20499078); Person person5 = new Person(5, "Michael", 40599078); db.insert(person4); db.insert(person5); // Test size after more insertions. Assertions.assertEquals(5,db.size(),"Incorrect size for database."); Person person5duplicate = new Person(5,"Kevin",89589122); db.insert(person5duplicate); // Test size after attempt to insert record with duplicate key. Assertions.assertEquals(5,db.size(),"Incorrect size for data base"); } @Test void findNotInDb(){ PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); // Test if IdNotFoundException is thrown where expected. Assertions.assertThrows(IdNotFoundException.class,()->db.find(3)); } @Test void findInDb(){ PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); Assertions.assertEquals(person2,db.find(2),"Record that was found was incorrect."); } @Test void updateNotInDb(){ PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); Person person3 = new Person(3,"Micheal",25671234); // Test if IdNotFoundException is thrown when person with ID 3 is not in DB. Assertions.assertThrows(IdNotFoundException.class,()->db.update(person3)); } @Test void updateInDb(){ PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); Person person = new Person(2,"Thomas",42273690); db.update(person); Assertions.assertEquals(person,db.find(2),"Incorrect update."); } @Test void deleteNotInDb(){ PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); // Test if IdNotFoundException is thrown when person with this ID not in DB. Assertions.assertThrows(IdNotFoundException.class,()->db.delete(3)); } @Test void deleteInDb(){ PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); // delete the record. db.delete(1); // test size of database after deletion. Assertions.assertEquals(1,db.size(),"Size after deletion is incorrect."); // try to find deleted record in db. Assertions.assertThrows(IdNotFoundException.class,()->db.find(1)); } }
5,184
41.154472
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/test/java/com/iluwatar/identitymap/PersonTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class PersonTest { @Test void testEquality(){ // dummy persons. Person person1 = new Person(1,"Harry",989950022); Person person2 = new Person(2,"Kane",989920011); Assertions.assertNotEquals(person1,person2,"Incorrect equality condition"); // person with duplicate nationalID. Person person3 = new Person(2,"John",789012211); // If nationalID is equal then persons are equal(even if name or phoneNum are different). // This situation will never arise in this implementation. Only for testing. Assertions.assertEquals(person2,person3,"Incorrect inequality condition"); } }
2,009
44.681818
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/test/java/com/iluwatar/identitymap/PersonFinderTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class PersonFinderTest { @Test void personFoundInDB(){ // personFinderInstance PersonFinder personFinder = new PersonFinder(); // init database for our personFinder PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); // Dummy persons Person person1 = new Person(1, "John", 27304159); Person person2 = new Person(2, "Thomas", 42273631); Person person3 = new Person(3, "Arthur", 27489171); Person person4 = new Person(4, "Finn", 20499078); Person person5 = new Person(5, "Michael", 40599078); // Add data to the database. db.insert(person1); db.insert(person2); db.insert(person3); db.insert(person4); db.insert(person5); personFinder.setDb(db); Assertions.assertEquals(person1,personFinder.getPerson(1),"Find person returns incorrect record."); Assertions.assertEquals(person3,personFinder.getPerson(3),"Find person returns incorrect record."); Assertions.assertEquals(person2,personFinder.getPerson(2),"Find person returns incorrect record."); Assertions.assertEquals(person5,personFinder.getPerson(5),"Find person returns incorrect record."); Assertions.assertEquals(person4,personFinder.getPerson(4),"Find person returns incorrect record."); } @Test void personFoundInIdMap(){ // personFinderInstance PersonFinder personFinder = new PersonFinder(); // init database for our personFinder PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); // Dummy persons Person person1 = new Person(1, "John", 27304159); Person person2 = new Person(2, "Thomas", 42273631); Person person3 = new Person(3, "Arthur", 27489171); Person person4 = new Person(4, "Finn", 20499078); Person person5 = new Person(5, "Michael", 40599078); // Add data to the database. db.insert(person1); db.insert(person2); db.insert(person3); db.insert(person4); db.insert(person5); personFinder.setDb(db); // Assure key is not in the ID map. Assertions.assertFalse(personFinder.getIdentityMap().getPersonMap().containsKey(3)); // Assure key is in the database. Assertions.assertEquals(person3,personFinder.getPerson(3),"Finder returns incorrect record."); // Assure that the record for this key is cached in the Map now. Assertions.assertTrue(personFinder.getIdentityMap().getPersonMap().containsKey(3)); // Find the record again. This time it will be found in the map. Assertions.assertEquals(person3,personFinder.getPerson(3),"Finder returns incorrect record."); } @Test void personNotFoundInDB(){ PersonFinder personFinder = new PersonFinder(); // init database for our personFinder PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); personFinder.setDb(db); Assertions.assertThrows(IdNotFoundException.class,()->personFinder.getPerson(1)); // Dummy persons Person person1 = new Person(1, "John", 27304159); Person person2 = new Person(2, "Thomas", 42273631); Person person3 = new Person(3, "Arthur", 27489171); Person person4 = new Person(4, "Finn", 20499078); Person person5 = new Person(5, "Michael", 40599078); db.insert(person1); db.insert(person2); db.insert(person3); db.insert(person4); db.insert(person5); personFinder.setDb(db); // Assure that the database has been updated. Assertions.assertEquals(person4,personFinder.getPerson(4),"Find returns incorrect record"); // Assure key is in DB now. Assertions.assertDoesNotThrow(()->personFinder.getPerson(1)); // Assure key not in DB. Assertions.assertThrows(IdNotFoundException.class,()->personFinder.getPerson(6)); } }
5,111
44.238938
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/test/java/com/iluwatar/identitymap/IdentityMapTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class IdentityMapTest { @Test void addToMap(){ // new instance of an identity map(not connected to any DB here) IdentityMap idMap = new IdentityMap(); // Dummy person instances Person person1 = new Person(11, "Michael", 27304159); Person person2 = new Person(22, "John", 42273631); Person person3 = new Person(33, "Arthur", 27489171); Person person4 = new Person(44, "Finn", 20499078); // id already in map Person person5 = new Person(11, "Michael", 40599078); // All records go into identity map idMap.addPerson(person1); idMap.addPerson(person2); idMap.addPerson(person3); idMap.addPerson(person4); idMap.addPerson(person5); // Test no duplicate in our Map. Assertions.assertEquals(4,idMap.size(),"Size of the map is incorrect"); // Test record not updated by add method. Assertions.assertEquals(27304159,idMap.getPerson(11).getPhoneNum(),"Incorrect return value for phone number"); } @Test void testGetFromMap() { // new instance of an identity map(not connected to any DB here) IdentityMap idMap = new IdentityMap(); // Dummy person instances Person person1 = new Person(11, "Michael", 27304159); Person person2 = new Person(22, "John", 42273631); Person person3 = new Person(33, "Arthur", 27489171); Person person4 = new Person(44, "Finn", 20499078); Person person5 = new Person(55, "Michael", 40599078); // All records go into identity map idMap.addPerson(person1); idMap.addPerson(person2); idMap.addPerson(person3); idMap.addPerson(person4); idMap.addPerson(person5); // Test for dummy persons in the map Assertions.assertEquals(person1,idMap.getPerson(11),"Incorrect person record returned"); Assertions.assertEquals(person4,idMap.getPerson(44),"Incorrect person record returned"); // Test for person with given id not in map Assertions.assertNull(idMap.getPerson(1), "Incorrect person record returned"); } }
3,378
43.460526
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/test/java/com/iluwatar/identitymap/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.identitymap; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,562
42.416667
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/main/java/com/iluwatar/identitymap/IdNotFoundException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; /** * Using Runtime Exception to control the flow in case Person Id doesn not exist. */ public class IdNotFoundException extends RuntimeException { public IdNotFoundException(final String message) { super(message); } }
1,548
43.257143
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/main/java/com/iluwatar/identitymap/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.identitymap; import lombok.extern.slf4j.Slf4j; /** * The basic idea behind the Identity Map is to have a series of maps containing objects that have been pulled from the database. * The below example demonstrates the identity map pattern by creating a sample DB. * Since only 1 DB has been created we only have 1 map corresponding to it for the purpose of this demo. * When you load an object from the database, you first check the map. * If there’s an object in it that corresponds to the one you’re loading, you return it. If not, you go to the database, * putting the objects on the map for future reference as you load them. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args. */ public static void main(String[] args) { // Dummy Persons Person person1 = new Person(1, "John", 27304159); Person person2 = new Person(2, "Thomas", 42273631); Person person3 = new Person(3, "Arthur", 27489171); Person person4 = new Person(4, "Finn", 20499078); Person person5 = new Person(5, "Michael", 40599078); // Init database PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); db.insert(person1); db.insert(person2); db.insert(person3); db.insert(person4); db.insert(person5); // Init a personFinder PersonFinder finder = new PersonFinder(); finder.setDb(db); // Find persons in DataBase not the map. LOGGER.info(finder.getPerson(2).toString()); LOGGER.info(finder.getPerson(4).toString()); LOGGER.info(finder.getPerson(5).toString()); // Find the person in the map. LOGGER.info(finder.getPerson(2).toString()); } }
2,995
39.486486
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/main/java/com/iluwatar/identitymap/IdentityMap.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; import java.util.HashMap; import java.util.Map; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * This class stores the map into which we will be caching records after loading them from a DataBase. * Stores the records as a Hash Map with the personNationalIDs as keys. */ @Slf4j @Getter public class IdentityMap { private Map<Integer, Person> personMap = new HashMap<>(); /** * Add person to the map. */ public void addPerson(Person person) { if (!personMap.containsKey(person.getPersonNationalId())) { personMap.put(person.getPersonNationalId(), person); } else { // Ensure that addPerson does not update a record. This situation will never arise in our implementation. Added only for testing purposes. LOGGER.info("Key already in Map"); } } /** * Get Person with given id. * * @param id : personNationalId as requested by user. */ public Person getPerson(int id) { Person person = personMap.get(id); if (person == null) { LOGGER.info("ID not in Map."); return null; } LOGGER.info(person.toString()); return person; } /** * Get the size of the map. */ public int size() { if (personMap == null) { return 0; } return personMap.size(); } }
2,595
32.714286
151
java
java-design-patterns
java-design-patterns-master/identity-map/src/main/java/com/iluwatar/identitymap/PersonFinder.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * Any object of this class stores a DataBase and an Identity Map. When we try to look for a key we first check if * it has been cached in the Identity Map and return it if it is indeed in the map. * If that is not the case then go to the DataBase, get the record, store it in the * Identity Map and then return the record. Now if we look for the record again we will find it in the table itself which * will make lookup faster. */ @Slf4j @Getter @Setter public class PersonFinder { private static final long serialVersionUID = 1L; // Access to the Identity Map private IdentityMap identityMap = new IdentityMap(); private PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); /** * get person corresponding to input ID. * * @param key : personNationalId to look for. */ public Person getPerson(int key) { // Try to find person in the identity map Person person = this.identityMap.getPerson(key); if (person != null) { LOGGER.info("Person found in the Map"); return person; } else { // Try to find person in the database person = this.db.find(key); if (person != null) { this.identityMap.addPerson(person); LOGGER.info("Person found in DB."); return person; } LOGGER.info("Person with this ID does not exist."); return null; } } }
2,779
38.714286
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/main/java/com/iluwatar/identitymap/Person.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * Person definition. */ @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Getter @Setter @AllArgsConstructor public final class Person implements Serializable { private static final long serialVersionUID = 1L; @EqualsAndHashCode.Include private int personNationalId; private String name; private long phoneNum; @Override public String toString() { return "Person ID is : " + personNationalId + " ; Person Name is : " + name + " ; Phone Number is :" + phoneNum; } }
1,958
33.368421
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulatorImplementation.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; import java.util.ArrayList; import java.util.List; import java.util.Optional; import lombok.extern.slf4j.Slf4j; /** * This is a sample database implementation. The database is in the form of an arraylist which stores records of * different persons. The personNationalId acts as the primary key for a record. * Operations : * -> find (look for object with a particular ID) * -> insert (insert record for a new person into the database) * -> update (update the record of a person). To do this, create a new person instance with the same ID as the record you * want to update. Then call this method with that person as an argument. * -> delete (delete the record for a particular ID) */ @Slf4j public class PersonDbSimulatorImplementation implements PersonDbSimulator { //This simulates a table in the database. To extend logic to multiple tables just add more lists to the implementation. private List<Person> personList = new ArrayList<>(); static final String NOT_IN_DATA_BASE = " not in DataBase"; static final String ID_STR = "ID : "; @Override public Person find(int personNationalId) throws IdNotFoundException { Optional<Person> elem = personList.stream().filter(p -> p.getPersonNationalId() == personNationalId).findFirst(); if (elem.isEmpty()) { throw new IdNotFoundException(ID_STR + personNationalId + NOT_IN_DATA_BASE); } LOGGER.info(elem.get().toString()); return elem.get(); } @Override public void insert(Person person) { Optional<Person> elem = personList.stream().filter(p -> p.getPersonNationalId() == person.getPersonNationalId()).findFirst(); if (elem.isPresent()) { LOGGER.info("Record already exists."); return; } personList.add(person); } @Override public void update(Person person) throws IdNotFoundException { Optional<Person> elem = personList.stream().filter(p -> p.getPersonNationalId() == person.getPersonNationalId()).findFirst(); if (elem.isPresent()) { elem.get().setName(person.getName()); elem.get().setPhoneNum(person.getPhoneNum()); LOGGER.info("Record updated successfully"); return; } throw new IdNotFoundException(ID_STR + person.getPersonNationalId() + NOT_IN_DATA_BASE); } /** * Delete the record corresponding to given ID from the DB. * * @param id : personNationalId for person whose record is to be deleted. */ public void delete(int id) throws IdNotFoundException { Optional<Person> elem = personList.stream().filter(p -> p.getPersonNationalId() == id).findFirst(); if (elem.isPresent()) { personList.remove(elem.get()); LOGGER.info("Record deleted successfully."); return; } throw new IdNotFoundException(ID_STR + id + NOT_IN_DATA_BASE); } /** * Return the size of the database. */ public int size() { if (personList == null) { return 0; } return personList.size(); } }
4,252
38.37963
140
java
java-design-patterns
java-design-patterns-master/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulator.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.identitymap; /** * Simulator interface for Person DB. */ public interface PersonDbSimulator { Person find(int personNationalId); void insert(Person person); void update(Person person); void delete(int personNationalId); }
1,542
37.575
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerDaoImplTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.domainmodel; import org.joda.money.CurrencyUnit; import org.joda.money.Money; 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.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import static org.joda.money.CurrencyUnit.USD; import static org.junit.jupiter.api.Assertions.*; class CustomerDaoImplTest { public static final String INSERT_CUSTOMER_SQL = "insert into CUSTOMERS values('customer', 100)"; public static final String SELECT_CUSTOMERS_SQL = "select name, money from CUSTOMERS"; public static final String INSERT_PURCHASES_SQL = "insert into PURCHASES values('product', 'customer')"; public static final String SELECT_PURCHASES_SQL = "select product_name, customer_name from PURCHASES"; private DataSource dataSource; private Product product; private Customer customer; private CustomerDao customerDao; @BeforeEach void setUp() throws SQLException { // create db schema dataSource = TestUtils.createDataSource(); TestUtils.deleteSchema(dataSource); TestUtils.createSchema(dataSource); // setup objects customerDao = new CustomerDaoImpl(dataSource); customer = Customer.builder().name("customer").money(Money.of(CurrencyUnit.USD,100.0)).customerDao(customerDao).build(); product = Product.builder() .name("product") .price(Money.of(USD, 100.0)) .expirationDate(LocalDate.parse("2021-06-27")) .productDao(new ProductDaoImpl(dataSource)) .build(); } @AfterEach void tearDown() throws SQLException { TestUtils.deleteSchema(dataSource); } @Test void shouldFindCustomerByName() throws SQLException { var customer = customerDao.findByName("customer"); assertTrue(customer.isEmpty()); TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource); customer = customerDao.findByName("customer"); assertTrue(customer.isPresent()); assertEquals("customer", customer.get().getName()); assertEquals(Money.of(USD, 100), customer.get().getMoney()); } @Test void shouldSaveCustomer() throws SQLException { customerDao.save(customer); try (var connection = dataSource.getConnection(); var statement = connection.createStatement(); ResultSet rs = statement.executeQuery(SELECT_CUSTOMERS_SQL)) { assertTrue(rs.next()); assertEquals(customer.getName(), rs.getString("name")); assertEquals(customer.getMoney(), Money.of(USD, rs.getBigDecimal("money"))); } assertThrows(SQLException.class, () -> customerDao.save(customer)); } @Test void shouldUpdateCustomer() throws SQLException { TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource); customer.setMoney(Money.of(CurrencyUnit.USD, 99)); customerDao.update(customer); try (var connection = dataSource.getConnection(); var statement = connection.createStatement(); ResultSet rs = statement.executeQuery(SELECT_CUSTOMERS_SQL)) { assertTrue(rs.next()); assertEquals(customer.getName(), rs.getString("name")); assertEquals(customer.getMoney(), Money.of(USD, rs.getBigDecimal("money"))); assertFalse(rs.next()); } } @Test void shouldAddProductToPurchases() throws SQLException { TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource); TestUtils.executeSQL(ProductDaoImplTest.INSERT_PRODUCT_SQL, dataSource); customerDao.addProduct(product, customer); try (var connection = dataSource.getConnection(); var statement = connection.createStatement(); ResultSet rs = statement.executeQuery(SELECT_PURCHASES_SQL)) { assertTrue(rs.next()); assertEquals(product.getName(), rs.getString("product_name")); assertEquals(customer.getName(), rs.getString("customer_name")); assertFalse(rs.next()); } } @Test void shouldDeleteProductFromPurchases() throws SQLException { TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource); TestUtils.executeSQL(ProductDaoImplTest.INSERT_PRODUCT_SQL, dataSource); TestUtils.executeSQL(INSERT_PURCHASES_SQL, dataSource); customerDao.deleteProduct(product, customer); try (var connection = dataSource.getConnection(); var statement = connection.createStatement(); ResultSet rs = statement.executeQuery(SELECT_PURCHASES_SQL)) { assertFalse(rs.next()); } } }
5,786
34.072727
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/test/java/com/iluwatar/domainmodel/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.domainmodel; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Optional; import static org.joda.money.CurrencyUnit.USD; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; class CustomerTest { private CustomerDao customerDao; private Customer customer; private Product product; @BeforeEach void setUp() { customerDao = mock(CustomerDao.class); customer = Customer.builder() .name("customer") .money(Money.of(CurrencyUnit.USD, 100.0)) .customerDao(customerDao) .build(); product = Product.builder() .name("product") .price(Money.of(USD, 100.0)) .expirationDate(LocalDate.now().plusDays(10)) .productDao(mock(ProductDao.class)) .build(); } @Test void shouldSaveCustomer() throws SQLException { when(customerDao.findByName("customer")).thenReturn(Optional.empty()); customer.save(); verify(customerDao, times(1)).save(customer); when(customerDao.findByName("customer")).thenReturn(Optional.of(customer)); customer.save(); verify(customerDao, times(1)).update(customer); } @Test void shouldAddProductToPurchases() { product.setPrice(Money.of(USD, 200.0)); customer.buyProduct(product); assertEquals(customer.getPurchases(), new ArrayList<>()); assertEquals(customer.getMoney(), Money.of(USD,100)); product.setPrice(Money.of(USD, 100.0)); customer.buyProduct(product); assertEquals(new ArrayList<>(Arrays.asList(product)), customer.getPurchases()); assertEquals(Money.zero(USD), customer.getMoney()); } @Test void shouldRemoveProductFromPurchases() { customer.setPurchases(new ArrayList<>(Arrays.asList(product))); customer.returnProduct(product); assertEquals(new ArrayList<>(), customer.getPurchases()); assertEquals(Money.of(USD, 200), customer.getMoney()); customer.returnProduct(product); assertEquals(new ArrayList<>(), customer.getPurchases()); assertEquals(Money.of(USD, 200), customer.getMoney()); } }
3,797
32.610619
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/test/java/com/iluwatar/domainmodel/TestUtils.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.domainmodel; import org.h2.jdbcx.JdbcDataSource; import javax.sql.DataSource; import java.sql.SQLException; public class TestUtils { public static void executeSQL( String sql, DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.executeUpdate(sql); } } public static void createSchema(DataSource dataSource) throws SQLException { TestUtils.executeSQL(App.CREATE_SCHEMA_SQL, dataSource); } public static void deleteSchema(DataSource dataSource) throws SQLException { TestUtils.executeSQL(App.DELETE_SCHEMA_SQL, dataSource); } public static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setURL(App.H2_DB_URL); return dataSource; } }
2,136
38.574074
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/test/java/com/iluwatar/domainmodel/ProductTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.domainmodel; import org.joda.money.Money; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.sql.SQLException; import java.time.LocalDate; import java.util.Optional; import static org.joda.money.CurrencyUnit.USD; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; class ProductTest { private ProductDao productDao; private Product product; @BeforeEach void setUp() { productDao = mock(ProductDaoImpl.class); product = Product.builder() .name("product") .price(Money.of(USD, 100.0)) .expirationDate(LocalDate.now().plusDays(10)) .productDao(productDao) .build(); } @Test void shouldSaveProduct() throws SQLException { when(productDao.findByName("product")).thenReturn(Optional.empty()); product.save(); verify(productDao, times(1)).save(product); when(productDao.findByName("product")).thenReturn(Optional.of(product)); product.save(); verify(productDao, times(1)).update(product); } @Test void shouldGetSalePriceOfProduct() { assertEquals(Money.of(USD, 100), product.getSalePrice()); product.setExpirationDate(LocalDate.now().plusDays(2)); assertEquals(Money.of(USD, 80), product.getSalePrice()); } }
2,717
33.405063
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/test/java/com/iluwatar/domainmodel/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.domainmodel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** Tests that Domain Model example runs without errors. */ final class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[] {})); } }
1,630
39.775
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/test/java/com/iluwatar/domainmodel/ProductDaoImplTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.domainmodel; import org.joda.money.Money; 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.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import static org.joda.money.CurrencyUnit.USD; import static org.junit.jupiter.api.Assertions.*; class ProductDaoImplTest { public static final String INSERT_PRODUCT_SQL = "insert into PRODUCTS values('product', 100, DATE '2021-06-27')"; public static final String SELECT_PRODUCTS_SQL = "select name, price, expiration_date from PRODUCTS"; private DataSource dataSource; private ProductDao productDao; private Product product; @BeforeEach void setUp() throws SQLException { // create schema dataSource = TestUtils.createDataSource(); TestUtils.deleteSchema(dataSource); TestUtils.createSchema(dataSource); // setup objects productDao = new ProductDaoImpl(dataSource); product = Product.builder() .name("product") .price(Money.of(USD, 100.0)) .expirationDate(LocalDate.parse("2021-06-27")) .productDao(productDao) .build(); } @AfterEach void tearDown() throws SQLException { TestUtils.deleteSchema(dataSource); } @Test void shouldFindProductByName() throws SQLException { var product = productDao.findByName("product"); assertTrue(product.isEmpty()); TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource); product = productDao.findByName("product"); assertTrue(product.isPresent()); assertEquals("product", product.get().getName()); assertEquals(Money.of(USD, 100), product.get().getPrice()); assertEquals(LocalDate.parse("2021-06-27"), product.get().getExpirationDate()); } @Test void shouldSaveProduct() throws SQLException { productDao.save(product); try (var connection = dataSource.getConnection(); var statement = connection.createStatement(); ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) { assertTrue(rs.next()); assertEquals(product.getName(), rs.getString("name")); assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price"))); assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate()); } assertThrows(SQLException.class, () -> productDao.save(product)); } @Test void shouldUpdateProduct() throws SQLException { TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource); product.setPrice(Money.of(USD, 99.0)); productDao.update(product); try (var connection = dataSource.getConnection(); var statement = connection.createStatement(); ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) { assertTrue(rs.next()); assertEquals(product.getName(), rs.getString("name")); assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price"))); assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate()); } } }
4,694
35.679688
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/main/java/com/iluwatar/domainmodel/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.domainmodel; import static org.joda.money.CurrencyUnit.USD; import java.sql.SQLException; import java.time.LocalDate; import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.joda.money.Money; /** * Domain Model pattern is a more complex solution for organizing domain logic than Transaction * Script and Table Module. It provides an object-oriented way of dealing with complicated logic. * Instead of having one procedure that handles all business logic for a user action like * Transaction Script there are multiple objects and each of them handles a slice of domain logic * that is relevant to it. The significant difference between Domain Model and Table Module pattern * is that in Table Module a single class encapsulates all the domain logic for all records stored * in table when in Domain Model every single class represents only one record in underlying table. * * <p>In this example, we will use the Domain Model pattern to implement buying of products * by customers in a Shop. The main method will create a customer and a few products. * Customer will do a few purchases, try to buy product which are too expensive for him, * return product which he bought to return money.</p> */ public class App { public static final String H2_DB_URL = "jdbc:h2:~/test"; public static final String CREATE_SCHEMA_SQL = "CREATE TABLE CUSTOMERS (name varchar primary key, money decimal);" + "CREATE TABLE PRODUCTS (name varchar primary key, price decimal, expiration_date date);" + "CREATE TABLE PURCHASES (" + "product_name varchar references PRODUCTS(name)," + "customer_name varchar references CUSTOMERS(name));"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE PURCHASES IF EXISTS;" + "DROP TABLE CUSTOMERS IF EXISTS;" + "DROP TABLE PRODUCTS IF EXISTS;"; /** * Program entry point. * * @param args command line arguments * @throws Exception if any error occurs */ public static void main(String[] args) throws Exception { // Create data source and create the customers, products and purchases tables final var dataSource = createDataSource(); deleteSchema(dataSource); createSchema(dataSource); // create customer var customerDao = new CustomerDaoImpl(dataSource); var tom = Customer.builder() .name("Tom") .money(Money.of(USD, 30)) .customerDao(customerDao) .build(); tom.save(); // create products var productDao = new ProductDaoImpl(dataSource); var eggs = Product.builder() .name("Eggs") .price(Money.of(USD, 10.0)) .expirationDate(LocalDate.now().plusDays(7)) .productDao(productDao) .build(); var butter = Product.builder() .name("Butter") .price(Money.of(USD, 20.00)) .expirationDate(LocalDate.now().plusDays(9)) .productDao(productDao) .build(); var cheese = Product.builder() .name("Cheese") .price(Money.of(USD, 25.0)) .expirationDate(LocalDate.now().plusDays(2)) .productDao(productDao) .build(); eggs.save(); butter.save(); cheese.save(); // show money balance of customer after each purchase tom.showBalance(); tom.showPurchases(); // buy eggs tom.buyProduct(eggs); tom.showBalance(); // buy butter tom.buyProduct(butter); tom.showBalance(); // trying to buy cheese, but receive a refusal // because he didn't have enough money tom.buyProduct(cheese); tom.showBalance(); // return butter and get money back tom.returnProduct(butter); tom.showBalance(); // Tom can buy cheese now because he has enough money // and there is a discount on cheese because it expires in 2 days tom.buyProduct(cheese); tom.save(); // show money balance and purchases after shopping tom.showBalance(); tom.showPurchases(); } private static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setUrl(H2_DB_URL); return dataSource; } private static void deleteSchema(DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(CREATE_SCHEMA_SQL); } } }
6,049
33.770115
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDao.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.domainmodel; import java.sql.SQLException; import java.util.Optional; /** * DAO interface for product transactions. */ public interface ProductDao { Optional<Product> findByName(String name) throws SQLException; void save(Product product) throws SQLException; void update(Product product) throws SQLException; }
1,630
38.780488
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDaoImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.domainmodel; import static org.joda.money.CurrencyUnit.USD; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Optional; import javax.sql.DataSource; import org.joda.money.Money; /** * Implementations for database operations of Customer. */ public class CustomerDaoImpl implements CustomerDao { private final DataSource dataSource; public CustomerDaoImpl(final DataSource userDataSource) { this.dataSource = userDataSource; } @Override public Optional<Customer> findByName(String name) throws SQLException { var sql = "select * from CUSTOMERS where name = ?;"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, name); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { return Optional.of( Customer.builder() .name(rs.getString("name")) .money(Money.of(USD, rs.getBigDecimal("money"))) .customerDao(this) .build()); } else { return Optional.empty(); } } } @Override public void update(Customer customer) throws SQLException { var sql = "update CUSTOMERS set money = ? where name = ?;"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setBigDecimal(1, customer.getMoney().getAmount()); preparedStatement.setString(2, customer.getName()); preparedStatement.executeUpdate(); } } @Override public void save(Customer customer) throws SQLException { var sql = "insert into CUSTOMERS (name, money) values (?, ?)"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, customer.getName()); preparedStatement.setBigDecimal(2, customer.getMoney().getAmount()); preparedStatement.executeUpdate(); } } @Override public void addProduct(Product product, Customer customer) throws SQLException { var sql = "insert into PURCHASES (product_name, customer_name) values (?,?)"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, product.getName()); preparedStatement.setString(2, customer.getName()); preparedStatement.executeUpdate(); } } @Override public void deleteProduct(Product product, Customer customer) throws SQLException { var sql = "delete from PURCHASES where product_name = ? and customer_name = ?"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, product.getName()); preparedStatement.setString(2, customer.getName()); preparedStatement.executeUpdate(); } } }
4,288
36.955752
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDaoImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.domainmodel; import static org.joda.money.CurrencyUnit.USD; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Optional; import javax.sql.DataSource; import org.joda.money.Money; /** * Implementations for database transactions of Product. */ public class ProductDaoImpl implements ProductDao { private final DataSource dataSource; public ProductDaoImpl(final DataSource userDataSource) { this.dataSource = userDataSource; } @Override public Optional<Product> findByName(String name) throws SQLException { var sql = "select * from PRODUCTS where name = ?;"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, name); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { return Optional.of( Product.builder() .name(rs.getString("name")) .price(Money.of(USD, rs.getBigDecimal("price"))) .expirationDate(rs.getDate("expiration_date").toLocalDate()) .productDao(this) .build()); } else { return Optional.empty(); } } } @Override public void save(Product product) throws SQLException { var sql = "insert into PRODUCTS (name, price, expiration_date) values (?, ?, ?)"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, product.getName()); preparedStatement.setBigDecimal(2, product.getPrice().getAmount()); preparedStatement.setDate(3, Date.valueOf(product.getExpirationDate())); preparedStatement.executeUpdate(); } } @Override public void update(Product product) throws SQLException { var sql = "update PRODUCTS set price = ?, expiration_date = ? where name = ?;"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setBigDecimal(1, product.getPrice().getAmount()); preparedStatement.setDate(2, Date.valueOf(product.getExpirationDate())); preparedStatement.setString(3, product.getName()); preparedStatement.executeUpdate(); } } }
3,633
37.252632
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/main/java/com/iluwatar/domainmodel/Product.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.domainmodel; import static org.joda.money.CurrencyUnit.USD; import java.math.RoundingMode; import java.sql.SQLException; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Optional; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.joda.money.Money; /** * This class organizes domain logic of product. * A single instance of this class * contains both the data and behavior of a single product. */ @Slf4j @Getter @Setter @Builder @AllArgsConstructor public class Product { private static final int DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE = 4; private static final double DISCOUNT_RATE = 0.2; @NonNull private final ProductDao productDao; @NonNull private String name; @NonNull private Money price; @NonNull private LocalDate expirationDate; /** * Save product or update if product already exist. */ public void save() { try { Optional<Product> product = productDao.findByName(name); if (product.isPresent()) { productDao.update(this); } else { productDao.save(this); } } catch (SQLException ex) { LOGGER.error(ex.getMessage()); } } /** * Calculate sale price of product with discount. */ public Money getSalePrice() { return price.minus(calculateDiscount()); } private Money calculateDiscount() { if (ChronoUnit.DAYS.between(LocalDate.now(), expirationDate) < DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE) { return price.multipliedBy(DISCOUNT_RATE, RoundingMode.DOWN); } return Money.zero(USD); } }
3,002
30.610526
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/main/java/com/iluwatar/domainmodel/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.domainmodel; import java.sql.SQLException; import java.util.Optional; /** * DAO interface for customer transactions. */ public interface CustomerDao { Optional<Customer> findByName(String name) throws SQLException; void update(Customer customer) throws SQLException; void save(Customer customer) throws SQLException; void addProduct(Product product, Customer customer) throws SQLException; void deleteProduct(Product product, Customer customer) throws SQLException; }
1,792
38.844444
140
java
java-design-patterns
java-design-patterns-master/domain-model/src/main/java/com/iluwatar/domainmodel/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.domainmodel; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import lombok.Builder; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.joda.money.Money; /** * This class organizes domain logic of customer. * A single instance of this class * contains both the data and behavior of a single customer. */ @Slf4j @Getter @Setter @Builder public class Customer { @NonNull private final CustomerDao customerDao; @Builder.Default private List<Product> purchases = new ArrayList<>(); @NonNull private String name; @NonNull private Money money; /** * Save customer or update if customer already exist. */ public void save() { try { Optional<Customer> customer = customerDao.findByName(name); if (customer.isPresent()) { customerDao.update(this); } else { customerDao.save(this); } } catch (SQLException ex) { LOGGER.error(ex.getMessage()); } } /** * Add product to purchases, save to db and withdraw money. * * @param product to buy. */ public void buyProduct(Product product) { LOGGER.info( String.format( "%s want to buy %s($%.2f)...", name, product.getName(), product.getSalePrice().getAmount())); try { withdraw(product.getSalePrice()); } catch (IllegalArgumentException ex) { LOGGER.error(ex.getMessage()); return; } try { customerDao.addProduct(product, this); purchases.add(product); LOGGER.info(String.format("%s bought %s!", name, product.getName())); } catch (SQLException exception) { receiveMoney(product.getSalePrice()); LOGGER.error(exception.getMessage()); } } /** * Remove product from purchases, delete from db and return money. * * @param product to return. */ public void returnProduct(Product product) { LOGGER.info( String.format( "%s want to return %s($%.2f)...", name, product.getName(), product.getSalePrice().getAmount())); if (purchases.contains(product)) { try { customerDao.deleteProduct(product, this); purchases.remove(product); receiveMoney(product.getSalePrice()); LOGGER.info(String.format("%s returned %s!", name, product.getName())); } catch (SQLException ex) { LOGGER.error(ex.getMessage()); } } else { LOGGER.error(String.format("%s didn't buy %s...", name, product.getName())); } } /** * Print customer's purchases. */ public void showPurchases() { Optional<String> purchasesToShow = purchases.stream() .map(p -> p.getName() + " - $" + p.getSalePrice().getAmount()) .reduce((p1, p2) -> p1 + ", " + p2); if (purchasesToShow.isPresent()) { LOGGER.info(name + " bought: " + purchasesToShow.get()); } else { LOGGER.info(name + " didn't bought anything"); } } /** * Print customer's money balance. */ public void showBalance() { LOGGER.info(name + " balance: " + money); } private void withdraw(Money amount) throws IllegalArgumentException { if (money.compareTo(amount) < 0) { throw new IllegalArgumentException("Not enough money!"); } money = money.minus(amount); } private void receiveMoney(Money amount) { money = money.plus(amount); } }
4,760
29.915584
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/test/java/com/iluwatar/leaderfollowers/WorkCenterTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderfollowers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; /** * Tests for WorkCenter */ class WorkCenterTest { @Test void testCreateWorkers() { var taskSet = new TaskSet(); var taskHandler = new TaskHandler(); var workCenter = new WorkCenter(); workCenter.createWorkers(5, taskSet, taskHandler); assertEquals(5, workCenter.getWorkers().size()); assertEquals(workCenter.getWorkers().get(0), workCenter.getLeader()); } @Test void testNullLeader() { var workCenter = new WorkCenter(); workCenter.promoteLeader(); assertNull(workCenter.getLeader()); } @Test void testPromoteLeader() { var taskSet = new TaskSet(); var taskHandler = new TaskHandler(); var workCenter = new WorkCenter(); workCenter.createWorkers(5, taskSet, taskHandler); workCenter.removeWorker(workCenter.getLeader()); workCenter.promoteLeader(); assertEquals(4, workCenter.getWorkers().size()); assertEquals(workCenter.getWorkers().get(0), workCenter.getLeader()); } }
2,446
36.075758
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskHandlerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderfollowers; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Tests for TaskHandler */ class TaskHandlerTest { @Test void testHandleTask() throws InterruptedException { var taskHandler = new TaskHandler(); var handle = new Task(100); taskHandler.handleTask(handle); assertTrue(handle.isFinished()); } }
1,692
36.622222
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskSetTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderfollowers; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Tests for TaskSet */ class TaskSetTest { @Test void testAddTask() throws InterruptedException { var taskSet = new TaskSet(); taskSet.addTask(new Task(10)); assertEquals(1, taskSet.getSize()); } @Test void testGetTask() throws InterruptedException { var taskSet = new TaskSet(); taskSet.addTask(new Task(100)); Task task = taskSet.getTask(); assertEquals(100, task.getTime()); assertEquals(0, taskSet.getSize()); } }
1,892
34.716981
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/test/java/com/iluwatar/leaderfollowers/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.leaderfollowers; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,595
37
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderfollowers; import lombok.extern.slf4j.Slf4j; /** * The TaskHandler is used by the {@link Worker} to process the newly arrived task. */ @Slf4j public class TaskHandler { /** * This interface handles one task at a time. */ public void handleTask(Task task) throws InterruptedException { var time = task.getTime(); Thread.sleep(time); LOGGER.info("It takes " + time + " milliseconds to finish the task"); task.setFinished(); } }
1,771
37.521739
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/main/java/com/iluwatar/leaderfollowers/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.leaderfollowers; import java.security.SecureRandom; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Leader/Followers pattern is a concurrency pattern. This pattern behaves like a taxi stand where * one of the threads acts as leader thread which listens for event from event sources, * de-multiplexes, dispatches and handles the event. It promotes the follower to be the new leader. * When processing completes the thread joins the followers queue, if there are no followers then it * becomes the leader and cycle repeats again. * * <p>In this example, one of the workers becomes Leader and listens on the {@link TaskSet} for * work. {@link TaskSet} basically acts as the source of input events for the {@link Worker}, who * are spawned and controlled by the {@link WorkCenter} . When {@link Task} arrives then the leader * takes the work and calls the {@link TaskHandler}. It also calls the {@link WorkCenter} to * promotes one of the followers to be the new leader, who can then process the next work and so * on. * * <p>The pros for this pattern are: * It enhances CPU cache affinity and eliminates unbound allocation and data buffer sharing between * threads by reading the request into buffer space allocated on the stack of the leader or by using * the Thread-Specific Storage pattern [22] to allocate memory. It minimizes locking overhead by not * exchanging data between threads, thereby reducing thread synchronization. In bound handle/thread * associations, the leader thread dispatches the event based on the I/O handle. It can minimize * priority inversion because no extra queuing is introduced in the server. It does not require a * context switch to handle each event, reducing the event dispatching latency. Note that promoting * a follower thread to fulfill the leader role requires a context switch. Programming simplicity: * The Leader/Followers pattern simplifies the programming of concurrency models where multiple * threads can receive requests, process responses, and de-multiplex connections using a shared * handle set. */ public class App { /** * The main method for the leader followers pattern. */ public static void main(String[] args) throws InterruptedException { var taskSet = new TaskSet(); var taskHandler = new TaskHandler(); var workCenter = new WorkCenter(); workCenter.createWorkers(4, taskSet, taskHandler); execute(workCenter, taskSet); } /** * Start the work, dispatch tasks and stop the thread pool at last. */ private static void execute(WorkCenter workCenter, TaskSet taskSet) throws InterruptedException { var workers = workCenter.getWorkers(); var exec = Executors.newFixedThreadPool(workers.size()); workers.forEach(exec::submit); Thread.sleep(1000); addTasks(taskSet); exec.awaitTermination(2, TimeUnit.SECONDS); exec.shutdownNow(); } /** * Add tasks. */ private static void addTasks(TaskSet taskSet) throws InterruptedException { var rand = new SecureRandom(); for (var i = 0; i < 5; i++) { var time = Math.abs(rand.nextInt(1000)); taskSet.addTask(new Task(time)); } } }
4,499
46.368421
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderfollowers; /** * A unit of work to be processed by the Workers. */ public class Task { private final int time; private boolean finished; public Task(int time) { this.time = time; } public int getTime() { return time; } public void setFinished() { this.finished = true; } public boolean isFinished() { return this.finished; } }
1,684
30.792453
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderfollowers; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * A TaskSet is a collection of the tasks, the leader receives task from here. */ public class TaskSet { private final BlockingQueue<Task> queue = new ArrayBlockingQueue<>(100); public void addTask(Task task) throws InterruptedException { queue.put(task); } public Task getTask() throws InterruptedException { return queue.take(); } public int getSize() { return queue.size(); } }
1,831
36.387755
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderfollowers; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; /** * Worker class that takes work from work center. */ @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Slf4j public class Worker implements Runnable { @EqualsAndHashCode.Include private final long id; private final WorkCenter workCenter; private final TaskSet taskSet; private final TaskHandler taskHandler; /** * Constructor to create a worker which will take work from the work center. */ public Worker(long id, WorkCenter workCenter, TaskSet taskSet, TaskHandler taskHandler) { super(); this.id = id; this.workCenter = workCenter; this.taskSet = taskSet; this.taskHandler = taskHandler; } /** * The leader thread listens for task. When task arrives, it promotes one of the followers to be * the new leader. Then it handles the task and add himself back to work center. */ @Override public void run() { while (!Thread.interrupted()) { try { if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) { synchronized (workCenter) { if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) { workCenter.wait(); continue; } } } final Task task = taskSet.getTask(); synchronized (workCenter) { workCenter.removeWorker(this); workCenter.promoteLeader(); workCenter.notifyAll(); } taskHandler.handleTask(task); LOGGER.info("The Worker with the ID " + id + " completed the task"); workCenter.addWorker(this); } catch (InterruptedException e) { LOGGER.warn("Worker interrupted"); Thread.currentThread().interrupt(); return; } } } }
3,137
34.659091
140
java
java-design-patterns
java-design-patterns-master/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.leaderfollowers; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * A WorkCenter contains a leader and a list of idle workers. The leader is responsible for * receiving work when it arrives. This class also provides a mechanism to promote a new leader. A * worker once he completes his task will add himself back to the center. */ public class WorkCenter { private Worker leader; private final List<Worker> workers = new CopyOnWriteArrayList<>(); /** * Create workers and set leader. */ public void createWorkers(int numberOfWorkers, TaskSet taskSet, TaskHandler taskHandler) { for (var id = 1; id <= numberOfWorkers; id++) { var worker = new Worker(id, this, taskSet, taskHandler); workers.add(worker); } promoteLeader(); } public void addWorker(Worker worker) { workers.add(worker); } public void removeWorker(Worker worker) { workers.remove(worker); } public Worker getLeader() { return leader; } /** * Promote a leader. */ public void promoteLeader() { Worker leader = null; if (workers.size() > 0) { leader = workers.get(0); } this.leader = leader; } public List<Worker> getWorkers() { return workers; } }
2,563
31.871795
140
java
java-design-patterns
java-design-patterns-master/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.parameter.object; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; class ParameterObjectTest { private static final Logger LOGGER = LoggerFactory.getLogger(ParameterObjectTest.class); @Test void testForDefaultSortBy() { //Creating parameter object with default value for SortBy set ParameterObject params = ParameterObject.newBuilder() .withType("sneakers") .sortOrder(SortOrder.DESC) .build(); assertEquals(ParameterObject.DEFAULT_SORT_BY, params.getSortBy(), "Default SortBy is not set."); LOGGER.info("{} Default parameter value is set during object creation as no value is passed." , "SortBy"); } @Test void testForDefaultSortOrder() { //Creating parameter object with default value for SortOrder set ParameterObject params = ParameterObject.newBuilder() .withType("sneakers") .sortBy("brand") .build(); assertEquals(ParameterObject.DEFAULT_SORT_ORDER, params.getSortOrder(), "Default SortOrder is not set."); LOGGER.info("{} Default parameter value is set during object creation as no value is passed." , "SortOrder"); } }
2,571
38.569231
140
java
java-design-patterns
java-design-patterns-master/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.parameter.object; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; class SearchServiceTest { private static final Logger LOGGER = LoggerFactory.getLogger(SearchServiceTest.class); private ParameterObject parameterObject; private SearchService searchService; @BeforeEach void setUp() { //Creating parameter object with default values set parameterObject = ParameterObject.newBuilder() .withType("sneakers") .build(); searchService = new SearchService(); } /** * Testing parameter object against the overloaded method to verify if the behaviour is same. */ @Test void testDefaultParametersMatch() { assertEquals(searchService.search(parameterObject), searchService.search("sneakers", SortOrder.ASC), "Default Parameter values do not not match."); LOGGER.info("SortBy Default parameter value matches."); assertEquals(searchService.search(parameterObject), searchService.search("sneakers", "price"), "Default Parameter values do not not match."); LOGGER.info("SortOrder Default parameter value matches."); LOGGER.info("testDefaultParametersMatch executed successfully without errors."); } }
2,636
39.569231
140
java
java-design-patterns
java-design-patterns-master/parameter-object/src/test/java/com/iluwatar/parameter/object/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.parameter.object; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,594
38.875
140
java
java-design-patterns
java-design-patterns-master/parameter-object/src/main/java/com/iluwatar/parameter/object/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.parameter.object; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The syntax of Java language doesn’t allow you to declare a method with a predefined value * for a parameter. Probably the best option to achieve default method parameters in Java is * by using the method overloading. Method overloading allows you to declare several methods * with the same name but with a different number of parameters. But the main problem with * method overloading as a solution for default parameter values reveals itself when a method * accepts multiple parameters. Creating an overloaded method for each possible combination of * parameters might be cumbersome. To deal with this issue, the Parameter Object pattern is used. * The Parameter Object is simply a wrapper object for all parameters of a method. * It is nothing more than just a regular POJO. The advantage of the Parameter Object over a * regular method parameter list is the fact that class fields can have default values. * Once the wrapper class is created for the method parameter list, a corresponding builder class * is also created. Usually it's an inner static class. The final step is to use the builder * to construct a new parameter object. For those parameters that are skipped, * their default values are going to be used. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { ParameterObject params = ParameterObject.newBuilder() .withType("sneakers") .sortBy("brand") .build(); LOGGER.info(params.toString()); LOGGER.info(new SearchService().search(params)); } }
3,070
46.984375
140
java
java-design-patterns
java-design-patterns-master/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.parameter.object; /** * enum for sort order types. */ public enum SortOrder { ASC("asc"), DESC("desc"); private String value; SortOrder(String value) { this.value = value; } public String getValue() { return value; } }
1,552
34.295455
140
java
java-design-patterns
java-design-patterns-master/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.parameter.object; /** * SearchService to demonstrate parameter object pattern. */ public class SearchService { /** * Below two methods of name `search` is overloaded so that we can send a default value for * one of the criteria and call the final api. A default SortOrder is sent in the first method * and a default SortBy is sent in the second method. So two separate method definitions are * needed for having default values for one argument in each case. Hence multiple overloaded * methods are needed as the number of argument increases. */ public String search(String type, String sortBy) { return getQuerySummary(type, sortBy, SortOrder.ASC); } public String search(String type, SortOrder sortOrder) { return getQuerySummary(type, "price", sortOrder); } /** * The need for multiple method definitions can be avoided by the Parameter Object pattern. * Below is the example where only one method is required and all the logic for having default * values are abstracted into the Parameter Object at the time of object creation. */ public String search(ParameterObject parameterObject) { return getQuerySummary(parameterObject.getType(), parameterObject.getSortBy(), parameterObject.getSortOrder()); } private String getQuerySummary(String type, String sortBy, SortOrder sortOrder) { return String.format("Requesting shoes of type \"%s\" sorted by \"%s\" in \"%sending\" order..", type, sortBy, sortOrder.getValue()); } }
2,835
42.630769
140
java
java-design-patterns
java-design-patterns-master/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.parameter.object; /** * ParameterObject. */ public class ParameterObject { /** * Default values are defined here. */ public static final String DEFAULT_SORT_BY = "price"; public static final SortOrder DEFAULT_SORT_ORDER = SortOrder.ASC; private String type; /** * Default values are assigned here. */ private String sortBy = DEFAULT_SORT_BY; private SortOrder sortOrder = DEFAULT_SORT_ORDER; /** * Overriding default values on object creation only when builder object has a valid value. */ private ParameterObject(Builder builder) { setType(builder.type); setSortBy(builder.sortBy != null && !builder.sortBy.isBlank() ? builder.sortBy : sortBy); setSortOrder(builder.sortOrder != null ? builder.sortOrder : sortOrder); } public static Builder newBuilder() { return new Builder(); } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSortBy() { return sortBy; } public void setSortBy(String sortBy) { this.sortBy = sortBy; } public SortOrder getSortOrder() { return sortOrder; } public void setSortOrder(SortOrder sortOrder) { this.sortOrder = sortOrder; } @Override public String toString() { return String.format("ParameterObject[type='%s', sortBy='%s', sortOrder='%s']", type, sortBy, sortOrder); } /** * Builder for ParameterObject. */ public static final class Builder { private String type; private String sortBy; private SortOrder sortOrder; private Builder() { } public Builder withType(String type) { this.type = type; return this; } public Builder sortBy(String sortBy) { this.sortBy = sortBy; return this; } public Builder sortOrder(SortOrder sortOrder) { this.sortOrder = sortOrder; return this; } public ParameterObject build() { return new ParameterObject(this); } } }
3,301
26.289256
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Date: 12/13/15 - 2:17 PM * * @author Jeroen Meulemeester */ class FilterTest { private static final Order PERFECT_ORDER = new Order("name", "12345678901", "addr", "dep", "order"); private static final Order WRONG_ORDER = new Order("name", "12345678901", "addr", "dep", ""); private static final Order WRONG_DEPOSIT = new Order("name", "12345678901", "addr", "", "order"); private static final Order WRONG_ADDRESS = new Order("name", "12345678901", "", "dep", "order"); private static final Order WRONG_CONTACT = new Order("name", "", "addr", "dep", "order"); private static final Order WRONG_NAME = new Order("", "12345678901", "addr", "dep", "order"); static List<Object[]> getTestData() { return List.of( new Object[]{new NameFilter(), PERFECT_ORDER, ""}, new Object[]{new NameFilter(), WRONG_NAME, "Invalid name!"}, new Object[]{new NameFilter(), WRONG_CONTACT, ""}, new Object[]{new NameFilter(), WRONG_ADDRESS, ""}, new Object[]{new NameFilter(), WRONG_DEPOSIT, ""}, new Object[]{new NameFilter(), WRONG_ORDER, ""}, new Object[]{new ContactFilter(), PERFECT_ORDER, ""}, new Object[]{new ContactFilter(), WRONG_NAME, ""}, new Object[]{new ContactFilter(), WRONG_CONTACT, "Invalid contact number!"}, new Object[]{new ContactFilter(), WRONG_ADDRESS, ""}, new Object[]{new ContactFilter(), WRONG_DEPOSIT, ""}, new Object[]{new ContactFilter(), WRONG_ORDER, ""}, new Object[]{new AddressFilter(), PERFECT_ORDER, ""}, new Object[]{new AddressFilter(), WRONG_NAME, ""}, new Object[]{new AddressFilter(), WRONG_CONTACT, ""}, new Object[]{new AddressFilter(), WRONG_ADDRESS, "Invalid address!"}, new Object[]{new AddressFilter(), WRONG_DEPOSIT, ""}, new Object[]{new AddressFilter(), WRONG_ORDER, ""}, new Object[]{new DepositFilter(), PERFECT_ORDER, ""}, new Object[]{new DepositFilter(), WRONG_NAME, ""}, new Object[]{new DepositFilter(), WRONG_CONTACT, ""}, new Object[]{new DepositFilter(), WRONG_ADDRESS, ""}, new Object[]{new DepositFilter(), WRONG_DEPOSIT, "Invalid deposit number!"}, new Object[]{new DepositFilter(), WRONG_ORDER, ""}, new Object[]{new OrderFilter(), PERFECT_ORDER, ""}, new Object[]{new OrderFilter(), WRONG_NAME, ""}, new Object[]{new OrderFilter(), WRONG_CONTACT, ""}, new Object[]{new OrderFilter(), WRONG_ADDRESS, ""}, new Object[]{new OrderFilter(), WRONG_DEPOSIT, ""}, new Object[]{new OrderFilter(), WRONG_ORDER, "Invalid order!"} ); } @ParameterizedTest @MethodSource("getTestData") void testExecute(Filter filter, Order order, String expectedResult) { final var result = filter.execute(order); assertNotNull(result); assertEquals(expectedResult, result.trim()); } @ParameterizedTest @MethodSource("getTestData") void testNext(Filter filter) { assertNull(filter.getNext()); assertSame(filter, filter.getLast()); } }
4,770
44.009434
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; /** * Date: 12/13/15 - 3:01 PM * * @author Jeroen Meulemeester */ class FilterManagerTest { @Test void testFilterRequest() { final var target = mock(Target.class); final var filterManager = new FilterManager(); assertEquals("RUNNING...", filterManager.filterRequest(mock(Order.class))); verifyNoMoreInteractions(target); } @Test void testAddFilter() { final var target = mock(Target.class); final var filterManager = new FilterManager(); verifyNoMoreInteractions(target); final var filter = mock(Filter.class); when(filter.execute(any(Order.class))).thenReturn("filter"); filterManager.addFilter(filter); final Order order = mock(Order.class); assertEquals("filter", filterManager.filterRequest(order)); verify(filter, times(1)).execute(any(Order.class)); verifyNoMoreInteractions(target, filter, order); } }
2,583
35.914286
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/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.intercepting.filter; 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,599
38.02439
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Date: 12/13/15 - 2:57 PM * * @author Jeroen Meulemeester */ class OrderTest { private static final String EXPECTED_VALUE = "test"; @Test void testSetName() { final var order = new Order(); order.setName(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getName()); } @Test void testSetContactNumber() { final var order = new Order(); order.setContactNumber(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getContactNumber()); } @Test void testSetAddress() { final var order = new Order(); order.setAddress(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getAddress()); } @Test void testSetDepositNumber() { final var order = new Order(); order.setDepositNumber(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getDepositNumber()); } @Test void testSetOrder() { final var order = new Order(); order.setOrderItem(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getOrderItem()); } }
2,431
31
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/TargetTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; /** * Date: 01/29/23 - 1:33 PM * * @author Rahul Raj */ class TargetTest { @Test void testSetup(){ final var target = new Target(); assertEquals(target.getSize().getWidth(), Double.valueOf(640)); assertEquals(target.getSize().getHeight(), Double.valueOf(480)); assertEquals(true,target.isVisible()); } }
1,844
38.255319
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Concrete implementation of filter This checks for the deposit code. * * @author joshzambales */ public class DepositFilter extends AbstractFilter { @Override public String execute(Order order) { var result = super.execute(order); var depositNumber = order.getDepositNumber(); if (depositNumber == null || depositNumber.isEmpty()) { return result + "Invalid deposit number! "; } else { return result; } } }
1,782
38.622222
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Concrete implementation of filter This filter is responsible for checking/filtering the input in * the address field. * * @author joshzambales */ public class AddressFilter extends AbstractFilter { @Override public String execute(Order order) { var result = super.execute(order); if (order.getAddress() == null || order.getAddress().isEmpty()) { return result + "Invalid address! "; } else { return result; } } }
1,786
38.711111
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/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.intercepting.filter; /** * When a request enters a Web application, it often must pass several entrance tests prior to the * main processing stage. For example, - Has the client been authenticated? - Does the client have a * valid session? - Is the client's IP address from a trusted network? - Does the request path * violate any constraints? - What encoding does the client use to send the data? - Do we support * the browser type of the client? Some of these checks are tests, resulting in a yes or no answer * that determines whether processing will continue. Other checks manipulate the incoming data * stream into a form suitable for processing. * * <p>The classic solution consists of a series of conditional checks, with any failed check * aborting the request. Nested if/else statements are a standard strategy, but this solution leads * to code fragility and a copy-and-paste style of programming, because the flow of the filtering * and the action of the filters is compiled into the application. * * <p>The key to solving this problem in a flexible and unobtrusive manner is to have a simple * mechanism for adding and removing processing components, in which each component completes a * specific filtering action. This is the Intercepting Filter pattern in action. * * <p>In this example we check whether the order request is valid through pre-processing done via * {@link Filter}. Each field has its own corresponding {@link Filter}. * * @author joshzambales */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var filterManager = new FilterManager(); filterManager.addFilter(new NameFilter()); filterManager.addFilter(new ContactFilter()); filterManager.addFilter(new AddressFilter()); filterManager.addFilter(new DepositFilter()); filterManager.addFilter(new OrderFilter()); var client = new Client(); client.setFilterManager(filterManager); } }
3,318
47.101449
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.util.Arrays; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; /** * The Client class is responsible for handling the input and running them through filters inside * the {@link FilterManager}. * * <p>This is where {@link Filter}s come to play as the client pre-processes the request before * being displayed in the {@link Target}. * * @author joshzambales */ public class Client extends JFrame { // NOSONAR private static final long serialVersionUID = 1L; private transient FilterManager filterManager; private final JLabel jl; private final JTextField[] jtFields; private final JTextArea[] jtAreas; private final JButton clearButton; private final JButton processButton; /** * Constructor. */ public Client() { super("Client System"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(300, 300); jl = new JLabel("RUNNING..."); jtFields = new JTextField[3]; for (var i = 0; i < 3; i++) { jtFields[i] = new JTextField(); } jtAreas = new JTextArea[2]; for (var i = 0; i < 2; i++) { jtAreas[i] = new JTextArea(); } clearButton = new JButton("Clear"); processButton = new JButton("Process"); setup(); } private void setup() { setLayout(new BorderLayout()); var panel = new JPanel(); add(jl, BorderLayout.SOUTH); add(panel, BorderLayout.CENTER); panel.setLayout(new GridLayout(6, 2)); panel.add(new JLabel("Name")); panel.add(jtFields[0]); panel.add(new JLabel("Contact Number")); panel.add(jtFields[1]); panel.add(new JLabel("Address")); panel.add(jtAreas[0]); panel.add(new JLabel("Deposit Number")); panel.add(jtFields[2]); panel.add(new JLabel("Order")); panel.add(jtAreas[1]); panel.add(clearButton); panel.add(processButton); clearButton.addActionListener(e -> { Arrays.stream(jtAreas).forEach(i -> i.setText("")); Arrays.stream(jtFields).forEach(i -> i.setText("")); }); processButton.addActionListener(this::actionPerformed); JRootPane rootPane = SwingUtilities.getRootPane(processButton); rootPane.setDefaultButton(processButton); setVisible(true); } public void setFilterManager(FilterManager filterManager) { this.filterManager = filterManager; } public String sendRequest(Order order) { return filterManager.filterRequest(order); } private void actionPerformed(ActionEvent e) { var fieldText1 = jtFields[0].getText(); var fieldText2 = jtFields[1].getText(); var areaText1 = jtAreas[0].getText(); var fieldText3 = jtFields[2].getText(); var areaText2 = jtAreas[1].getText(); var order = new Order(fieldText1, fieldText2, areaText1, fieldText3, areaText2); jl.setText(sendRequest(order)); } }
4,432
32.583333
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Filter Chain carries multiple filters and help to execute them in defined order on target. * * @author joshzambales */ public class FilterChain { private Filter chain; /** * Adds filter. */ public void addFilter(Filter filter) { if (chain == null) { chain = filter; } else { chain.getLast().setNext(filter); } } /** * Execute filter chain. */ public String execute(Order order) { if (chain != null) { return chain.execute(order); } else { return "RUNNING..."; } } }
1,882
30.383333
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Concrete implementation of filter. This filter checks if the input in the Name field is valid. * (alphanumeric) * * @author joshzambales */ public class NameFilter extends AbstractFilter { @Override public String execute(Order order) { var result = super.execute(order); var name = order.getName(); if (name == null || name.isEmpty() || name.matches(".*[^\\w|\\s]+.*")) { return result + "Invalid name! "; } else { return result; } } }
1,813
38.434783
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Order class carries the order data. */ public class Order { private String name; private String contactNumber; private String address; private String depositNumber; private String orderItem; public Order() { } /** * Constructor. */ public Order( String name, String contactNumber, String address, String depositNumber, String order ) { this.name = name; this.contactNumber = contactNumber; this.address = address; this.depositNumber = depositNumber; this.orderItem = order; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDepositNumber() { return depositNumber; } public void setDepositNumber(String depositNumber) { this.depositNumber = depositNumber; } public String getOrderItem() { return orderItem; } public void setOrderItem(String order) { this.orderItem = order; } }
2,594
26.315789
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Concrete implementation of filter. This checks for the order field. * * @author joshzambales */ public class OrderFilter extends AbstractFilter { @Override public String execute(Order order) { var result = super.execute(order); var orderItem = order.getOrderItem(); if (orderItem == null || orderItem.isEmpty()) { return result + "Invalid order! "; } else { return result; } } }
1,755
38.022222
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Filters perform certain tasks prior or after execution of request by request handler. In this * case, before the request is handled by the target, the request undergoes through each Filter * * @author joshzambales */ public interface Filter { /** * Execute order processing filter. */ String execute(Order order); /** * Set next filter in chain after this. */ void setNext(Filter filter); /** * Get next filter in chain after this. */ Filter getNext(); /** * Get last filter in the chain. */ Filter getLast(); }
1,894
33.454545
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Base class for order processing filters. Handles chain management. */ public abstract class AbstractFilter implements Filter { private Filter next; public AbstractFilter() { } public AbstractFilter(Filter next) { this.next = next; } @Override public void setNext(Filter filter) { this.next = filter; } @Override public Filter getNext() { return next; } @Override public Filter getLast() { Filter last = this; while (last.getNext() != null) { last = last.getNext(); } return last; } @Override public String execute(Order order) { if (getNext() != null) { return getNext().execute(order); } else { return ""; } } }
2,047
28.681159
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Filter Manager manages the filters and {@link FilterChain}. * * @author joshzambales */ public class FilterManager { private final FilterChain filterChain; public FilterManager() { filterChain = new FilterChain(); } public void addFilter(Filter filter) { filterChain.addFilter(filter); } public String filterRequest(Order order) { return filterChain.execute(order); } }
1,737
35.208333
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; /** * Concrete implementation of filter This filter checks for the contact field in which it checks if * the input consist of numbers and it also checks if the input follows the length constraint (11 * digits). * * @author joshzambales */ public class ContactFilter extends AbstractFilter { @Override public String execute(Order order) { var result = super.execute(order); var contactNumber = order.getContactNumber(); if (contactNumber == null || contactNumber.isEmpty() || contactNumber.matches(".*[^\\d]+.*") || contactNumber.length() != 11) { return result + "Invalid contact number! "; } else { return result; } } }
2,009
40.020408
140
java
java-design-patterns
java-design-patterns-master/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.intercepting.filter; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.stream.IntStream; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; /** * This is where the requests are displayed after being validated by filters. * * @author mjoshzambales */ public class Target extends JFrame { //NOSONAR private static final long serialVersionUID = 1L; private final JTable jt; private final DefaultTableModel dtm; private final JButton del; /** * Constructor. */ public Target() { super("Order System"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(640, 480); dtm = new DefaultTableModel( new Object[]{"Name", "Contact Number", "Address", "Deposit Number", "Order"}, 0); jt = new JTable(dtm); del = new JButton("Delete"); setup(); } private void setup() { setLayout(new BorderLayout()); var bot = new JPanel(); add(jt.getTableHeader(), BorderLayout.NORTH); bot.setLayout(new BorderLayout()); bot.add(del, BorderLayout.EAST); add(bot, BorderLayout.SOUTH); var jsp = new JScrollPane(jt); jsp.setPreferredSize(new Dimension(500, 250)); add(jsp, BorderLayout.CENTER); del.addActionListener(new TargetListener()); var rootPane = SwingUtilities.getRootPane(del); rootPane.setDefaultButton(del); setVisible(true); } public void execute(String[] request) { dtm.addRow(new Object[]{request[0], request[1], request[2], request[3], request[4]}); } class TargetListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { var temp = jt.getSelectedRow(); if (temp == -1) { return; } var temp2 = jt.getSelectedRowCount(); IntStream.range(0, temp2).forEach(i -> dtm.removeRow(temp)); } } }
3,415
32.490196
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.front.controller.utils.InMemoryAppender; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Date: 12/13/15 - 1:39 PM * * @author Jeroen Meulemeester */ class ViewTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } static List<Object[]> dataProvider() { return List.of( new Object[]{new ArcherView(), "Displaying archers"}, new Object[]{new CatapultView(), "Displaying catapults"}, new Object[]{new ErrorView(), "Error 500"} ); } /** * @param view The view that's been tested * @param displayMessage The expected display message */ @ParameterizedTest @MethodSource("dataProvider") void testDisplay(View view, String displayMessage) { assertEquals(0, appender.getLogSize()); view.display(); assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } }
2,577
32.480519
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.front.controller.utils.InMemoryAppender; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Date: 12/13/15 - 1:39 PM * * @author Jeroen Meulemeester */ class FrontControllerTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } static List<Object[]> dataProvider() { return List.of( new Object[]{new ArcherCommand(), "Displaying archers"}, new Object[]{new CatapultCommand(), "Displaying catapults"}, new Object[]{new UnknownCommand(), "Error 500"} ); } /** * @param command The command that's been tested * @param displayMessage The expected display message */ @ParameterizedTest @MethodSource("dataProvider") void testDisplay(Command command, String displayMessage) { assertEquals(0, appender.getLogSize()); command.process(); assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } }
2,611
32.922078
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.api.Test; /** * Date: 12/13/15 - 1:35 PM * * @author Jeroen Meulemeester */ class ApplicationExceptionTest { @Test void testCause() { final var cause = new Exception(); assertSame(cause, new ApplicationException(cause).getCause()); } }
1,665
36.863636
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.front.controller.utils.InMemoryAppender; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Date: 12/13/15 - 1:39 PM * * @author Jeroen Meulemeester */ class CommandTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } static List<Object[]> dataProvider() { return List.of( new Object[]{"Archer", "Displaying archers"}, new Object[]{"Catapult", "Displaying catapults"}, new Object[]{"NonExistentCommand", "Error 500"} ); } /** * @param request The request that's been tested * @param displayMessage The expected display message */ @ParameterizedTest @MethodSource("dataProvider") void testDisplay(String request, String displayMessage) { final var frontController = new FrontController(); assertEquals(0, appender.getLogSize()); frontController.handleRequest(request); assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } }
2,656
33.064103
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; 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,595
37.926829
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller.utils; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; /** * InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public String getLastMessage() { return log.get(log.size() - 1).getFormattedMessage(); } public int getLogSize() { return log.size(); } }
2,079
34.254237
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; /** * The Front Controller is a presentation tier pattern. Essentially it defines a controller that * handles all requests for a web site. * * <p>The Front Controller pattern consolidates request handling through a single handler object ( * {@link FrontController}). This object can carry out the common the behavior such as * authorization, request logging and routing requests to corresponding views. * * <p>Typically the requests are mapped to command objects ({@link Command}) which then display the * correct view ({@link View}). * * <p>In this example we have implemented two views: {@link ArcherView} and {@link CatapultView}. * These are displayed by sending correct request to the {@link FrontController} object. For * example, the {@link ArcherView} gets displayed when {@link FrontController} receives request * "Archer". When the request is unknown, we display the error view ({@link ErrorView}). */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var controller = new FrontController(); controller.handleRequest("Archer"); controller.handleRequest("Catapult"); controller.handleRequest("foobar"); } }
2,564
44
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; /** * FrontController is the handler class that takes in all the requests and renders the correct * response. */ public class FrontController { public void handleRequest(String request) { var command = getCommand(request); command.process(); } private Command getCommand(String request) { var commandClass = getCommandClass(request); try { return (Command) commandClass.newInstance(); } catch (Exception e) { throw new ApplicationException(e); } } private static Class<?> getCommandClass(String request) { try { return Class.forName("com.iluwatar.front.controller." + request + "Command"); } catch (ClassNotFoundException e) { return UnknownCommand.class; } } }
2,064
36.545455
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; /** * Custom exception type. */ public class ApplicationException extends RuntimeException { private static final long serialVersionUID = 1L; public ApplicationException(Throwable cause) { super(cause); } }
1,545
39.684211
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/Command.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; /** * Commands are the intermediary between requests and views. */ public interface Command { void process(); }
1,441
41.411765
140
java
java-design-patterns
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; /** * Command for catapults. */ public class CatapultCommand implements Command { @Override public void process() { new CatapultView().display(); } }
1,487
39.216216
140
java