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/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectingparameter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.LinkedList;
import java.util.Queue;
import static org.junit.jupiter.api.Assertions.*;
class PrinterQueueTest {
@Test
@Timeout(1000)
void singletonTest() {
PrinterQueue printerQueue1 = PrinterQueue.getInstance();
PrinterQueue printerQueue2 = PrinterQueue.getInstance();
assertSame(printerQueue1, printerQueue2);
}
@Test()
@Timeout(1000)
void negativePageCount() throws IllegalArgumentException {
Assertions.assertThrows(IllegalArgumentException.class, () -> new PrinterItem(PaperSizes.A4, -1, true, true));
}
@Test()
@Timeout(1000)
void nullPageSize() throws IllegalArgumentException {
Assertions.assertThrows(IllegalArgumentException.class, () -> new PrinterItem(null, 1, true, true));
}
} | 2,197 | 37.561404 | 140 | java |
java-design-patterns | java-design-patterns-master/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectingparameter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.LinkedList;
import java.util.Queue;
class CollectingParameterTest {
@Test
@Timeout(1000)
void testCollectingParameter() {
PrinterQueue printerQueue = PrinterQueue.getInstance();
printerQueue.emptyQueue();
PrinterItem item1 = new PrinterItem(PaperSizes.A4, 1, false, true);
PrinterItem item2 = new PrinterItem(PaperSizes.A4, 10, true, false);
PrinterItem item3 = new PrinterItem(PaperSizes.A4, 4, true, true);
PrinterItem item4 = new PrinterItem(PaperSizes.A3, 9, false, false);
PrinterItem item5 = new PrinterItem(PaperSizes.A3, 3, true, true);
PrinterItem item6 = new PrinterItem(PaperSizes.A3, 3, false, true);
PrinterItem item7 = new PrinterItem(PaperSizes.A3, 3, true, false);
PrinterItem item8 = new PrinterItem(PaperSizes.A2, 1, false, false);
PrinterItem item9 = new PrinterItem(PaperSizes.A2, 2, false, false);
PrinterItem item10 = new PrinterItem(PaperSizes.A2, 1, true, false);
PrinterItem item11 = new PrinterItem(PaperSizes.A2, 1, false, true);
printerQueue.addPrinterItem(item1);
printerQueue.addPrinterItem(item2);
printerQueue.addPrinterItem(item3);
printerQueue.addPrinterItem(item4);
printerQueue.addPrinterItem(item5);
printerQueue.addPrinterItem(item6);
printerQueue.addPrinterItem(item7);
printerQueue.addPrinterItem(item8);
printerQueue.addPrinterItem(item9);
printerQueue.addPrinterItem(item10);
printerQueue.addPrinterItem(item11);
Queue<PrinterItem> result = new LinkedList<>();
App.addValidA4Papers(result);
App.addValidA3Papers(result);
App.addValidA2Papers(result);
Queue<PrinterItem> testResult = new LinkedList<>();
testResult.add(item1);
testResult.add(item2);
testResult.add(item4);
testResult.add(item8);
Assertions.assertArrayEquals(testResult.toArray(), result.toArray());
}
}
| 3,320 | 41.037975 | 140 | java |
java-design-patterns | java-design-patterns-master/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/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.collectingparameter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
class AppTest {
/**
* Checks whether {@link App} executes without throwing exception
*/
@Test
void executesWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,633 | 39.85 | 140 | java |
java-design-patterns | java-design-patterns-master/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/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.collectingparameter;
import java.util.LinkedList;
import java.util.Queue;
/**
* The Collecting Parameter Design Pattern aims to return a result that is the collaborative result of several
* methods. This design pattern uses a 'collecting parameter' that is passed to several functions, accumulating results
* as it travels from method-to-method. This is different to the Composed Method design pattern, where a single
* collection is modified via several methods.
*
* <p>This example is inspired by Kent Beck's example in his book, 'Smalltalk Best Practice Patterns'. The context for this
* situation is that there is a single printer queue {@link PrinterQueue} that holds numerous print jobs
* {@link PrinterItem} that must be distributed to various print centers.
* Each print center has its own requirements and printing limitations. In this example, the following requirements are:
* If an A4 document is coloured, it must also be single-sided. All other non-coloured A4 documents are accepted.
* All A3 documents must be non-coloured and single sided. All A2 documents must be a single page, single sided, and
* non-coloured.
*
* <p>A collecting parameter (the result variable) is used to filter the global printer queue so that it meets the
* requirements for this centre,
**/
public class App {
static PrinterQueue printerQueue = PrinterQueue.getInstance();
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
/*
Initialising the printer queue with jobs
*/
printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false));
printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false));
printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false));
/*
This variable is the collecting parameter, and will store the policy abiding print jobs.
*/
var result = new LinkedList<PrinterItem>();
/*
Adding A4, A3, and A2 papers that obey the policy
*/
addValidA4Papers(result);
addValidA3Papers(result);
addValidA2Papers(result);
}
/**
* Adds A4 document jobs to the collecting parameter according to some policy that can be whatever the client
* (the print center) wants.
*
* @param printerItemsCollection the collecting parameter
*/
public static void addValidA4Papers(Queue<PrinterItem> printerItemsCollection) {
/*
Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter,
which is 'printerItemsCollection' in this case.
*/
for (PrinterItem nextItem : printerQueue.getPrinterQueue()) {
if (nextItem.paperSize.equals(PaperSizes.A4)) {
var isColouredAndSingleSided = nextItem.isColour && !nextItem.isDoubleSided;
if (isColouredAndSingleSided || !nextItem.isColour) {
printerItemsCollection.add(nextItem);
}
}
}
}
/**
* Adds A3 document jobs to the collecting parameter according to some policy that can be whatever the client
* (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate
* the wants of the client.
*
* @param printerItemsCollection the collecting parameter
*/
public static void addValidA3Papers(Queue<PrinterItem> printerItemsCollection) {
for (PrinterItem nextItem : printerQueue.getPrinterQueue()) {
if (nextItem.paperSize.equals(PaperSizes.A3)) {
// Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at the same time
var isNotColouredAndSingleSided = !nextItem.isColour && !nextItem.isDoubleSided;
if (isNotColouredAndSingleSided) {
printerItemsCollection.add(nextItem);
}
}
}
}
/**
* Adds A2 document jobs to the collecting parameter according to some policy that can be whatever the client
* (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate
* the wants of the client.
*
* @param printerItemsCollection the collecting parameter
*/
public static void addValidA2Papers(Queue<PrinterItem> printerItemsCollection) {
for (PrinterItem nextItem : printerQueue.getPrinterQueue()) {
if (nextItem.paperSize.equals(PaperSizes.A2)) {
// Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and non-coloured.
var isNotColouredSingleSidedAndOnePage = nextItem.pageCount == 1 && !nextItem.isDoubleSided
&& !nextItem.isColour;
if (isNotColouredSingleSidedAndOnePage) {
printerItemsCollection.add(nextItem);
}
}
}
}
}
| 6,066 | 42.647482 | 140 | java |
java-design-patterns | java-design-patterns-master/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PaperSizes.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectingparameter;
enum PaperSizes {
A2,
A3,
A4
}
| 1,364 | 41.65625 | 140 | java |
java-design-patterns | java-design-patterns-master/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectingparameter;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
/**
* This class represents a singleton Printer Queue. It contains a queue that can be filled up with {@link PrinterItem}.
**/
public class PrinterQueue {
static PrinterQueue currentInstance = null;
private final Queue<PrinterItem> printerItemQueue;
/**
* This class is a singleton. The getInstance method will ensure that only one instance exists at a time.
*/
public static PrinterQueue getInstance() {
if (Objects.isNull(currentInstance)) {
currentInstance = new PrinterQueue();
}
return currentInstance;
}
/**
* Empty the printer queue.
*/
public void emptyQueue() {
currentInstance.getPrinterQueue().clear();
}
/**
* Private constructor prevents instantiation, unless using the getInstance() method.
*/
private PrinterQueue() {
printerItemQueue = new LinkedList<>();
}
public Queue<PrinterItem> getPrinterQueue() {
return currentInstance.printerItemQueue;
}
/**
* Adds a single print job to the queue.
*
* @param printerItem The printing job to be added to the queue
*/
public void addPrinterItem(PrinterItem printerItem) {
currentInstance.getPrinterQueue().add(printerItem);
}
}
| 2,597 | 32.74026 | 140 | java |
java-design-patterns | java-design-patterns-master/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectingparameter;
import java.util.Objects;
/**
* This class represents a Print Item, that should be added to the queue.
**/
public class PrinterItem {
PaperSizes paperSize;
int pageCount;
boolean isDoubleSided;
boolean isColour;
/**
* The {@link PrinterItem} constructor.
**/
public PrinterItem(PaperSizes paperSize, int pageCount, boolean isDoubleSided, boolean isColour) {
if (!Objects.isNull(paperSize)) {
this.paperSize = paperSize;
} else {
throw new IllegalArgumentException();
}
if (pageCount > 0) {
this.pageCount = pageCount;
} else {
throw new IllegalArgumentException();
}
this.isColour = isColour;
this.isDoubleSided = isDoubleSided;
}
} | 2,042 | 34.224138 | 140 | java |
java-design-patterns | java-design-patterns-master/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.compositeview;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.Assert.*;
class JavaBeansTest {
@Test
void testDefaultConstructor() {
ClientPropertiesBean newBean = new ClientPropertiesBean();
assertEquals("DEFAULT_NAME", newBean.getName());
assertTrue(newBean.isBusinessInterest());
assertTrue(newBean.isScienceNewsInterest());
assertTrue(newBean.isSportsInterest());
assertTrue(newBean.isWorldNewsInterest());
}
@Test
void testNameGetterSetter() {
ClientPropertiesBean newBean = new ClientPropertiesBean();
assertEquals("DEFAULT_NAME", newBean.getName());
newBean.setName("TEST_NAME_ONE");
assertEquals("TEST_NAME_ONE", newBean.getName());
}
@Test
void testBusinessSetterGetter() {
ClientPropertiesBean newBean = new ClientPropertiesBean();
assertTrue(newBean.isBusinessInterest());
newBean.setBusinessInterest(false);
assertFalse(newBean.isBusinessInterest());
}
@Test
void testScienceSetterGetter() {
ClientPropertiesBean newBean = new ClientPropertiesBean();
assertTrue(newBean.isScienceNewsInterest());
newBean.setScienceNewsInterest(false);
assertFalse(newBean.isScienceNewsInterest());
}
@Test
void testSportsSetterGetter() {
ClientPropertiesBean newBean = new ClientPropertiesBean();
assertTrue(newBean.isSportsInterest());
newBean.setSportsInterest(false);
assertFalse(newBean.isSportsInterest());
}
@Test
void testWorldSetterGetter() {
ClientPropertiesBean newBean = new ClientPropertiesBean();
assertTrue(newBean.isWorldNewsInterest());
newBean.setWorldNewsInterest(false);
assertFalse(newBean.isWorldNewsInterest());
}
@Test
void testRequestConstructor(){
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
ClientPropertiesBean newBean = new ClientPropertiesBean((mockReq));
assertEquals("DEFAULT_NAME", newBean.getName());
assertFalse(newBean.isWorldNewsInterest());
assertFalse(newBean.isBusinessInterest());
assertFalse(newBean.isScienceNewsInterest());
assertFalse(newBean.isSportsInterest());
}
}
| 3,682 | 37.364583 | 140 | java |
java-design-patterns | java-design-patterns-master/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.compositeview;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.PrintWriter;
import java.io.StringWriter;
import static org.junit.Assert.*;
/* Written with reference from https://stackoverflow.com/questions/5434419/how-to-test-my-servlet-using-junit
and https://stackoverflow.com/questions/50211433/servlets-unit-testing
*/
class AppServletTest extends Mockito{
private String msgPartOne = "<h1>This Server Doesn't Support";
private String msgPartTwo = "Requests</h1>\n"
+ "<h2>Use a GET request with boolean values for the following parameters<h2>\n"
+ "<h3>'name'</h3>\n<h3>'bus'</h3>\n<h3>'sports'</h3>\n<h3>'sci'</h3>\n<h3>'world'</h3>";
private String destination = "newsDisplay.jsp";
@Test
void testDoGet() throws Exception {
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
RequestDispatcher mockDispatcher = Mockito.mock(RequestDispatcher.class);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
when(mockResp.getWriter()).thenReturn(printWriter);
when(mockReq.getRequestDispatcher(destination)).thenReturn(mockDispatcher);
AppServlet curServlet = new AppServlet();
curServlet.doGet(mockReq, mockResp);
verify(mockReq, times(1)).getRequestDispatcher(destination);
verify(mockDispatcher).forward(mockReq, mockResp);
}
@Test
void testDoPost() throws Exception {
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
when(mockResp.getWriter()).thenReturn(printWriter);
AppServlet curServlet = new AppServlet();
curServlet.doPost(mockReq, mockResp);
printWriter.flush();
assertTrue(stringWriter.toString().contains(msgPartOne + " Post " + msgPartTwo));
}
@Test
void testDoPut() throws Exception {
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
when(mockResp.getWriter()).thenReturn(printWriter);
AppServlet curServlet = new AppServlet();
curServlet.doPut(mockReq, mockResp);
printWriter.flush();
assertTrue(stringWriter.toString().contains(msgPartOne + " Put " + msgPartTwo));
}
@Test
void testDoDelete() throws Exception {
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
when(mockResp.getWriter()).thenReturn(printWriter);
AppServlet curServlet = new AppServlet();
curServlet.doDelete(mockReq, mockResp);
printWriter.flush();
assertTrue(stringWriter.toString().contains(msgPartOne + " Delete " + msgPartTwo));
}
}
| 4,637 | 42.345794 | 140 | java |
java-design-patterns | java-design-patterns-master/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.compositeview;
import jakarta.servlet.http.HttpServletRequest;
import java.io.Serializable;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* A Java beans class that parses a http request and stores parameters.
* Java beans used in JSP's to dynamically include elements in view.
* DEFAULT_NAME = a constant, default name to be used for the default constructor
* worldNewsInterest = whether current request has world news interest
* sportsInterest = whether current request has a sportsInterest
* businessInterest = whether current request has a businessInterest
* scienceNewsInterest = whether current request has a scienceNewsInterest
*/
@Getter
@Setter
@NoArgsConstructor
public class ClientPropertiesBean implements Serializable {
private static final String WORLD_PARAM = "world";
private static final String SCIENCE_PARAM = "sci";
private static final String SPORTS_PARAM = "sport";
private static final String BUSINESS_PARAM = "bus";
private static final String NAME_PARAM = "name";
private static final String DEFAULT_NAME = "DEFAULT_NAME";
private boolean worldNewsInterest = true;
private boolean sportsInterest = true;
private boolean businessInterest = true;
private boolean scienceNewsInterest = true;
private String name = DEFAULT_NAME;
/**
* Constructor that parses an HttpServletRequest and stores all the request parameters.
*
* @param req the HttpServletRequest object that is passed in
*/
public ClientPropertiesBean(HttpServletRequest req) {
worldNewsInterest = Boolean.parseBoolean(req.getParameter(WORLD_PARAM));
sportsInterest = Boolean.parseBoolean(req.getParameter(SPORTS_PARAM));
businessInterest = Boolean.parseBoolean(req.getParameter(BUSINESS_PARAM));
scienceNewsInterest = Boolean.parseBoolean(req.getParameter(SCIENCE_PARAM));
String tempName = req.getParameter(NAME_PARAM);
if (tempName == null || tempName.equals("")) {
tempName = DEFAULT_NAME;
}
name = tempName;
}
}
| 3,331 | 41.717949 | 140 | java |
java-design-patterns | java-design-patterns-master/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.compositeview;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* A servlet object that extends HttpServlet.
* Runs on Tomcat 10 and handles Http requests
*/
public final class AppServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
private String msgPartOne = "<h1>This Server Doesn't Support";
private String msgPartTwo = "Requests</h1>\n"
+ "<h2>Use a GET request with boolean values for the following parameters<h2>\n"
+ "<h3>'name'</h3>\n<h3>'bus'</h3>\n<h3>'sports'</h3>\n<h3>'sci'</h3>\n<h3>'world'</h3>";
private String destination = "newsDisplay.jsp";
public AppServlet() {
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination);
ClientPropertiesBean reqParams = new ClientPropertiesBean(req);
req.setAttribute("properties", reqParams);
requestDispatcher.forward(req, resp);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Post " + msgPartTwo);
}
}
@Override
public void doDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Delete " + msgPartTwo);
}
}
@Override
public void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Put " + msgPartTwo);
}
}
}
| 3,419 | 37 | 140 | java |
java-design-patterns | java-design-patterns-master/priority-queue/src/test/java/com/iluwatar/priority/queue/QueueManagerTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.priority.queue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* Check queue manager
*/
class QueueManagerTest {
@Test
void publishMessage() {
var queueManager = new QueueManager(2);
var testMessage = new Message("Test Message", 1);
queueManager.publishMessage(testMessage);
var recivedMessage = queueManager.receiveMessage();
assertEquals(testMessage, recivedMessage);
}
@Test
void receiveMessage() {
var queueManager = new QueueManager(2);
var testMessage1 = new Message("Test Message 1", 1);
queueManager.publishMessage(testMessage1);
var testMessage2 = new Message("Test Message 2", 2);
queueManager.publishMessage(testMessage2);
var recivedMessage = queueManager.receiveMessage();
assertEquals(testMessage2, recivedMessage);
}
} | 2,158 | 38.254545 | 140 | java |
java-design-patterns | java-design-patterns-master/priority-queue/src/test/java/com/iluwatar/priority/queue/PriorityMessageQueueTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.priority.queue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Test case for order of messages
*/
class PriorityMessageQueueTest {
@Test
void remove() {
var stringPriorityMessageQueue = new PriorityMessageQueue<>(new String[2]);
var pushMessage = "test";
stringPriorityMessageQueue.add(pushMessage);
assertEquals(stringPriorityMessageQueue.remove(), pushMessage);
}
@Test
void add() {
var stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]);
stringPriorityMessageQueue.add(1);
stringPriorityMessageQueue.add(5);
stringPriorityMessageQueue.add(10);
stringPriorityMessageQueue.add(3);
assertEquals(10, (int) stringPriorityMessageQueue.remove());
}
@Test
void isEmpty() {
var stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]);
assertTrue(stringPriorityMessageQueue.isEmpty());
stringPriorityMessageQueue.add(1);
stringPriorityMessageQueue.remove();
assertTrue(stringPriorityMessageQueue.isEmpty());
}
@Test
void testEnsureSize() {
var stringPriorityMessageQueue = new PriorityMessageQueue<>(new Integer[2]);
assertTrue(stringPriorityMessageQueue.isEmpty());
stringPriorityMessageQueue.add(1);
stringPriorityMessageQueue.add(2);
stringPriorityMessageQueue.add(2);
stringPriorityMessageQueue.add(3);
assertEquals(3, (int) stringPriorityMessageQueue.remove());
}
} | 2,841 | 36.893333 | 140 | java |
java-design-patterns | java-design-patterns-master/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.priority.queue;
/**
* Message bean.
*/
public class Message implements Comparable<Message> {
private final String message;
private final int priority; // define message priority in queue
public Message(String message, int priority) {
this.message = message;
this.priority = priority;
}
@Override
public int compareTo(Message o) {
return priority - o.priority;
}
@Override
public String toString() {
return "Message{"
+ "message='" + message + '\''
+ ", priority=" + priority
+ '}';
}
}
| 1,858 | 34.075472 | 140 | java |
java-design-patterns | java-design-patterns-master/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.priority.queue;
/**
* Manage priority queue.
*/
public class QueueManager {
/*
Priority message
*/
private final PriorityMessageQueue<Message> messagePriorityMessageQueue;
public QueueManager(int initialCapacity) {
messagePriorityMessageQueue = new PriorityMessageQueue<>(new Message[initialCapacity]);
}
/**
* Publish message to queue.
*/
public void publishMessage(Message message) {
messagePriorityMessageQueue.add(message);
}
/**
* Receive message from queue.
*/
public Message receiveMessage() {
if (messagePriorityMessageQueue.isEmpty()) {
return null;
}
return messagePriorityMessageQueue.remove();
}
}
| 1,990 | 32.183333 | 140 | java |
java-design-patterns | java-design-patterns-master/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.priority.queue;
/**
* Prioritize requests sent to services so that requests with a higher priority are received and
* processed more quickly than those of a lower priority. This pattern is useful in applications
* that offer different service level guarantees to individual clients. Example :Send multiple
* message with different priority to worker queue. Worker execute higher priority message first
*
* @see "https://docs.microsoft.com/en-us/previous-versions/msp-n-p/dn589794(v=pandp.10)"
*/
public class Application {
/**
* main entry.
*/
public static void main(String[] args) throws Exception {
var queueManager = new QueueManager(10);
// push some message to queue
// Low Priority message
for (var i = 0; i < 10; i++) {
queueManager.publishMessage(new Message("Low Message Priority", 0));
}
// High Priority message
for (var i = 0; i < 10; i++) {
queueManager.publishMessage(new Message("High Message Priority", 1));
}
// run worker
var worker = new Worker(queueManager);
worker.run();
}
}
| 2,385 | 38.114754 | 140 | java |
java-design-patterns | java-design-patterns-master/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.priority.queue;
import static java.util.Arrays.copyOf;
import lombok.extern.slf4j.Slf4j;
/**
* Keep high Priority message on top using maxHeap.
*
* @param <T> : DataType to push in Queue
*/
@Slf4j
public class PriorityMessageQueue<T extends Comparable> {
private int size = 0;
private int capacity;
private T[] queue;
public PriorityMessageQueue(T[] queue) {
this.queue = queue;
this.capacity = queue.length;
}
/**
* Remove top message from queue.
*/
public T remove() {
if (isEmpty()) {
return null;
}
final var root = queue[0];
queue[0] = queue[size - 1];
size--;
maxHeapifyDown();
return root;
}
/**
* Add message to queue.
*/
public void add(T t) {
ensureCapacity();
queue[size] = t;
size++;
maxHeapifyUp();
}
/**
* Check queue size.
*/
public boolean isEmpty() {
return size == 0;
}
private void maxHeapifyDown() {
var index = 0;
while (hasLeftChild(index)) {
var smallerIndex = leftChildIndex(index);
if (hasRightChild(index) && right(index).compareTo(left(index)) > 0) {
smallerIndex = rightChildIndex(index);
}
if (queue[index].compareTo(queue[smallerIndex]) > 0) {
break;
} else {
swap(index, smallerIndex);
}
index = smallerIndex;
}
}
private void maxHeapifyUp() {
var index = size - 1;
while (hasParent(index) && parent(index).compareTo(queue[index]) < 0) {
swap(parentIndex(index), index);
index = parentIndex(index);
}
}
// index
private int parentIndex(int pos) {
return (pos - 1) / 2;
}
private int leftChildIndex(int parentPos) {
return 2 * parentPos + 1;
}
private int rightChildIndex(int parentPos) {
return 2 * parentPos + 2;
}
// value
private T parent(int childIndex) {
return queue[parentIndex(childIndex)];
}
private T left(int parentIndex) {
return queue[leftChildIndex(parentIndex)];
}
private T right(int parentIndex) {
return queue[rightChildIndex(parentIndex)];
}
// check
private boolean hasLeftChild(int index) {
return leftChildIndex(index) < size;
}
private boolean hasRightChild(int index) {
return rightChildIndex(index) < size;
}
private boolean hasParent(int index) {
return parentIndex(index) >= 0;
}
private void swap(int fpos, int tpos) {
var tmp = queue[fpos];
queue[fpos] = queue[tpos];
queue[tpos] = tmp;
}
private void ensureCapacity() {
if (size == capacity) {
capacity = capacity * 2;
queue = copyOf(queue, capacity);
}
}
/**
* For debug .. print current state of queue
*/
public void print() {
for (var i = 0; i <= size / 2; i++) {
LOGGER.info(" PARENT : " + queue[i] + " LEFT CHILD : "
+ left(i) + " RIGHT CHILD :" + right(i));
}
}
}
| 4,199 | 22.463687 | 140 | java |
java-design-patterns | java-design-patterns-master/priority-queue/src/main/java/com/iluwatar/priority/queue/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.priority.queue;
import lombok.extern.slf4j.Slf4j;
/**
* Message Worker.
*/
@Slf4j
public class Worker {
private final QueueManager queueManager;
public Worker(QueueManager queueManager) {
this.queueManager = queueManager;
}
/**
* Keep checking queue for message.
*/
@SuppressWarnings("squid:S2189")
public void run() throws Exception {
while (true) {
var message = queueManager.receiveMessage();
if (message == null) {
LOGGER.info("No Message ... waiting");
Thread.sleep(200);
} else {
processMessage(message);
}
}
}
/**
* Process message.
*/
private void processMessage(Message message) {
LOGGER.info(message.toString());
}
}
| 2,037 | 30.353846 | 140 | java |
java-design-patterns | java-design-patterns-master/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellPoolTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.typeobject;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Hashtable;
import org.junit.jupiter.api.Test;
/**
* The CellPoolTest class tests the methods in the {@link CellPool} class.
*/
class CellPoolTest {
@Test
void assignRandomCandyTypesTest() {
var cp = new CellPool(10);
var ht = new Hashtable<String, Boolean>();
var parentTypes = 0;
for (var i = 0; i < cp.randomCode.length; i++) {
ht.putIfAbsent(cp.randomCode[i].name, true);
if (cp.randomCode[i].name.equals("fruit") || cp.randomCode[i].name.equals("candy")) {
parentTypes++;
}
}
assertTrue(ht.size() == 5 && parentTypes == 0);
}
}
| 1,989 | 36.54717 | 140 | java |
java-design-patterns | java-design-patterns-master/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CandyGameTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.typeobject;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.typeobject.Candy.Type;
import org.junit.jupiter.api.Test;
/**
* The CandyGameTest class tests the methods in the {@link CandyGame} class.
*/
class CandyGameTest {
@Test
void adjacentCellsTest() {
var cg = new CandyGame(3, new CellPool(9));
var arr1 = cg.adjacentCells(0, 0);
var arr2 = cg.adjacentCells(1, 2);
var arr3 = cg.adjacentCells(1, 1);
assertTrue(arr1.size() == 2 && arr2.size() == 3 && arr3.size() == 4);
}
@Test
void continueRoundTest() {
var matrix = new Cell[2][2];
var c1 = new Candy("green jelly", "jelly", Type.CRUSHABLE_CANDY, 5);
var c2 = new Candy("purple jelly", "jelly", Type.CRUSHABLE_CANDY, 5);
var c3 = new Candy("green apple", "apple", Type.REWARD_FRUIT, 10);
matrix[0][0] = new Cell(c1, 0, 0);
matrix[0][1] = new Cell(c2, 1, 0);
matrix[1][0] = new Cell(c3, 0, 1);
matrix[1][1] = new Cell(c2, 1, 1);
var p = new CellPool(4);
var cg = new CandyGame(2, p);
cg.cells = matrix;
var fruitInLastRow = cg.continueRound();
matrix[1][0].crush(p, matrix);
matrix[0][0] = new Cell(c3, 0, 0);
var matchingCandy = cg.continueRound();
matrix[0][1].crush(p, matrix);
matrix[0][1] = new Cell(c3, 1, 0);
var noneLeft = cg.continueRound();
assertTrue(fruitInLastRow && matchingCandy && !noneLeft);
}
}
| 2,722 | 37.352113 | 140 | java |
java-design-patterns | java-design-patterns-master/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.typeobject;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.typeobject.Candy.Type;
import org.junit.jupiter.api.Test;
/**
* The CellTest class tests the methods in the {@link Cell} class.
*/
class CellTest {
@Test
void interactTest() {
var c1 = new Candy("green jelly", "jelly", Type.CRUSHABLE_CANDY, 5);
var c2 = new Candy("green apple", "apple", Type.REWARD_FRUIT, 10);
var matrix = new Cell[4][4];
matrix[0][0] = new Cell(c1, 0, 0);
matrix[0][1] = new Cell(c1, 1, 0);
matrix[0][2] = new Cell(c2, 2, 0);
matrix[0][3] = new Cell(c1, 3, 0);
var cp = new CellPool(5);
var points1 = matrix[0][0].interact(matrix[0][1], cp, matrix);
var points2 = matrix[0][2].interact(matrix[0][3], cp, matrix);
assertTrue(points1 > 0 && points2 == 0);
}
@Test
void crushTest() {
var c1 = new Candy("green jelly", "jelly", Type.CRUSHABLE_CANDY, 5);
var c2 = new Candy("purple candy", "candy", Type.CRUSHABLE_CANDY, 5);
var matrix = new Cell[4][4];
matrix[0][0] = new Cell(c1, 0, 0);
matrix[1][0] = new Cell(c2, 0, 1);
matrix[1][0].crush(new CellPool(5), matrix);
assertEquals("green jelly", matrix[1][0].candy.name);
}
}
| 2,590 | 39.484375 | 140 | java |
java-design-patterns | java-design-patterns-master/typeobjectpattern/src/main/java/com/iluwatar/typeobject/Cell.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.typeobject;
import com.iluwatar.typeobject.Candy.Type;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
/**
* The Cell object is what the game matrix is made of and contains the candy which is to be crushed
* or collected as reward.
*/
@AllArgsConstructor
@NoArgsConstructor
public class Cell {
Candy candy;
int positionX;
int positionY;
void crush(CellPool pool, Cell[][] cellMatrix) {
//take out from this position and put back in pool
pool.addNewCell(this);
this.fillThisSpace(pool, cellMatrix);
}
void fillThisSpace(CellPool pool, Cell[][] cellMatrix) {
for (var y = this.positionY; y > 0; y--) {
cellMatrix[y][this.positionX] = cellMatrix[y - 1][this.positionX];
cellMatrix[y][this.positionX].positionY = y;
}
var newC = pool.getNewCell();
cellMatrix[0][this.positionX] = newC;
cellMatrix[0][this.positionX].positionX = this.positionX;
cellMatrix[0][this.positionX].positionY = 0;
}
void handleCrush(Cell c, CellPool pool, Cell[][] cellMatrix) {
if (this.positionY >= c.positionY) {
this.crush(pool, cellMatrix);
c.crush(pool, cellMatrix);
} else {
c.crush(pool, cellMatrix);
this.crush(pool, cellMatrix);
}
}
int interact(Cell c, CellPool pool, Cell[][] cellMatrix) {
if (this.candy.getType().equals(Type.REWARD_FRUIT) || c.candy.getType()
.equals(Type.REWARD_FRUIT)) {
return 0;
} else {
if (this.candy.name.equals(c.candy.name)) {
var pointsWon = this.candy.getPoints() + c.candy.getPoints();
handleCrush(c, pool, cellMatrix);
return pointsWon;
} else {
return 0;
}
}
}
}
| 2,994 | 34.654762 | 140 | java |
java-design-patterns | java-design-patterns-master/typeobjectpattern/src/main/java/com/iluwatar/typeobject/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.typeobject;
import lombok.extern.slf4j.Slf4j;
/**
* <p>Type object pattern is the pattern we use when the OOP concept of creating a base class and
* inheriting from it just doesn't work for the case in hand. This happens when we either don't know
* what types we will need upfront, or want to be able to modify or add new types conveniently w/o
* recompiling repeatedly. The pattern provides a solution by allowing flexible creation of required
* objects by creating one class, which has a field which represents the 'type' of the object.</p>
* <p>In this example, we have a mini candy-crush game in action. There are many different candies
* in the game, which may change over time, as we may want to upgrade the game. To make the object
* creation convenient, we have a class {@link Candy} which has a field name, parent, points and
* Type. We have a json file {@link candy} which contains the details about the candies, and this is
* parsed to get all the different candies in {@link JsonParser}. The {@link Cell} class is what the
* game matrix is made of, which has the candies that are to be crushed, and contains information on
* how crushing can be done, how the matrix is to be reconfigured and how points are to be gained.
* The {@link CellPool} class is a pool which reuses the candy cells that have been crushed instead
* of making new ones repeatedly. The {@link CandyGame} class has the rules for the continuation of
* the game and the {@link App} class has the game itself.</p>
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var givenTime = 50; //50ms
var toWin = 500; //points
var pointsWon = 0;
var numOfRows = 3;
var start = System.currentTimeMillis();
var end = System.currentTimeMillis();
var round = 0;
while (pointsWon < toWin && end - start < givenTime) {
round++;
var pool = new CellPool(numOfRows * numOfRows + 5);
var cg = new CandyGame(numOfRows, pool);
if (round > 1) {
LOGGER.info("Refreshing..");
} else {
LOGGER.info("Starting game..");
}
cg.printGameStatus();
end = System.currentTimeMillis();
cg.round((int) (end - start), givenTime);
pointsWon += cg.totalPoints;
end = System.currentTimeMillis();
}
LOGGER.info("Game Over");
if (pointsWon >= toWin) {
LOGGER.info("" + pointsWon);
LOGGER.info("You win!!");
} else {
LOGGER.info("" + pointsWon);
LOGGER.info("Sorry, you lose!");
}
}
}
| 3,905 | 43.386364 | 140 | java |
java-design-patterns | java-design-patterns-master/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.typeobject;
import com.iluwatar.typeobject.Candy.Type;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
/**
* The CandyGame class contains the rules for the continuation of the game and has the game matrix
* (field 'cells') and totalPoints gained during the game.
*/
@Slf4j
public class CandyGame {
Cell[][] cells;
CellPool pool;
int totalPoints;
CandyGame(int num, CellPool pool) {
this.cells = new Cell[num][num];
this.pool = pool;
this.totalPoints = 0;
for (var i = 0; i < num; i++) {
for (var j = 0; j < num; j++) {
this.cells[i][j] = this.pool.getNewCell();
this.cells[i][j].positionX = j;
this.cells[i][j].positionY = i;
}
}
}
static String numOfSpaces(int num) {
return " ".repeat(Math.max(0, num));
}
void printGameStatus() {
LOGGER.info("");
for (Cell[] cell : cells) {
for (var j = 0; j < cells.length; j++) {
var candyName = cell[j].candy.name;
if (candyName.length() < 20) {
var totalSpaces = 20 - candyName.length();
LOGGER.info(numOfSpaces(totalSpaces / 2) + cell[j].candy.name
+ numOfSpaces(totalSpaces - totalSpaces / 2) + "|");
} else {
LOGGER.info(candyName + "|");
}
}
LOGGER.info("");
}
LOGGER.info("");
}
List<Cell> adjacentCells(int y, int x) {
var adjacent = new ArrayList<Cell>();
if (y == 0) {
adjacent.add(this.cells[1][x]);
}
if (x == 0) {
adjacent.add(this.cells[y][1]);
}
if (y == cells.length - 1) {
adjacent.add(this.cells[cells.length - 2][x]);
}
if (x == cells.length - 1) {
adjacent.add(this.cells[y][cells.length - 2]);
}
if (y > 0 && y < cells.length - 1) {
adjacent.add(this.cells[y - 1][x]);
adjacent.add(this.cells[y + 1][x]);
}
if (x > 0 && x < cells.length - 1) {
adjacent.add(this.cells[y][x - 1]);
adjacent.add(this.cells[y][x + 1]);
}
return adjacent;
}
boolean continueRound() {
for (var i = 0; i < this.cells.length; i++) {
if (this.cells[cells.length - 1][i].candy.getType().equals(Type.REWARD_FRUIT)) {
return true;
}
}
for (var i = 0; i < this.cells.length; i++) {
for (var j = 0; j < this.cells.length; j++) {
if (!this.cells[i][j].candy.getType().equals(Type.REWARD_FRUIT)) {
var adj = adjacentCells(i, j);
for (Cell cell : adj) {
if (this.cells[i][j].candy.name.equals(cell.candy.name)) {
return true;
}
}
}
}
}
return false;
}
void handleChange(int points) {
LOGGER.info("+" + points + " points!");
this.totalPoints += points;
printGameStatus();
}
void round(int timeSoFar, int totalTime) {
var start = System.currentTimeMillis();
var end = System.currentTimeMillis();
while (end - start + timeSoFar < totalTime && continueRound()) {
for (var i = 0; i < this.cells.length; i++) {
var points = 0;
var j = this.cells.length - 1;
while (this.cells[j][i].candy.getType().equals(Type.REWARD_FRUIT)) {
points = this.cells[j][i].candy.getPoints();
this.cells[j][i].crush(pool, this.cells);
handleChange(points);
}
}
for (var i = 0; i < this.cells.length; i++) {
var j = cells.length - 1;
var points = 0;
while (j > 0) {
points = this.cells[j][i].interact(this.cells[j - 1][i], this.pool, this.cells);
if (points != 0) {
handleChange(points);
} else {
j = j - 1;
}
}
}
for (Cell[] cell : this.cells) {
var j = 0;
var points = 0;
while (j < cells.length - 1) {
points = cell[j].interact(cell[j + 1], this.pool, this.cells);
if (points != 0) {
handleChange(points);
} else {
j = j + 1;
}
}
}
end = System.currentTimeMillis();
}
}
}
| 5,399 | 30.213873 | 140 | java |
java-design-patterns | java-design-patterns-master/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.typeobject;
import com.google.gson.JsonParseException;
import com.iluwatar.typeobject.Candy.Type;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
/**
* The CellPool class allows the reuse of crushed cells instead of creation of new cells each time.
* The reused cell is given a new candy to hold using the randomCode field which holds all the
* candies available.
*/
public class CellPool {
private static final SecureRandom RANDOM = new SecureRandom();
public static final String FRUIT = "fruit";
public static final String CANDY = "candy";
List<Cell> pool;
int pointer;
Candy[] randomCode;
CellPool(int num) {
this.pool = new ArrayList<>(num);
try {
this.randomCode = assignRandomCandytypes();
} catch (Exception e) {
e.printStackTrace();
//manually initialising this.randomCode
this.randomCode = new Candy[5];
randomCode[0] = new Candy("cherry", FRUIT, Type.REWARD_FRUIT, 20);
randomCode[1] = new Candy("mango", FRUIT, Type.REWARD_FRUIT, 20);
randomCode[2] = new Candy("purple popsicle", CANDY, Type.CRUSHABLE_CANDY, 10);
randomCode[3] = new Candy("green jellybean", CANDY, Type.CRUSHABLE_CANDY, 10);
randomCode[4] = new Candy("orange gum", CANDY, Type.CRUSHABLE_CANDY, 10);
}
for (int i = 0; i < num; i++) {
var c = new Cell();
c.candy = randomCode[RANDOM.nextInt(randomCode.length)];
this.pool.add(c);
}
this.pointer = num - 1;
}
Cell getNewCell() {
var newCell = this.pool.remove(pointer);
pointer--;
return newCell;
}
void addNewCell(Cell c) {
c.candy = randomCode[RANDOM.nextInt(randomCode.length)]; //changing candytype to new
this.pool.add(c);
pointer++;
}
Candy[] assignRandomCandytypes() throws JsonParseException {
var jp = new JsonParser();
jp.parse();
var randomCode = new Candy[jp.candies.size() - 2]; //exclude generic types 'fruit' and 'candy'
var i = 0;
for (var e = jp.candies.keys(); e.hasMoreElements(); ) {
var s = e.nextElement();
if (!s.equals(FRUIT) && !s.equals(CANDY)) {
//not generic
randomCode[i] = jp.candies.get(s);
i++;
}
}
return randomCode;
}
}
| 3,556 | 35.670103 | 140 | java |
java-design-patterns | java-design-patterns-master/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.typeobject;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.iluwatar.typeobject.Candy.Type;
import java.io.InputStreamReader;
import java.util.Hashtable;
/**
* The JsonParser class helps parse the json file candy.json to get all the different candies.
*/
public class JsonParser {
Hashtable<String, Candy> candies;
JsonParser() {
this.candies = new Hashtable<>();
}
void parse() throws JsonParseException {
var is = this.getClass().getClassLoader().getResourceAsStream("candy.json");
var reader = new InputStreamReader(is);
var json = (JsonObject) com.google.gson.JsonParser.parseReader(reader);
var array = (JsonArray) json.get("candies");
for (var item : array) {
var candy = (JsonObject) item;
var name = candy.get("name").getAsString();
var parentName = candy.get("parent").getAsString();
var t = candy.get("type").getAsString();
var type = Type.CRUSHABLE_CANDY;
if (t.equals("rewardFruit")) {
type = Type.REWARD_FRUIT;
}
var points = candy.get("points").getAsInt();
var c = new Candy(name, parentName, type, points);
this.candies.put(name, c);
}
setParentAndPoints();
}
void setParentAndPoints() {
for (var e = this.candies.keys(); e.hasMoreElements(); ) {
var c = this.candies.get(e.nextElement());
if (c.parentName == null) {
c.parent = null;
} else {
c.parent = this.candies.get(c.parentName);
}
if (c.getPoints() == 0 && c.parent != null) {
c.setPoints(c.parent.getPoints());
}
}
}
}
| 2,964 | 35.604938 | 140 | java |
java-design-patterns | java-design-patterns-master/typeobjectpattern/src/main/java/com/iluwatar/typeobject/Candy.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.typeobject;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
/**
* The Candy class has a field type, which represents the 'type' of candy. The objects are created
* by parsing the candy.json file.
*/
@Getter(AccessLevel.PACKAGE)
public class Candy {
enum Type {
CRUSHABLE_CANDY,
REWARD_FRUIT
}
String name;
Candy parent;
String parentName;
@Setter
private int points;
private final Type type;
Candy(String name, String parentName, Type type, int points) {
this.name = name;
this.parent = null;
this.type = type;
this.points = points;
this.parentName = parentName;
}
}
| 1,953 | 31.566667 | 140 | java |
java-design-patterns | java-design-patterns-master/composite/src/test/java/com/iluwatar/composite/MessengerTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.composite;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Date: 12/11/15 - 8:12 PM
*
* @author Jeroen Meulemeester
*/
class MessengerTest {
/**
* The buffer used to capture every write to {@link System#out}
*/
private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream();
/**
* Keep the original std-out so it can be restored after the test
*/
private final PrintStream realStdOut = System.out;
/**
* Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
*/
@BeforeEach
void setUp() {
this.stdOutBuffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdOutBuffer));
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@AfterEach
void tearDown() {
System.setOut(realStdOut);
}
/**
* Test the message from the orcs
*/
@Test
void testMessageFromOrcs() {
final var messenger = new Messenger();
testMessage(
messenger.messageFromOrcs(),
"Where there is a whip there is a way."
);
}
/**
* Test the message from the elves
*/
@Test
void testMessageFromElves() {
final var messenger = new Messenger();
testMessage(
messenger.messageFromElves(),
"Much wind pours from your mouth."
);
}
/**
* Test if the given composed message matches the expected message
*
* @param composedMessage The composed message, received from the messenger
* @param message The expected message
*/
private void testMessage(final LetterComposite composedMessage, final String message) {
// Test is the composed message has the correct number of words
final var words = message.split(" ");
assertNotNull(composedMessage);
assertEquals(words.length, composedMessage.count());
// Print the message to the mocked stdOut ...
composedMessage.print();
// ... and verify if the message matches with the expected one
assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim());
}
}
| 3,650 | 31.026316 | 140 | java |
java-design-patterns | java-design-patterns-master/composite/src/test/java/com/iluwatar/composite/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.composite;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Application test
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test
void shouldExecuteApplicationWithoutException() {
Assertions.assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,788 | 37.06383 | 140 | java |
java-design-patterns | java-design-patterns-master/composite/src/main/java/com/iluwatar/composite/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.composite;
import lombok.extern.slf4j.Slf4j;
/**
* The Composite pattern is a partitioning design pattern. The Composite pattern describes that a
* group of objects is to be treated in the same way as a single instance of an object. The intent
* of a composite is to "compose" objects into tree structures to represent part-whole hierarchies.
* Implementing the Composite pattern lets clients treat individual objects and compositions
* uniformly.
*
* <p>In this example we have sentences composed of words composed of letters. All of the objects
* can be treated through the same interface ({@link LetterComposite}).
*
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var messenger = new Messenger();
LOGGER.info("Message from the orcs: ");
messenger.messageFromOrcs().print();
LOGGER.info("Message from the elves: ");
messenger.messageFromElves().print();
}
}
| 2,306 | 38.101695 | 140 | java |
java-design-patterns | java-design-patterns-master/composite/src/main/java/com/iluwatar/composite/LetterComposite.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.composite;
import java.util.ArrayList;
import java.util.List;
/**
* Composite interface.
*/
public abstract class LetterComposite {
private final List<LetterComposite> children = new ArrayList<>();
public void add(LetterComposite letter) {
children.add(letter);
}
public int count() {
return children.size();
}
protected void printThisBefore() {
}
protected void printThisAfter() {
}
/**
* Print.
*/
public void print() {
printThisBefore();
children.forEach(LetterComposite::print);
printThisAfter();
}
}
| 1,870 | 30.183333 | 140 | java |
java-design-patterns | java-design-patterns-master/composite/src/main/java/com/iluwatar/composite/Sentence.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.composite;
import java.util.List;
/**
* Sentence.
*/
public class Sentence extends LetterComposite {
/**
* Constructor.
*/
public Sentence(List<Word> words) {
words.forEach(this::add);
}
@Override
protected void printThisAfter() {
System.out.print(".\n");
}
}
| 1,597 | 33.73913 | 140 | java |
java-design-patterns | java-design-patterns-master/composite/src/main/java/com/iluwatar/composite/Messenger.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.composite;
import java.util.List;
/**
* Messenger.
*/
public class Messenger {
LetterComposite messageFromOrcs() {
var words = List.of(
new Word('W', 'h', 'e', 'r', 'e'),
new Word('t', 'h', 'e', 'r', 'e'),
new Word('i', 's'),
new Word('a'),
new Word('w', 'h', 'i', 'p'),
new Word('t', 'h', 'e', 'r', 'e'),
new Word('i', 's'),
new Word('a'),
new Word('w', 'a', 'y')
);
return new Sentence(words);
}
LetterComposite messageFromElves() {
var words = List.of(
new Word('M', 'u', 'c', 'h'),
new Word('w', 'i', 'n', 'd'),
new Word('p', 'o', 'u', 'r', 's'),
new Word('f', 'r', 'o', 'm'),
new Word('y', 'o', 'u', 'r'),
new Word('m', 'o', 'u', 't', 'h')
);
return new Sentence(words);
}
}
| 2,150 | 30.632353 | 140 | java |
java-design-patterns | java-design-patterns-master/composite/src/main/java/com/iluwatar/composite/Word.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.composite;
import java.util.List;
/**
* Word.
*/
public class Word extends LetterComposite {
/**
* Constructor.
*/
public Word(List<Letter> letters) {
letters.forEach(this::add);
}
/**
* Constructor.
* @param letters to include
*/
public Word(char... letters) {
for (char letter : letters) {
this.add(new Letter(letter));
}
}
@Override
protected void printThisBefore() {
System.out.print(" ");
}
}
| 1,765 | 30.535714 | 140 | java |
java-design-patterns | java-design-patterns-master/composite/src/main/java/com/iluwatar/composite/Letter.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.composite;
import lombok.RequiredArgsConstructor;
/**
* Letter.
*/
@RequiredArgsConstructor
public class Letter extends LetterComposite {
private final char character;
@Override
protected void printThisBefore() {
System.out.print(character);
}
}
| 1,569 | 36.380952 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/test/java/com/iluwatar/specialcase/SpecialCasesTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
/**
* Special cases unit tests. (including the successful scenario {@link ReceiptDto})
*/
class SpecialCasesTest {
private static ApplicationServices applicationServices;
private static ReceiptViewModel receipt;
@BeforeAll
static void beforeAll() {
Db.getInstance().seedUser("ignite1771", 1000.0);
Db.getInstance().seedItem("computer", 800.0);
Db.getInstance().seedItem("car", 20000.0);
applicationServices = new ApplicationServicesImpl();
}
@BeforeEach
void beforeEach() {
MaintenanceLock.getInstance().setLock(false);
}
@Test
void testDownForMaintenance() {
final Logger LOGGER = (Logger) LoggerFactory.getLogger(DownForMaintenance.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
LOGGER.addAppender(listAppender);
MaintenanceLock.getInstance().setLock(true);
receipt = applicationServices.loggedInUserPurchase(null, null);
receipt.show();
List<ILoggingEvent> loggingEventList = listAppender.list;
assertEquals("Down for maintenance", loggingEventList.get(0).getMessage());
assertEquals(Level.INFO, loggingEventList.get(0).getLevel());
}
@Test
void testInvalidUser() {
final Logger LOGGER = (Logger) LoggerFactory.getLogger(InvalidUser.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
LOGGER.addAppender(listAppender);
receipt = applicationServices.loggedInUserPurchase("a", null);
receipt.show();
List<ILoggingEvent> loggingEventList = listAppender.list;
assertEquals("Invalid user: a", loggingEventList.get(0).getMessage());
assertEquals(Level.INFO, loggingEventList.get(0).getLevel());
}
@Test
void testOutOfStock() {
final Logger LOGGER = (Logger) LoggerFactory.getLogger(OutOfStock.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
LOGGER.addAppender(listAppender);
receipt = applicationServices.loggedInUserPurchase("ignite1771", "tv");
receipt.show();
List<ILoggingEvent> loggingEventList = listAppender.list;
assertEquals("Out of stock: tv for user = ignite1771 to buy"
, loggingEventList.get(0).getMessage());
assertEquals(Level.INFO, loggingEventList.get(0).getLevel());
}
@Test
void testInsufficientFunds() {
final Logger LOGGER = (Logger) LoggerFactory.getLogger(InsufficientFunds.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
LOGGER.addAppender(listAppender);
receipt = applicationServices.loggedInUserPurchase("ignite1771", "car");
receipt.show();
List<ILoggingEvent> loggingEventList = listAppender.list;
assertEquals("Insufficient funds: 1000.0 of user: ignite1771 for buying item: car"
, loggingEventList.get(0).getMessage());
assertEquals(Level.INFO, loggingEventList.get(0).getLevel());
}
@Test
void testReceiptDto() {
final Logger LOGGER = (Logger) LoggerFactory.getLogger(ReceiptDto.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
LOGGER.addAppender(listAppender);
receipt = applicationServices.loggedInUserPurchase("ignite1771", "computer");
receipt.show();
List<ILoggingEvent> loggingEventList = listAppender.list;
assertEquals("Receipt: 800.0 paid"
, loggingEventList.get(0).getMessage());
assertEquals(Level.INFO, loggingEventList.get(0).getLevel());
}
}
| 5,237 | 35.375 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/test/java/com/iluwatar/specialcase/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.specialcase;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
/**
* Application test.
*/
class AppTest {
@Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,580 | 37.560976 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/OutOfStock.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Receipt view for showing out of stock message.
*/
public class OutOfStock implements ReceiptViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(OutOfStock.class);
private String userName;
private String itemName;
public OutOfStock(String userName, String itemName) {
this.userName = userName;
this.itemName = itemName;
}
@Override
public void show() {
LOGGER.info("Out of stock: " + itemName + " for user = " + userName + " to buy");
}
}
| 1,876 | 36.54 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/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.specialcase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>The Special Case Pattern is a software design pattern that encapsulates particular cases
* into subclasses that provide special behaviors.</p>
*
* <p>In this example ({@link ReceiptViewModel}) encapsulates all particular cases.</p>
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
private static final String LOGGER_STRING = "[REQUEST] User: {} buy product: {}";
private static final String TEST_USER_1 = "ignite1771";
private static final String TEST_USER_2 = "abc123";
private static final String ITEM_TV = "tv";
private static final String ITEM_CAR = "car";
private static final String ITEM_COMPUTER = "computer";
/**
* Program entry point.
*/
public static void main(String[] args) {
// DB seeding
LOGGER.info("Db seeding: " + "1 user: {\"ignite1771\", amount = 1000.0}, "
+ "2 products: {\"computer\": price = 800.0, \"car\": price = 20000.0}");
Db.getInstance().seedUser(TEST_USER_1, 1000.0);
Db.getInstance().seedItem(ITEM_COMPUTER, 800.0);
Db.getInstance().seedItem(ITEM_CAR, 20000.0);
final var applicationServices = new ApplicationServicesImpl();
ReceiptViewModel receipt;
LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV);
receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV);
receipt.show();
MaintenanceLock.getInstance().setLock(false);
LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV);
receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV);
receipt.show();
LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_TV);
receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_TV);
receipt.show();
LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_CAR);
receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_CAR);
receipt.show();
LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_COMPUTER);
receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_COMPUTER);
receipt.show();
}
}
| 3,415 | 42.240506 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/DownForMaintenance.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Down for Maintenance view for the ReceiptViewModel.
*/
public class DownForMaintenance implements ReceiptViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(DownForMaintenance.class);
@Override
public void show() {
LOGGER.info("Down for maintenance");
}
}
| 1,676 | 38.928571 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/ReceiptViewModel.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
/**
* ReceiptViewModel interface.
*/
public interface ReceiptViewModel {
void show();
}
| 1,412 | 40.558824 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/DomainServicesImpl.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
/**
* Implementation of DomainServices for special case.
*/
public class DomainServicesImpl implements DomainServices {
/**
* Domain purchase with userName and itemName, with validation for userName.
*
* @param userName of the user
* @param itemName of the item
* @return instance of ReceiptViewModel
*/
public ReceiptViewModel purchase(String userName, String itemName) {
Db.User user = Db.getInstance().findUserByUserName(userName);
if (user == null) {
return new InvalidUser(userName);
}
Db.Account account = Db.getInstance().findAccountByUser(user);
return purchase(user, account, itemName);
}
/**
* Domain purchase with user, account and itemName,
* with validation for whether product is out of stock
* and whether user has insufficient funds in the account.
*
* @param user in Db
* @param account in Db
* @param itemName of the item
* @return instance of ReceiptViewModel
*/
private ReceiptViewModel purchase(Db.User user, Db.Account account, String itemName) {
Db.Product item = Db.getInstance().findProductByItemName(itemName);
if (item == null) {
return new OutOfStock(user.getUserName(), itemName);
}
ReceiptDto receipt = user.purchase(item);
MoneyTransaction transaction = account.withdraw(receipt.getPrice());
if (transaction == null) {
return new InsufficientFunds(user.getUserName(), account.getAmount(), itemName);
}
return receipt;
}
}
| 2,806 | 36.932432 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/Db.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
import java.util.HashMap;
import java.util.Map;
/**
* DB class for seeding user info.
*/
public class Db {
private static Db instance;
private Map<String, User> userName2User;
private Map<User, Account> user2Account;
private Map<String, Product> itemName2Product;
/**
* Get the instance of Db.
*
* @return singleton instance of Db class
*/
public static synchronized Db getInstance() {
if (instance == null) {
Db newInstance = new Db();
newInstance.userName2User = new HashMap<>();
newInstance.user2Account = new HashMap<>();
newInstance.itemName2Product = new HashMap<>();
instance = newInstance;
}
return instance;
}
/**
* Seed a user into Db.
*
* @param userName of the user
* @param amount of the user's account
*/
public void seedUser(String userName, Double amount) {
User user = new User(userName);
instance.userName2User.put(userName, user);
Account account = new Account(amount);
instance.user2Account.put(user, account);
}
/**
* Seed an item into Db.
*
* @param itemName of the item
* @param price of the item
*/
public void seedItem(String itemName, Double price) {
Product item = new Product(price);
itemName2Product.put(itemName, item);
}
/**
* Find a user with the userName.
*
* @param userName of the user
* @return instance of User
*/
public User findUserByUserName(String userName) {
if (!userName2User.containsKey(userName)) {
return null;
}
return userName2User.get(userName);
}
/**
* Find an account of the user.
*
* @param user in Db
* @return instance of Account of the user
*/
public Account findAccountByUser(User user) {
if (!user2Account.containsKey(user)) {
return null;
}
return user2Account.get(user);
}
/**
* Find a product with the itemName.
*
* @param itemName of the item
* @return instance of Product
*/
public Product findProductByItemName(String itemName) {
if (!itemName2Product.containsKey(itemName)) {
return null;
}
return itemName2Product.get(itemName);
}
/**
* User class to store user info.
*/
public class User {
private String userName;
public User(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public ReceiptDto purchase(Product item) {
return new ReceiptDto(item.getPrice());
}
}
/**
* Account info.
*/
public class Account {
private Double amount;
public Account(Double amount) {
this.amount = amount;
}
/**
* Withdraw the price of the item from the account.
*
* @param price of the item
* @return instance of MoneyTransaction
*/
public MoneyTransaction withdraw(Double price) {
if (price > amount) {
return null;
}
return new MoneyTransaction(amount, price);
}
public Double getAmount() {
return amount;
}
}
/**
* Product info.
*/
public class Product {
private Double price;
public Product(Double price) {
this.price = price;
}
public Double getPrice() {
return price;
}
}
}
| 4,578 | 23.88587 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServices.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
/**
* ApplicationServices interface to demonstrate special case pattern.
*/
public interface ApplicationServices {
ReceiptViewModel loggedInUserPurchase(String userName, String itemName);
}
| 1,514 | 43.558824 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/MaintenanceLock.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Acquire lock on the DB for maintenance.
*/
public class MaintenanceLock {
private static final Logger LOGGER = LoggerFactory.getLogger(MaintenanceLock.class);
private static MaintenanceLock instance;
private boolean lock = true;
/**
* Get the instance of MaintenanceLock.
*
* @return singleton instance of MaintenanceLock
*/
public static synchronized MaintenanceLock getInstance() {
if (instance == null) {
instance = new MaintenanceLock();
}
return instance;
}
public boolean isLock() {
return lock;
}
public void setLock(boolean lock) {
this.lock = lock;
LOGGER.info("Maintenance lock is set to: ", lock);
}
}
| 2,065 | 32.868852 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/ReceiptDto.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Receipt view representing the transaction recceipt.
*/
public class ReceiptDto implements ReceiptViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ReceiptDto.class);
private Double price;
public ReceiptDto(Double price) {
this.price = price;
}
public Double getPrice() {
return price;
}
@Override
public void show() {
LOGGER.info("Receipt: " + price + " paid");
}
}
| 1,809 | 33.807692 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/MoneyTransaction.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
/**
* Represents the money transaction taking place at a given moment.
*/
public class MoneyTransaction {
private Double amount;
private Double price;
public MoneyTransaction(Double amount, Double price) {
this.amount = amount;
this.price = price;
}
}
| 1,591 | 38.8 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/DomainServices.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
/**
* DomainServices interface.
*/
public interface DomainServices {
}
| 1,392 | 42.53125 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/InvalidUser.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Receipt View representing invalid user.
*/
public class InvalidUser implements ReceiptViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(InvalidUser.class);
private final String userName;
public InvalidUser(String userName) {
this.userName = userName;
}
@Override
public void show() {
LOGGER.info("Invalid user: " + userName);
}
}
| 1,764 | 35.770833 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServicesImpl.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
/**
* Implementation of special case pattern.
*/
public class ApplicationServicesImpl implements ApplicationServices {
private DomainServicesImpl domain = new DomainServicesImpl();
@Override
public ReceiptViewModel loggedInUserPurchase(String userName, String itemName) {
if (isDownForMaintenance()) {
return new DownForMaintenance();
}
return this.domain.purchase(userName, itemName);
}
private boolean isDownForMaintenance() {
return MaintenanceLock.getInstance().isLock();
}
}
| 1,838 | 38.978261 | 140 | java |
java-design-patterns | java-design-patterns-master/special-case/src/main/java/com/iluwatar/specialcase/InsufficientFunds.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specialcase;
import lombok.extern.slf4j.Slf4j;
/**
* View representing insufficient funds.
*/
@Slf4j
public class InsufficientFunds implements ReceiptViewModel {
private String userName;
private Double amount;
private String itemName;
/**
* Constructor of InsufficientFunds.
*
* @param userName of the user
* @param amount of the user's account
* @param itemName of the item
*/
public InsufficientFunds(String userName, Double amount, String itemName) {
this.userName = userName;
this.amount = amount;
this.itemName = itemName;
}
@Override
public void show() {
LOGGER.info("Insufficient funds: " + amount + " of user: " + userName
+ " for buying item: " + itemName);
}
}
| 2,043 | 34.241379 | 140 | java |
java-design-patterns | java-design-patterns-master/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.delegation.simple;
import static org.junit.jupiter.api.Assertions.assertEquals;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.iluwatar.delegation.simple.printers.CanonPrinter;
import com.iluwatar.delegation.simple.printers.EpsonPrinter;
import com.iluwatar.delegation.simple.printers.HpPrinter;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
/**
* Test for Delegation Pattern
*/
class DelegateTest {
private InMemoryAppender appender;
@BeforeEach
void setUp() {
appender = new InMemoryAppender();
}
@AfterEach
void tearDown() {
appender.stop();
}
private static final String MESSAGE = "Test Message Printed";
@Test
void testCanonPrinter() throws Exception {
var printerController = new PrinterController(new CanonPrinter());
printerController.print(MESSAGE);
assertEquals("Canon Printer : Test Message Printed", appender.getLastMessage());
}
@Test
void testHpPrinter() throws Exception {
var printerController = new PrinterController(new HpPrinter());
printerController.print(MESSAGE);
assertEquals("HP Printer : Test Message Printed", appender.getLastMessage());
}
@Test
void testEpsonPrinter() throws Exception {
var printerController = new PrinterController(new EpsonPrinter());
printerController.print(MESSAGE);
assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage());
}
/**
* Logging Appender
*/
private static class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
public int getLogSize() {
return log.size();
}
}
}
| 3,520 | 30.4375 | 140 | java |
java-design-patterns | java-design-patterns-master/delegation/src/test/java/com/iluwatar/delegation/simple/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.delegation.simple;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application Test Entry
*/
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,819 | 36.142857 | 140 | java |
java-design-patterns | java-design-patterns-master/delegation/src/main/java/com/iluwatar/delegation/simple/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.delegation.simple;
import com.iluwatar.delegation.simple.printers.CanonPrinter;
import com.iluwatar.delegation.simple.printers.EpsonPrinter;
import com.iluwatar.delegation.simple.printers.HpPrinter;
/**
* The delegate pattern provides a mechanism to abstract away the implementation and control of the
* desired action. The class being called in this case {@link PrinterController} is not responsible
* for the actual desired action, but is actually delegated to a helper class either {@link
* CanonPrinter}, {@link EpsonPrinter} or {@link HpPrinter}. The consumer does not have or require
* knowledge of the actual class carrying out the action, only the container on which they are
* calling.
*
* <p>In this example the delegates are {@link EpsonPrinter}, {@link HpPrinter} and {@link
* CanonPrinter} they all implement {@link Printer}. The {@link PrinterController} class also
* implements {@link Printer}. However neither provide the functionality of {@link Printer} by
* printing to the screen, they actually call upon the instance of {@link Printer} that they were
* instantiated with. Therefore delegating the behaviour to another class.
*/
public class App {
private static final String MESSAGE_TO_PRINT = "hello world";
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var hpPrinterController = new PrinterController(new HpPrinter());
var canonPrinterController = new PrinterController(new CanonPrinter());
var epsonPrinterController = new PrinterController(new EpsonPrinter());
hpPrinterController.print(MESSAGE_TO_PRINT);
canonPrinterController.print(MESSAGE_TO_PRINT);
epsonPrinterController.print(MESSAGE_TO_PRINT);
}
}
| 3,057 | 46.046154 | 140 | java |
java-design-patterns | java-design-patterns-master/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.delegation.simple;
/**
* Delegator Class to delegate the implementation of the Printer. This ensures two things: - when
* the actual implementation of the Printer class changes the delegation will still be operational -
* the actual benefit is observed when there are more than one implementors and they share a
* delegation control
*/
public class PrinterController implements Printer {
private final Printer printer;
public PrinterController(Printer printer) {
this.printer = printer;
}
/**
* This method is implemented from {@link Printer} however instead on providing an implementation,
* it instead calls upon the class passed through the constructor. This is the delegate, hence the
* pattern. Therefore meaning that the caller does not care of the implementing class only the
* owning controller.
*
* @param message to be printed to the screen
*/
@Override
public void print(String message) {
printer.print(message);
}
}
| 2,285 | 41.333333 | 140 | java |
java-design-patterns | java-design-patterns-master/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.delegation.simple;
import com.iluwatar.delegation.simple.printers.CanonPrinter;
import com.iluwatar.delegation.simple.printers.EpsonPrinter;
import com.iluwatar.delegation.simple.printers.HpPrinter;
/**
* Interface that both the Controller and the Delegate will implement.
*
* @see CanonPrinter
* @see EpsonPrinter
* @see HpPrinter
*/
public interface Printer {
/**
* Method that takes a String to print to the screen. This will be implemented on both the
* controller and the delegate allowing the controller to call the same method on the delegate
* class.
*
* @param message to be printed to the screen
*/
void print(final String message);
}
| 1,981 | 39.44898 | 140 | java |
java-design-patterns | java-design-patterns-master/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.delegation.simple.printers;
import com.iluwatar.delegation.simple.Printer;
import lombok.extern.slf4j.Slf4j;
/**
* Specialised Implementation of {@link Printer} for a HP Printer, in this case the message to be
* printed is appended to "HP Printer : ".
*
* @see Printer
*/
@Slf4j
public class HpPrinter implements Printer {
/**
* {@inheritDoc}
*/
@Override
public void print(String message) {
LOGGER.info("HP Printer : {}", message);
}
}
| 1,769 | 35.875 | 140 | java |
java-design-patterns | java-design-patterns-master/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.delegation.simple.printers;
import com.iluwatar.delegation.simple.Printer;
import lombok.extern.slf4j.Slf4j;
/**
* Specialised Implementation of {@link Printer} for a Canon Printer, in this case the message to be
* printed is appended to "Canon Printer : ".
*
* @see Printer
*/
@Slf4j
public class CanonPrinter implements Printer {
/**
* {@inheritDoc}
*/
@Override
public void print(String message) {
LOGGER.info("Canon Printer : {}", message);
}
}
| 1,781 | 36.125 | 140 | java |
java-design-patterns | java-design-patterns-master/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.delegation.simple.printers;
import com.iluwatar.delegation.simple.Printer;
import lombok.extern.slf4j.Slf4j;
/**
* Specialised Implementation of {@link Printer} for a Epson Printer, in this case the message to be
* printed is appended to "Epson Printer : ".
*
* @see Printer
*/
@Slf4j
public class EpsonPrinter implements Printer {
/**
* {@inheritDoc}
*/
@Override
public void print(String message) {
LOGGER.info("Epson Printer : {}", message);
}
}
| 1,781 | 36.125 | 140 | java |
java-design-patterns | java-design-patterns-master/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/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.collectionpipeline;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
/**
* Tests that Collection Pipeline methods work as expected.
*/
@Slf4j
class AppTest {
private final List<Car> cars = CarFactory.createCars();
@Test
void testGetModelsAfter2000UsingFor() {
var models = ImperativeProgramming.getModelsAfter2000(cars);
assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models);
}
@Test
void testGetModelsAfter2000UsingPipeline() {
var models = FunctionalProgramming.getModelsAfter2000(cars);
assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models);
}
@Test
void testGetGroupingOfCarsByCategory() {
var modelsExpected = Map.of(
Category.CONVERTIBLE, List.of(
new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE),
new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)
),
Category.SEDAN, List.of(
new Car("Dodge", "Avenger", 2010, Category.SEDAN),
new Car("Ford", "Focus", 2012, Category.SEDAN)
),
Category.JEEP, List.of(
new Car("Jeep", "Wrangler", 2011, Category.JEEP),
new Car("Jeep", "Comanche", 1990, Category.JEEP))
);
var modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars);
var modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars);
LOGGER.info("Category " + modelsFunctional);
assertEquals(modelsExpected, modelsFunctional);
assertEquals(modelsExpected, modelsImperative);
}
@Test
void testGetSedanCarsOwnedSortedByDate() {
var john = new Person(cars);
var modelsExpected = List.of(
new Car("Dodge", "Avenger", 2010, Category.SEDAN),
new Car("Ford", "Focus", 2012, Category.SEDAN)
);
var modelsFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john));
var modelsImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john));
assertEquals(modelsExpected, modelsFunctional);
assertEquals(modelsExpected, modelsImperative);
}
}
| 3,528 | 38.651685 | 140 | java |
java-design-patterns | java-design-patterns-master/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectionpipeline;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Iterating and sorting with a collection pipeline
*
* <p>In functional programming, it's common to sequence complex operations through
* a series of smaller modular functions or operations. The series is called a composition of
* functions, or a function composition. When a collection of data flows through a function
* composition, it becomes a collection pipeline. Function Composition and Collection Pipeline are
* two design patterns frequently used in functional-style programming.
*
* <p>Instead of passing a lambda expression to the map method, we passed the
* method reference Car::getModel. Likewise, instead of passing the lambda expression car ->
* car.getYear() to the comparing method, we passed the method reference Car::getYear. Method
* references are short, concise, and expressive. It is best to use them wherever possible.
*/
public class FunctionalProgramming {
private FunctionalProgramming() {
}
/**
* Method to get models using for collection pipeline.
*
* @param cars {@link List} of {@link Car} to be used for filtering
* @return {@link List} of {@link String} representing models built after year 2000
*/
public static List<String> getModelsAfter2000(List<Car> cars) {
return cars.stream().filter(car -> car.getYear() > 2000)
.sorted(Comparator.comparing(Car::getYear))
.map(Car::getModel).toList();
}
/**
* Method to group cars by category using groupingBy.
*
* @param cars {@link List} of {@link Car} to be used for grouping
* @return {@link Map} with category as key and cars belonging to that category as value
*/
public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> cars) {
return cars.stream().collect(Collectors.groupingBy(Car::getCategory));
}
/**
* Method to get all Sedan cars belonging to a group of persons sorted by year of manufacture.
*
* @param persons {@link List} of {@link Person} to be used
* @return {@link List} of {@link Car} to belonging to the group
*/
public static List<Car> getSedanCarsOwnedSortedByDate(List<Person> persons) {
return persons.stream().map(Person::getCars).flatMap(List::stream)
.filter(car -> Category.SEDAN.equals(car.getCategory()))
.sorted(Comparator.comparing(Car::getYear)).toList();
}
}
| 3,758 | 43.75 | 140 | java |
java-design-patterns | java-design-patterns-master/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/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.collectionpipeline;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
/**
* In imperative-style programming, it is common to use for and while loops for most kinds of data
* processing. Function composition is a simple technique that lets you sequence modular functions
* to create more complex operations. When you run data through the sequence, you have a collection
* pipeline. Together, the Function Composition and Collection Pipeline patterns enable you to
* create sophisticated programs where data flow from upstream to downstream and is passed through a
* series of transformations.
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var cars = CarFactory.createCars();
var modelsImperative = ImperativeProgramming.getModelsAfter2000(cars);
LOGGER.info(modelsImperative.toString());
var modelsFunctional = FunctionalProgramming.getModelsAfter2000(cars);
LOGGER.info(modelsFunctional.toString());
var groupingByCategoryImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars);
LOGGER.info(groupingByCategoryImperative.toString());
var groupingByCategoryFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars);
LOGGER.info(groupingByCategoryFunctional.toString());
var john = new Person(cars);
var sedansOwnedImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john));
LOGGER.info(sedansOwnedImperative.toString());
var sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john));
LOGGER.info(sedansOwnedFunctional.toString());
}
}
| 3,002 | 41.9 | 140 | java |
java-design-patterns | java-design-patterns-master/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectionpipeline;
/**
* Enum for the category of car.
*/
public enum Category {
JEEP,
SEDAN,
CONVERTIBLE
}
| 1,423 | 39.685714 | 140 | java |
java-design-patterns | java-design-patterns-master/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectionpipeline;
import java.util.List;
/**
* A factory class to create a collection of {@link Car} instances.
*/
public class CarFactory {
private CarFactory() {
}
/**
* Factory method to create a {@link List} of {@link Car} instances.
*
* @return {@link List} of {@link Car}
*/
public static List<Car> createCars() {
return List.of(new Car("Jeep", "Wrangler", 2011, Category.JEEP),
new Car("Jeep", "Comanche", 1990, Category.JEEP),
new Car("Dodge", "Avenger", 2010, Category.SEDAN),
new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE),
new Car("Ford", "Focus", 2012, Category.SEDAN),
new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE));
}
} | 2,036 | 40.571429 | 140 | java |
java-design-patterns | java-design-patterns-master/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectionpipeline;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* A Car class that has the properties of make, model, year and category.
*/
@Getter
@EqualsAndHashCode
@RequiredArgsConstructor
public class Car {
private final String make;
private final String model;
private final int year;
private final Category category;
} | 1,696 | 38.465116 | 140 | java |
java-design-patterns | java-design-patterns-master/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/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.collectionpipeline;
import java.util.List;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* A Person class that has the list of cars that the person owns and use.
*/
@Getter
@RequiredArgsConstructor
public class Person {
private final List<Car> cars;
} | 1,583 | 38.6 | 140 | java |
java-design-patterns | java-design-patterns-master/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.collectionpipeline;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Imperative-style programming to iterate over the list and get the names of cars made later than
* the year 2000. We then sort the models in ascending order by year.
*
* <p>As you can see, there's a lot of looping in this code. First, the
* getModelsAfter2000UsingFor method takes a list of cars as its parameter. It extracts or filters
* out cars made after the year 2000, putting them into a new list named carsSortedByYear. Next, it
* sorts that list in ascending order by year-of-make. Finally, it loops through the list
* carsSortedByYear to get the model names and returns them in a list.
*
* <p>This short example demonstrates what I call the effect of statements. While
* functions and methods in general can be used as expressions, the {@link Collections} sort method
* doesn't return a result. Because it is used as a statement, it mutates the list given as
* argument. Both of the for loops also mutate lists as they iterate. Being statements, that's just
* how these elements work. As a result, the code contains unnecessary garbage variables
*/
public class ImperativeProgramming {
private ImperativeProgramming() {
}
/**
* Method to return the car models built after year 2000 using for loops.
*
* @param cars {@link List} of {@link Car} to iterate over
* @return {@link List} of {@link String} of car models built after year 2000
*/
public static List<String> getModelsAfter2000(List<Car> cars) {
List<Car> carsSortedByYear = new ArrayList<>();
for (Car car : cars) {
if (car.getYear() > 2000) {
carsSortedByYear.add(car);
}
}
Collections.sort(carsSortedByYear, new Comparator<Car>() {
@Override
public int compare(Car car1, Car car2) {
return car1.getYear() - car2.getYear();
}
});
List<String> models = new ArrayList<>();
for (Car car : carsSortedByYear) {
models.add(car.getModel());
}
return models;
}
/**
* Method to group cars by category using for loops.
*
* @param cars {@link List} of {@link Car} to be used for grouping
* @return {@link Map} with category as key and cars belonging to that category as value
*/
public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> cars) {
Map<Category, List<Car>> groupingByCategory = new HashMap<>();
for (Car car : cars) {
if (groupingByCategory.containsKey(car.getCategory())) {
groupingByCategory.get(car.getCategory()).add(car);
} else {
List<Car> categoryCars = new ArrayList<>();
categoryCars.add(car);
groupingByCategory.put(car.getCategory(), categoryCars);
}
}
return groupingByCategory;
}
/**
* Method to get all Sedan cars belonging to a group of persons sorted by year of manufacture
* using for loops.
*
* @param persons {@link List} of {@link Person} to be used
* @return {@link List} of {@link Car} to belonging to the group
*/
public static List<Car> getSedanCarsOwnedSortedByDate(List<Person> persons) {
List<Car> cars = new ArrayList<>();
for (Person person : persons) {
cars.addAll(person.getCars());
}
List<Car> sedanCars = new ArrayList<>();
for (Car car : cars) {
if (Category.SEDAN.equals(car.getCategory())) {
sedanCars.add(car);
}
}
sedanCars.sort(new Comparator<Car>() {
@Override
public int compare(Car o1, Car o2) {
return o1.getYear() - o2.getYear();
}
});
return sedanCars;
}
}
| 5,018 | 36.455224 | 140 | java |
java-design-patterns | java-design-patterns-master/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.decorator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link ClubbedTroll}
*/
class ClubbedTrollTest {
@Test
void testClubbedTroll() {
// Create a normal troll first, but make sure we can spy on it later on.
final var simpleTroll = spy(new SimpleTroll());
// Now we want to decorate the troll to make it stronger ...
final var clubbed = new ClubbedTroll(simpleTroll);
assertEquals(20, clubbed.getAttackPower());
verify(simpleTroll, times(1)).getAttackPower();
// Check if the clubbed troll actions are delegated to the decorated troll
clubbed.attack();
verify(simpleTroll, times(1)).attack();
clubbed.fleeBattle();
verify(simpleTroll, times(1)).fleeBattle();
verifyNoMoreInteractions(simpleTroll);
}
}
| 2,359 | 39 | 140 | java |
java-design-patterns | java-design-patterns-master/decorator/src/test/java/com/iluwatar/decorator/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.decorator;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,804 | 36.604167 | 140 | java |
java-design-patterns | java-design-patterns-master/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.decorator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
/**
* Tests for {@link SimpleTroll}
*/
class SimpleTrollTest {
private InMemoryAppender appender;
@BeforeEach
void setUp() {
appender = new InMemoryAppender(SimpleTroll.class);
}
@AfterEach
void tearDown() {
appender.stop();
}
@Test
void testTrollActions() {
final var troll = new SimpleTroll();
assertEquals(10, troll.getAttackPower());
troll.attack();
assertEquals("The troll tries to grab you!", appender.getLastMessage());
troll.fleeBattle();
assertEquals("The troll shrieks in horror and runs away!", appender.getLastMessage());
assertEquals(2, appender.getLogSize());
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private final List<ILoggingEvent> log = new LinkedList<>();
InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
String getLastMessage() {
return log.get(log.size() - 1).getMessage();
}
int getLogSize() {
return log.size();
}
}
}
| 2,864 | 29.806452 | 140 | java |
java-design-patterns | java-design-patterns-master/decorator/src/main/java/com/iluwatar/decorator/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.decorator;
import lombok.extern.slf4j.Slf4j;
/**
* The Decorator pattern is a more flexible alternative to subclassing. The Decorator class
* implements the same interface as the target and uses composition to "decorate" calls to the
* target. Using the Decorator pattern it is possible to change the behavior of the class during
* runtime.
*
* <p>In this example we show how the simple {@link SimpleTroll} first attacks and then flees the
* battle. Then we decorate the {@link SimpleTroll} with a {@link ClubbedTroll} and perform the
* attack again. You can see how the behavior changes after the decoration.
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// simple troll
LOGGER.info("A simple looking troll approaches.");
var troll = new SimpleTroll();
troll.attack();
troll.fleeBattle();
LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower());
// change the behavior of the simple troll by adding a decorator
LOGGER.info("A troll with huge club surprises you.");
var clubbedTroll = new ClubbedTroll(troll);
clubbedTroll.attack();
clubbedTroll.fleeBattle();
LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower());
}
}
| 2,620 | 39.953125 | 140 | java |
java-design-patterns | java-design-patterns-master/decorator/src/main/java/com/iluwatar/decorator/Troll.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.decorator;
/**
* Interface for trolls.
*/
public interface Troll {
void attack();
int getAttackPower();
void fleeBattle();
}
| 1,443 | 36.025641 | 140 | java |
java-design-patterns | java-design-patterns-master/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.decorator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Decorator that adds a club for the troll.
*/
@Slf4j
@RequiredArgsConstructor
public class ClubbedTroll implements Troll {
private final Troll decorated;
@Override
public void attack() {
decorated.attack();
LOGGER.info("The troll swings at you with a club!");
}
@Override
public int getAttackPower() {
return decorated.getAttackPower() + 10;
}
@Override
public void fleeBattle() {
decorated.fleeBattle();
}
}
| 1,847 | 32.6 | 140 | java |
java-design-patterns | java-design-patterns-master/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.decorator;
import lombok.extern.slf4j.Slf4j;
/**
* SimpleTroll implements {@link Troll} interface directly.
*/
@Slf4j
public class SimpleTroll implements Troll {
@Override
public void attack() {
LOGGER.info("The troll tries to grab you!");
}
@Override
public int getAttackPower() {
return 10;
}
@Override
public void fleeBattle() {
LOGGER.info("The troll shrieks in horror and runs away!");
}
}
| 1,737 | 33.76 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/test/java/com/iluwatar/lockableobject/SubCreaturesTests.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject;
import com.iluwatar.lockableobject.domain.CreatureStats;
import com.iluwatar.lockableobject.domain.Elf;
import com.iluwatar.lockableobject.domain.Human;
import com.iluwatar.lockableobject.domain.Orc;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SubCreaturesTests {
@Test
void statsTest(){
var elf = new Elf("Limbar");
var orc = new Orc("Dargal");
var human = new Human("Jerry");
Assertions.assertEquals(CreatureStats.ELF_HEALTH.getValue(), elf.getHealth());
Assertions.assertEquals(CreatureStats.ELF_DAMAGE.getValue(), elf.getDamage());
Assertions.assertEquals(CreatureStats.ORC_DAMAGE.getValue(), orc.getDamage());
Assertions.assertEquals(CreatureStats.ORC_HEALTH.getValue(), orc.getHealth());
Assertions.assertEquals(CreatureStats.HUMAN_DAMAGE.getValue(), human.getDamage());
Assertions.assertEquals(CreatureStats.HUMAN_HEALTH.getValue(), human.getHealth());
}
}
| 2,268 | 45.306122 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ExceptionsTest {
private String msg = "test";
@Test
void testException(){
Exception e;
try{
throw new LockingException(msg);
}
catch(LockingException ex){
e = ex;
}
Assertions.assertEquals(msg, e.getMessage());
}
}
| 1,666 | 35.23913 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject;
import com.iluwatar.lockableobject.domain.Creature;
import com.iluwatar.lockableobject.domain.CreatureStats;
import com.iluwatar.lockableobject.domain.CreatureType;
import com.iluwatar.lockableobject.domain.Elf;
import com.iluwatar.lockableobject.domain.Orc;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class CreatureTest {
private Creature orc;
private Creature elf;
private Lockable sword;
@BeforeEach
void init() {
elf = new Elf("Elf test");
orc = new Orc("Orc test");
sword = new SwordOfAragorn();
}
@Test
void baseTest() {
Assertions.assertEquals("Elf test", elf.getName());
Assertions.assertEquals(CreatureType.ELF, elf.getType());
Assertions.assertThrows(NullPointerException.class, () -> new Elf(null));
Assertions.assertThrows(NullPointerException.class, () -> elf.acquire(null));
Assertions.assertThrows(NullPointerException.class, () -> elf.attack(null));
Assertions.assertThrows(IllegalArgumentException.class, () -> elf.hit(-10));
}
@Test
void hitTest() {
elf.hit(CreatureStats.ELF_HEALTH.getValue() / 2);
Assertions.assertEquals(CreatureStats.ELF_HEALTH.getValue() / 2, elf.getHealth());
elf.hit(CreatureStats.ELF_HEALTH.getValue() / 2);
Assertions.assertFalse(elf.isAlive());
Assertions.assertEquals(0, orc.getInstruments().size());
Assertions.assertTrue(orc.acquire(sword));
Assertions.assertEquals(1, orc.getInstruments().size());
orc.kill();
Assertions.assertEquals(0, orc.getInstruments().size());
}
@Test
void testFight() throws InterruptedException {
killCreature(elf, orc);
Assertions.assertTrue(elf.isAlive());
Assertions.assertFalse(orc.isAlive());
Assertions.assertTrue(elf.getHealth() > 0);
Assertions.assertTrue(orc.getHealth() <= 0);
}
@Test
void testAcqusition() throws InterruptedException {
Assertions.assertTrue(elf.acquire(sword));
Assertions.assertEquals(elf.getName(), sword.getLocker().getName());
Assertions.assertTrue(elf.getInstruments().contains(sword));
Assertions.assertFalse(orc.acquire(sword));
killCreature(orc, elf);
Assertions.assertTrue(orc.acquire(sword));
Assertions.assertEquals(orc, sword.getLocker());
}
void killCreature(Creature source, Creature target) throws InterruptedException {
while (target.isAlive()) {
source.attack(target);
}
}
@Test
void invalidDamageTest(){
Assertions.assertThrows(IllegalArgumentException.class, () -> elf.hit(-50));
}
}
| 3,895 | 36.461538 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/test/java/com/iluwatar/lockableobject/TheSwordOfAragornTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject;
import com.iluwatar.lockableobject.domain.Human;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class TheSwordOfAragornTest {
@Test
void basicSwordTest() {
var sword = new SwordOfAragorn();
Assertions.assertNotNull(sword.getName());
Assertions.assertNull(sword.getLocker());
Assertions.assertFalse(sword.isLocked());
var human = new Human("Tupac");
Assertions.assertTrue(human.acquire(sword));
Assertions.assertEquals(human, sword.getLocker());
Assertions.assertTrue(sword.isLocked());
}
@Test
void invalidLockerTest(){
var sword = new SwordOfAragorn();
Assertions.assertThrows(NullPointerException.class, () -> sword.lock(null));
Assertions.assertThrows(NullPointerException.class, () -> sword.unlock(null));
}
}
| 2,124 | 39.865385 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/test/java/com/iluwatar/lockableobject/FeindTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject;
import com.iluwatar.lockableobject.domain.Creature;
import com.iluwatar.lockableobject.domain.Elf;
import com.iluwatar.lockableobject.domain.Feind;
import com.iluwatar.lockableobject.domain.Orc;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class FeindTest {
private Creature elf;
private Creature orc;
private Lockable sword;
@BeforeEach
void init(){
elf = new Elf("Nagdil");
orc = new Orc("Ghandar");
sword = new SwordOfAragorn();
}
@Test
void nullTests(){
Assertions.assertThrows(NullPointerException.class, () -> new Feind(null, null));
Assertions.assertThrows(NullPointerException.class, () -> new Feind(elf, null));
Assertions.assertThrows(NullPointerException.class, () -> new Feind(null, sword));
}
@Test
void testBaseCase() throws InterruptedException {
var base = new Thread(new Feind(orc, sword));
Assertions.assertNull(sword.getLocker());
base.start();
base.join();
Assertions.assertEquals(orc, sword.getLocker());
var extend = new Thread(new Feind(elf, sword));
extend.start();
extend.join();
Assertions.assertTrue(sword.isLocked());
sword.unlock(elf.isAlive() ? elf : orc);
Assertions.assertNull(sword.getLocker());
}
}
| 2,626 | 35.486111 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/test/java/com/iluwatar/lockableobject/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.lockableobject;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
class AppTest {
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[] {}));
}
@Test
void shouldExecuteApplicationAsRunnableWithoutException() {
assertDoesNotThrow(() -> (new App()).run());
}
}
| 1,690 | 38.325581 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/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.lockableobject;
import com.iluwatar.lockableobject.domain.Creature;
import com.iluwatar.lockableobject.domain.Elf;
import com.iluwatar.lockableobject.domain.Feind;
import com.iluwatar.lockableobject.domain.Human;
import com.iluwatar.lockableobject.domain.Orc;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
/**
* The Lockable Object pattern is a concurrency pattern. Instead of using the "synchronized" word
* upon the methods to be synchronized, the object which implements the Lockable interface handles
* the request.
*
* <p>In this example, we create a new Lockable object with the SwordOfAragorn implementation of it.
* Afterwards we create 6 Creatures with the Elf, Orc and Human implementations and assign them each
* to a Fiend object and the Sword is the target object. Because there is only one Sword and it uses
* the Lockable Object pattern, only one creature can hold the sword at a given time. When the sword
* is locked, any other alive Fiends will try to lock, which will result in a race to lock the
* sword.
*
* @author Noam Greenshtain
*/
@Slf4j
public class App implements Runnable {
private static final int WAIT_TIME = 3;
private static final int WORKERS = 2;
private static final int MULTIPLICATION_FACTOR = 3;
/**
* main method.
*
* @param args as arguments for the main method.
*/
public static void main(String[] args) {
var app = new App();
app.run();
}
@Override
public void run() {
// The target object for this example.
var sword = new SwordOfAragorn();
// Creation of creatures.
List<Creature> creatures = new ArrayList<>();
for (var i = 0; i < WORKERS; i++) {
creatures.add(new Elf(String.format("Elf %s", i)));
creatures.add(new Orc(String.format("Orc %s", i)));
creatures.add(new Human(String.format("Human %s", i)));
}
int totalFiends = WORKERS * MULTIPLICATION_FACTOR;
ExecutorService service = Executors.newFixedThreadPool(totalFiends);
// Attach every creature and the sword is a Fiend to fight for the sword.
for (var i = 0; i < totalFiends; i = i + MULTIPLICATION_FACTOR) {
service.submit(new Feind(creatures.get(i), sword));
service.submit(new Feind(creatures.get(i + 1), sword));
service.submit(new Feind(creatures.get(i + 2), sword));
}
// Wait for program to terminate.
try {
if (!service.awaitTermination(WAIT_TIME, TimeUnit.SECONDS)) {
LOGGER.info("The master of the sword is now {}.", sword.getLocker().getName());
}
} catch (InterruptedException e) {
LOGGER.error(e.getMessage());
Thread.currentThread().interrupt();
} finally {
service.shutdown();
}
}
}
| 4,162 | 39.813725 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/SwordOfAragorn.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject;
import com.iluwatar.lockableobject.domain.Creature;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
/**
* An implementation of a Lockable object. This is the the Sword of Aragorn and every creature wants
* to posses it!
*/
@Slf4j
public class SwordOfAragorn implements Lockable {
private Creature locker;
private final Object synchronizer;
private static final String NAME = "The Sword of Aragorn";
public SwordOfAragorn() {
this.locker = null;
this.synchronizer = new Object();
}
@Override
public boolean isLocked() {
return this.locker != null;
}
@Override
public boolean lock(@NonNull Creature creature) {
synchronized (synchronizer) {
LOGGER.info("{} is now trying to acquire {}!", creature.getName(), this.getName());
if (!isLocked()) {
locker = creature;
return true;
} else {
if (!locker.getName().equals(creature.getName())) {
return false;
}
}
}
return false;
}
@Override
public void unlock(@NonNull Creature creature) {
synchronized (synchronizer) {
if (locker != null && locker.getName().equals(creature.getName())) {
locker = null;
LOGGER.info("{} is now free!", this.getName());
}
if (locker != null) {
throw new LockingException("You cannot unlock an object you are not the owner of.");
}
}
}
@Override
public Creature getLocker() {
return this.locker;
}
@Override
public String getName() {
return NAME;
}
}
| 2,858 | 30.417582 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject;
/**
* An exception regarding the locking process of a Lockable object.
*/
public class LockingException extends RuntimeException {
private static final long serialVersionUID = 8556381044865867037L;
public LockingException(String message) {
super(message);
}
}
| 1,597 | 39.974359 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/Lockable.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject;
import com.iluwatar.lockableobject.domain.Creature;
/** This interface describes the methods to be supported by a lockable-object. */
public interface Lockable {
/**
* Checks if the object is locked.
*
* @return true if it is locked.
*/
boolean isLocked();
/**
* locks the object with the creature as the locker.
*
* @param creature as the locker.
* @return true if the object was locked successfully.
*/
boolean lock(Creature creature);
/**
* Unlocks the object.
*
* @param creature as the locker.
*/
void unlock(Creature creature);
/**
* Gets the locker.
*
* @return the Creature that holds the object. Returns null if no one is locking.
*/
Creature getLocker();
/**
* Returns the name of the object.
*
* @return the name of the object.
*/
String getName();
}
| 2,173 | 30.970588 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureType.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject.domain;
/** Constants of supported creatures. */
public enum CreatureType {
ORC,
HUMAN,
ELF
}
| 1,421 | 42.090909 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject.domain;
/** Attribute constants of each Creature implementation. */
public enum CreatureStats {
ELF_HEALTH(90),
ELF_DAMAGE(40),
ORC_HEALTH(70),
ORC_DAMAGE(50),
HUMAN_HEALTH(60),
HUMAN_DAMAGE(60);
int value;
private CreatureStats(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
| 1,665 | 35.217391 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Elf.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject.domain;
/** An Elf implementation of a Creature. */
public class Elf extends Creature {
/**
* A constructor that initializes the attributes of an elf.
*
* @param name as the name of the creature.
*/
public Elf(String name) {
super(name);
setType(CreatureType.ELF);
setDamage(CreatureStats.ELF_DAMAGE.getValue());
setHealth(CreatureStats.ELF_HEALTH.getValue());
}
}
| 1,721 | 40 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject.domain;
import com.iluwatar.lockableobject.Lockable;
import java.util.HashSet;
import java.util.Set;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
* An abstract class of a creature that wanders across the wasteland. It can attack, get hit and
* acquire a Lockable object.
*/
@Getter
@Setter
@Slf4j
public abstract class Creature {
private String name;
private CreatureType type;
private int health;
private int damage;
Set<Lockable> instruments;
protected Creature(@NonNull String name) {
this.name = name;
this.instruments = new HashSet<>();
}
/**
* Reaches for the Lockable and tried to hold it.
*
* @param lockable as the Lockable to lock.
* @return true of Lockable was locked by this creature.
*/
public boolean acquire(@NonNull Lockable lockable) {
if (lockable.lock(this)) {
instruments.add(lockable);
return true;
}
return false;
}
/** Terminates the Creature and unlocks all of the Lockable that it posses. */
public synchronized void kill() {
LOGGER.info("{} {} has been slayed!", type, name);
for (Lockable lockable : instruments) {
lockable.unlock(this);
}
this.instruments.clear();
}
/**
* Attacks a foe.
*
* @param creature as the foe to be attacked.
*/
public synchronized void attack(@NonNull Creature creature) {
creature.hit(getDamage());
}
/**
* When a creature gets hit it removed the amount of damage from the creature's life.
*
* @param damage as the damage that was taken.
*/
public synchronized void hit(int damage) {
if (damage < 0) {
throw new IllegalArgumentException("Damage cannot be a negative number");
}
if (isAlive()) {
setHealth(getHealth() - damage);
if (!isAlive()) {
kill();
}
}
}
/**
* Checks if the creature is still alive.
*
* @return true of creature is alive.
*/
public synchronized boolean isAlive() {
return getHealth() > 0;
}
}
| 3,370 | 28.570175 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Orc.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject.domain;
/** A Orc implementation of a Creature. */
public class Orc extends Creature {
/**
* A constructor that initializes the attributes of an orc.
*
* @param name as the name of the creature.
*/
public Orc(String name) {
super(name);
setType(CreatureType.ORC);
setDamage(CreatureStats.ORC_DAMAGE.getValue());
setHealth(CreatureStats.ORC_HEALTH.getValue());
}
}
| 1,719 | 40.95122 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Human.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject.domain;
/** A human implementation of a Creature. */
public class Human extends Creature {
/**
* A constructor that initializes the attributes of an human.
*
* @param name as the name of the creature.
*/
public Human(String name) {
super(name);
setType(CreatureType.HUMAN);
setDamage(CreatureStats.HUMAN_DAMAGE.getValue());
setHealth(CreatureStats.HUMAN_HEALTH.getValue());
}
}
| 1,734 | 40.309524 | 140 | java |
java-design-patterns | java-design-patterns-master/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject.domain;
import com.iluwatar.lockableobject.Lockable;
import java.security.SecureRandom;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** A Feind is a creature that all it wants is to posses a Lockable object. */
public class Feind implements Runnable {
private final Creature creature;
private final Lockable target;
private final SecureRandom random;
private static final Logger LOGGER = LoggerFactory.getLogger(Feind.class.getName());
/**
* public constructor.
*
* @param feind as the creature to lock to he lockable.
* @param target as the target object.
*/
public Feind(@NonNull Creature feind, @NonNull Lockable target) {
this.creature = feind;
this.target = target;
this.random = new SecureRandom();
}
@Override
public void run() {
if (!creature.acquire(target)) {
try {
fightForTheSword(creature, target.getLocker(), target);
} catch (InterruptedException e) {
LOGGER.error(e.getMessage());
Thread.currentThread().interrupt();
}
} else {
LOGGER.info("{} has acquired the sword!", target.getLocker().getName());
}
}
/**
* Keeps on fighting until the Lockable is possessed.
*
* @param reacher as the source creature.
* @param holder as the foe.
* @param sword as the Lockable to posses.
* @throws InterruptedException in case of interruption.
*/
private void fightForTheSword(Creature reacher, @NonNull Creature holder, Lockable sword)
throws InterruptedException {
LOGGER.info("A duel between {} and {} has been started!", reacher.getName(), holder.getName());
boolean randBool;
while (this.target.isLocked() && reacher.isAlive() && holder.isAlive()) {
randBool = random.nextBoolean();
if (randBool) {
reacher.attack(holder);
} else {
holder.attack(reacher);
}
}
if (reacher.isAlive()) {
if (!reacher.acquire(sword)) {
fightForTheSword(reacher, sword.getLocker(), sword);
} else {
LOGGER.info("{} has acquired the sword!", reacher.getName());
}
}
}
}
| 3,456 | 35.010417 | 140 | java |
java-design-patterns | java-design-patterns-master/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reactor.app;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.iluwatar.reactor.framework.SameThreadDispatcher;
import com.iluwatar.reactor.framework.ThreadPoolDispatcher;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
/**
* This class tests the Distributed Logging service by starting a Reactor and then sending it
* concurrent logging requests using multiple clients.
*/
@Slf4j
class ReactorTest {
/**
* Test the application using pooled thread dispatcher.
*
* @throws IOException if any I/O error occurs.
* @throws InterruptedException if interrupted while stopping the application.
*/
@Test
void testAppUsingThreadPoolDispatcher() throws IOException, InterruptedException {
LOGGER.info("testAppUsingThreadPoolDispatcher start");
var app = new App(new ThreadPoolDispatcher(2));
app.start();
assertNotNull(app);
var client = new AppClient();
client.start();
assertNotNull(client);
// allow clients to send requests. Artificial delay.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
LOGGER.error("sleep interrupted", e);
}
client.stop();
app.stop();
LOGGER.info("testAppUsingThreadPoolDispatcher stop");
}
/**
* Test the application using same thread dispatcher.
*
* @throws IOException if any I/O error occurs.
* @throws InterruptedException if interrupted while stopping the application.
*/
@Test
void testAppUsingSameThreadDispatcher() throws IOException, InterruptedException {
LOGGER.info("testAppUsingSameThreadDispatcher start");
var app = new App(new SameThreadDispatcher());
app.start();
assertNotNull(app);
var client = new AppClient();
client.start();
assertNotNull(client);
// allow clients to send requests. Artificial delay.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
LOGGER.error("sleep interrupted", e);
}
client.stop();
app.stop();
LOGGER.info("testAppUsingSameThreadDispatcher stop");
}
}
| 3,437 | 31.433962 | 140 | java |
java-design-patterns | java-design-patterns-master/reactor/src/main/java/com/iluwatar/reactor/app/App.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reactor.app;
import com.iluwatar.reactor.framework.AbstractNioChannel;
import com.iluwatar.reactor.framework.ChannelHandler;
import com.iluwatar.reactor.framework.Dispatcher;
import com.iluwatar.reactor.framework.NioDatagramChannel;
import com.iluwatar.reactor.framework.NioReactor;
import com.iluwatar.reactor.framework.NioServerSocketChannel;
import com.iluwatar.reactor.framework.ThreadPoolDispatcher;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* This application demonstrates Reactor pattern. The example demonstrated is a Distributed Logging
* Service where it listens on multiple TCP or UDP sockets for incoming log requests.
*
* <p><i>INTENT</i> <br>
* The Reactor design pattern handles service requests that are delivered concurrently to an
* application by one or more clients. The application can register specific handlers for processing
* which are called by reactor on specific events.
*
* <p><i>PROBLEM</i> <br>
* Server applications in a distributed system must handle multiple clients that send them service
* requests. Following forces need to be resolved:
* <ul>
* <li>Availability</li>
* <li>Efficiency</li>
* <li>Programming Simplicity</li>
* <li>Adaptability</li>
* </ul>
*
* <p><i>PARTICIPANTS</i> <br>
* <ul>
* <li>Synchronous Event De-multiplexer
* <p>
* {@link NioReactor} plays the role of synchronous event de-multiplexer.
* It waits for events on multiple channels registered to it in an event loop.
* </p>
* </li>
* <li>Initiation Dispatcher
* <p>
* {@link NioReactor} plays this role as the application specific {@link ChannelHandler}s
* are registered to the reactor.
* </p>
* </li>
* <li>Handle
* <p>
* {@link AbstractNioChannel} acts as a handle that is registered to the reactor.
* When any events occur on a handle, reactor calls the appropriate handler.
* </p>
* </li>
* <li>Event Handler
* <p>
* {@link ChannelHandler} acts as an event handler, which is bound to a
* channel and is called back when any event occurs on any of its associated handles. Application
* logic resides in event handlers.
* </p>
* </li>
* </ul>
* The application utilizes single thread to listen for requests on all ports. It does not create a
* separate thread for each client, which provides better scalability under load (number of clients
* increase).
* The example uses Java NIO framework to implement the Reactor.
*/
public class App {
private NioReactor reactor;
private final List<AbstractNioChannel> channels = new ArrayList<>();
private final Dispatcher dispatcher;
/**
* Creates an instance of App which will use provided dispatcher for dispatching events on
* reactor.
*
* @param dispatcher the dispatcher that will be used to dispatch events.
*/
public App(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
/**
* App entry.
*/
public static void main(String[] args) throws IOException {
new App(new ThreadPoolDispatcher(2)).start();
}
/**
* Starts the NIO reactor.
*
* @throws IOException if any channel fails to bind.
*/
public void start() throws IOException {
/*
* The application can customize its event dispatching mechanism.
*/
reactor = new NioReactor(dispatcher);
/*
* This represents application specific business logic that dispatcher will call on appropriate
* events. These events are read events in our example.
*/
var loggingHandler = new LoggingHandler();
/*
* Our application binds to multiple channels and uses same logging handler to handle incoming
* log requests.
*/
reactor
.registerChannel(tcpChannel(16666, loggingHandler))
.registerChannel(tcpChannel(16667, loggingHandler))
.registerChannel(udpChannel(16668, loggingHandler))
.registerChannel(udpChannel(16669, loggingHandler))
.start();
}
/**
* Stops the NIO reactor. This is a blocking call.
*
* @throws InterruptedException if interrupted while stopping the reactor.
* @throws IOException if any I/O error occurs
*/
public void stop() throws InterruptedException, IOException {
reactor.stop();
dispatcher.stop();
for (var channel : channels) {
channel.getJavaChannel().close();
}
}
private AbstractNioChannel tcpChannel(int port, ChannelHandler handler) throws IOException {
var channel = new NioServerSocketChannel(port, handler);
channel.bind();
channels.add(channel);
return channel;
}
private AbstractNioChannel udpChannel(int port, ChannelHandler handler) throws IOException {
var channel = new NioDatagramChannel(port, handler);
channel.bind();
channels.add(channel);
return channel;
}
}
| 6,090 | 34.829412 | 140 | java |
java-design-patterns | java-design-patterns-master/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reactor.app;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
/**
* Represents the clients of Reactor pattern. Multiple clients are run concurrently and send logging
* requests to Reactor.
*/
@Slf4j
public class AppClient {
private final ExecutorService service = Executors.newFixedThreadPool(4);
/**
* App client entry.
*
* @throws IOException if any I/O error occurs.
*/
public static void main(String[] args) throws IOException {
var appClient = new AppClient();
appClient.start();
}
/**
* Starts the logging clients.
*
* @throws IOException if any I/O error occurs.
*/
public void start() throws IOException {
LOGGER.info("Starting logging clients");
service.execute(new TcpLoggingClient("Client 1", 16666));
service.execute(new TcpLoggingClient("Client 2", 16667));
service.execute(new UdpLoggingClient("Client 3", 16668));
service.execute(new UdpLoggingClient("Client 4", 16669));
}
/**
* Stops logging clients. This is a blocking call.
*/
public void stop() {
service.shutdown();
if (!service.isTerminated()) {
service.shutdownNow();
try {
service.awaitTermination(1000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.error("exception awaiting termination", e);
}
}
LOGGER.info("Logging clients stopped");
}
private static void artificialDelayOf(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
LOGGER.error("sleep interrupted", e);
}
}
/**
* A logging client that sends requests to Reactor on TCP socket.
*/
static class TcpLoggingClient implements Runnable {
private final int serverPort;
private final String clientName;
/**
* Creates a new TCP logging client.
*
* @param clientName the name of the client to be sent in logging requests.
* @param serverPort the port on which client will send logging requests.
*/
public TcpLoggingClient(String clientName, int serverPort) {
this.clientName = clientName;
this.serverPort = serverPort;
}
@Override
public void run() {
try (var socket = new Socket(InetAddress.getLocalHost(), serverPort)) {
var outputStream = socket.getOutputStream();
var writer = new PrintWriter(outputStream);
sendLogRequests(writer, socket.getInputStream());
} catch (IOException e) {
LOGGER.error("error sending requests", e);
throw new RuntimeException(e);
}
}
private void sendLogRequests(PrintWriter writer, InputStream inputStream) throws IOException {
for (var i = 0; i < 4; i++) {
writer.println(clientName + " - Log request: " + i);
writer.flush();
var data = new byte[1024];
var read = inputStream.read(data, 0, data.length);
if (read == 0) {
LOGGER.info("Read zero bytes");
} else {
LOGGER.info(new String(data, 0, read));
}
artificialDelayOf(100);
}
}
}
/**
* A logging client that sends requests to Reactor on UDP socket.
*/
static class UdpLoggingClient implements Runnable {
private final String clientName;
private final InetSocketAddress remoteAddress;
/**
* Creates a new UDP logging client.
*
* @param clientName the name of the client to be sent in logging requests.
* @param port the port on which client will send logging requests.
* @throws UnknownHostException if localhost is unknown
*/
public UdpLoggingClient(String clientName, int port) throws UnknownHostException {
this.clientName = clientName;
this.remoteAddress = new InetSocketAddress(InetAddress.getLocalHost(), port);
}
@Override
public void run() {
try (var socket = new DatagramSocket()) {
for (var i = 0; i < 4; i++) {
var message = clientName + " - Log request: " + i;
var bytes = message.getBytes();
var request = new DatagramPacket(bytes, bytes.length, remoteAddress);
socket.send(request);
var data = new byte[1024];
var reply = new DatagramPacket(data, data.length);
socket.receive(reply);
if (reply.getLength() == 0) {
LOGGER.info("Read zero bytes");
} else {
LOGGER.info(new String(reply.getData(), 0, reply.getLength()));
}
artificialDelayOf(100);
}
} catch (IOException e1) {
LOGGER.error("error sending packets", e1);
}
}
}
}
| 6,279 | 31.371134 | 140 | java |
java-design-patterns | java-design-patterns-master/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reactor.app;
import com.iluwatar.reactor.framework.AbstractNioChannel;
import com.iluwatar.reactor.framework.ChannelHandler;
import com.iluwatar.reactor.framework.NioDatagramChannel.DatagramPacket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import lombok.extern.slf4j.Slf4j;
/**
* Logging server application logic. It logs the incoming requests on standard console and returns a
* canned acknowledgement back to the remote peer.
*/
@Slf4j
public class LoggingHandler implements ChannelHandler {
private static final byte[] ACK = "Data logged successfully".getBytes();
/**
* Decodes the received data and logs it on standard console.
*/
@Override
public void handleChannelRead(AbstractNioChannel channel, Object readObject, SelectionKey key) {
/*
* As this handler is attached with both TCP and UDP channels we need to check whether the data
* received is a ByteBuffer (from TCP channel) or a DatagramPacket (from UDP channel).
*/
if (readObject instanceof ByteBuffer) {
doLogging((ByteBuffer) readObject);
sendReply(channel, key);
} else if (readObject instanceof DatagramPacket) {
var datagram = (DatagramPacket) readObject;
doLogging(datagram.getData());
sendReply(channel, datagram, key);
} else {
throw new IllegalStateException("Unknown data received");
}
}
private static void sendReply(
AbstractNioChannel channel,
DatagramPacket incomingPacket,
SelectionKey key
) {
/*
* Create a reply acknowledgement datagram packet setting the receiver to the sender of incoming
* message.
*/
var replyPacket = new DatagramPacket(ByteBuffer.wrap(ACK));
replyPacket.setReceiver(incomingPacket.getSender());
channel.write(replyPacket, key);
}
private static void sendReply(AbstractNioChannel channel, SelectionKey key) {
var buffer = ByteBuffer.wrap(ACK);
channel.write(buffer, key);
}
private static void doLogging(ByteBuffer data) {
// assuming UTF-8 :(
LOGGER.info(new String(data.array(), 0, data.limit()));
}
}
| 3,414 | 37.370787 | 140 | java |
java-design-patterns | java-design-patterns-master/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reactor.framework;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
/**
* This class acts as Synchronous Event De-multiplexer and Initiation Dispatcher of Reactor pattern.
* Multiple handles i.e. {@link AbstractNioChannel}s can be registered to the reactor and it blocks
* for events from all these handles. Whenever an event occurs on any of the registered handles, it
* synchronously de-multiplexes the event which can be any of read, write or accept, and dispatches
* the event to the appropriate {@link ChannelHandler} using the {@link Dispatcher}.
*
* <p>Implementation: A NIO reactor runs in its own thread when it is started using {@link
* #start()} method. {@link NioReactor} uses {@link Selector} for realizing Synchronous Event
* De-multiplexing.
*
* <p>NOTE: This is one of the ways to implement NIO reactor and it does not take care of all
* possible edge cases which are required in a real application. This implementation is meant to
* demonstrate the fundamental concepts that lie behind Reactor pattern.
*/
@Slf4j
public class NioReactor {
private final Selector selector;
private final Dispatcher dispatcher;
/**
* All the work of altering the SelectionKey operations and Selector operations are performed in
* the context of main event loop of reactor. So when any channel needs to change its readability
* or writability, a new command is added in the command queue and then the event loop picks up
* the command and executes it in next iteration.
*/
private final Queue<Runnable> pendingCommands = new ConcurrentLinkedQueue<>();
private final ExecutorService reactorMain = Executors.newSingleThreadExecutor();
/**
* Creates a reactor which will use provided {@code dispatcher} to dispatch events. The
* application can provide various implementations of dispatcher which suits its needs.
*
* @param dispatcher a non-null dispatcher used to dispatch events on registered channels.
* @throws IOException if any I/O error occurs.
*/
public NioReactor(Dispatcher dispatcher) throws IOException {
this.dispatcher = dispatcher;
this.selector = Selector.open();
}
/**
* Starts the reactor event loop in a new thread.
*/
public void start() {
reactorMain.execute(() -> {
try {
LOGGER.info("Reactor started, waiting for events...");
eventLoop();
} catch (IOException e) {
LOGGER.error("exception in event loop", e);
}
});
}
/**
* Stops the reactor and related resources such as dispatcher.
*
* @throws InterruptedException if interrupted while stopping the reactor.
* @throws IOException if any I/O error occurs.
*/
public void stop() throws InterruptedException, IOException {
reactorMain.shutdown();
selector.wakeup();
if (!reactorMain.awaitTermination(4, TimeUnit.SECONDS)) {
reactorMain.shutdownNow();
}
selector.close();
LOGGER.info("Reactor stopped");
}
/**
* Registers a new channel (handle) with this reactor. Reactor will start waiting for events on
* this channel and notify of any events. While registering the channel the reactor uses {@link
* AbstractNioChannel#getInterestedOps()} to know about the interested operation of this channel.
*
* @param channel a new channel on which reactor will wait for events. The channel must be bound
* prior to being registered.
* @return this
* @throws IOException if any I/O error occurs.
*/
public NioReactor registerChannel(AbstractNioChannel channel) throws IOException {
var key = channel.getJavaChannel().register(selector, channel.getInterestedOps());
key.attach(channel);
channel.setReactor(this);
return this;
}
private void eventLoop() throws IOException {
// honor interrupt request
while (!Thread.interrupted()) {
// honor any pending commands first
processPendingCommands();
/*
* Synchronous event de-multiplexing happens here, this is blocking call which returns when it
* is possible to initiate non-blocking operation on any of the registered channels.
*/
selector.select();
/*
* Represents the events that have occurred on registered handles.
*/
var keys = selector.selectedKeys();
var iterator = keys.iterator();
while (iterator.hasNext()) {
var key = iterator.next();
if (!key.isValid()) {
iterator.remove();
continue;
}
processKey(key);
}
keys.clear();
}
}
private void processPendingCommands() {
var iterator = pendingCommands.iterator();
while (iterator.hasNext()) {
var command = iterator.next();
command.run();
iterator.remove();
}
}
/*
* Initiation dispatcher logic, it checks the type of event and notifier application specific
* event handler to handle the event.
*/
private void processKey(SelectionKey key) throws IOException {
if (key.isAcceptable()) {
onChannelAcceptable(key);
} else if (key.isReadable()) {
onChannelReadable(key);
} else if (key.isWritable()) {
onChannelWritable(key);
}
}
private static void onChannelWritable(SelectionKey key) throws IOException {
var channel = (AbstractNioChannel) key.attachment();
channel.flush(key);
}
private void onChannelReadable(SelectionKey key) {
try {
// reads the incoming data in context of reactor main loop. Can this be improved?
var readObject = ((AbstractNioChannel) key.attachment()).read(key);
dispatchReadEvent(key, readObject);
} catch (IOException e) {
try {
key.channel().close();
} catch (IOException e1) {
LOGGER.error("error closing channel", e1);
}
}
}
/*
* Uses the application provided dispatcher to dispatch events to application handler.
*/
private void dispatchReadEvent(SelectionKey key, Object readObject) {
dispatcher.onChannelReadEvent((AbstractNioChannel) key.attachment(), readObject, key);
}
private void onChannelAcceptable(SelectionKey key) throws IOException {
var serverSocketChannel = (ServerSocketChannel) key.channel();
var socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
var readKey = socketChannel.register(selector, SelectionKey.OP_READ);
readKey.attach(key.attachment());
}
/**
* Queues the change of operations request of a channel, which will change the interested
* operations of the channel sometime in future.
*
* <p>This is a non-blocking method and does not guarantee that the operations have changed when
* this method returns.
*
* @param key the key for which operations have to be changed.
* @param interestedOps the new interest operations.
*/
public void changeOps(SelectionKey key, int interestedOps) {
pendingCommands.add(new ChangeKeyOpsCommand(key, interestedOps));
selector.wakeup();
}
/**
* A command that changes the interested operations of the key provided.
*/
class ChangeKeyOpsCommand implements Runnable {
private final SelectionKey key;
private final int interestedOps;
public ChangeKeyOpsCommand(SelectionKey key, int interestedOps) {
this.key = key;
this.interestedOps = interestedOps;
}
public void run() {
key.interestOps(interestedOps);
}
@Override
public String toString() {
return "Change of ops to: " + interestedOps;
}
}
}
| 9,178 | 35.716 | 140 | java |
java-design-patterns | java-design-patterns-master/reactor/src/main/java/com/iluwatar/reactor/framework/SameThreadDispatcher.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reactor.framework;
import java.nio.channels.SelectionKey;
/**
* Dispatches the events in the context of caller thread. This implementation is a good fit for
* small applications where there are limited clients. Using this implementation limits the
* scalability because the I/O thread performs the application specific processing.
*
* <p>For better performance use {@link ThreadPoolDispatcher}.
*
* @see ThreadPoolDispatcher
*/
public class SameThreadDispatcher implements Dispatcher {
/**
* Dispatches the read event in the context of caller thread. <br> Note this is a blocking call.
* It returns only after the associated handler has handled the read event.
*/
@Override
public void onChannelReadEvent(AbstractNioChannel channel, Object readObject, SelectionKey key) {
/*
* Calls the associated handler to notify the read event where application specific code
* resides.
*/
channel.getHandler().handleChannelRead(channel, readObject, key);
}
/**
* No resources to free.
*/
@Override
public void stop() {
// no-op
}
}
| 2,395 | 38.278689 | 140 | java |
java-design-patterns | java-design-patterns-master/reactor/src/main/java/com/iluwatar/reactor/framework/Dispatcher.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reactor.framework;
import java.nio.channels.SelectionKey;
/**
* Represents the event dispatching strategy. When {@link NioReactor} senses any event on the
* registered {@link AbstractNioChannel}s then it de-multiplexes the event type, read or write or
* connect, and then calls the {@link Dispatcher} to dispatch the read events. This decouples the
* I/O processing from application specific processing. <br> Dispatcher should call the {@link
* ChannelHandler} associated with the channel on which event occurred.
*
* <p>The application can customize the way in which event is dispatched such as using the reactor
* thread to dispatch event to channels or use a worker pool to do the non I/O processing.
*
* @see SameThreadDispatcher
* @see ThreadPoolDispatcher
*/
public interface Dispatcher {
/**
* This hook method is called when read event occurs on particular channel. The data read is
* provided in <code>readObject</code>. The implementation should dispatch this read event to the
* associated {@link ChannelHandler} of <code>channel</code>.
*
* <p>The type of <code>readObject</code> depends on the channel on which data was received.
*
* @param channel on which read event occurred
* @param readObject object read by channel
* @param key on which event occurred
*/
void onChannelReadEvent(AbstractNioChannel channel, Object readObject, SelectionKey key);
/**
* Stops dispatching events and cleans up any acquired resources such as threads.
*
* @throws InterruptedException if interrupted while stopping dispatcher.
*/
void stop() throws InterruptedException;
}
| 2,950 | 45.84127 | 140 | java |
java-design-patterns | java-design-patterns-master/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reactor.framework;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import lombok.extern.slf4j.Slf4j;
/**
* A wrapper over {@link NioServerSocketChannel} which can read and write data on a {@link
* SocketChannel}.
*/
@Slf4j
public class NioServerSocketChannel extends AbstractNioChannel {
private final int port;
/**
* Creates a {@link ServerSocketChannel} which will bind at provided port and use
* <code>handler</code> to handle incoming events on this channel.
*
* <p>Note the constructor does not bind the socket, {@link #bind()} method should be called for
* binding the socket.
*
* @param port the port on which channel will be bound to accept incoming connection requests.
* @param handler the handler that will handle incoming requests on this channel.
* @throws IOException if any I/O error occurs.
*/
public NioServerSocketChannel(int port, ChannelHandler handler) throws IOException {
super(handler, ServerSocketChannel.open());
this.port = port;
}
@Override
public int getInterestedOps() {
// being a server socket channel it is interested in accepting connection from remote peers.
return SelectionKey.OP_ACCEPT;
}
/**
* Get server socket channel.
*
* @return the underlying {@link ServerSocketChannel}.
*/
@Override
public ServerSocketChannel getJavaChannel() {
return (ServerSocketChannel) super.getJavaChannel();
}
/**
* Reads and returns {@link ByteBuffer} from the underlying {@link SocketChannel} represented by
* the <code>key</code>. Due to the fact that there is a dedicated channel for each client
* connection we don't need to store the sender.
*/
@Override
public ByteBuffer read(SelectionKey key) throws IOException {
var socketChannel = (SocketChannel) key.channel();
var buffer = ByteBuffer.allocate(1024);
var read = socketChannel.read(buffer);
buffer.flip();
if (read == -1) {
throw new IOException("Socket closed");
}
return buffer;
}
/**
* Binds TCP socket on the provided <code>port</code>.
*
* @throws IOException if any I/O error occurs.
*/
@Override
public void bind() throws IOException {
var javaChannel = getJavaChannel();
javaChannel.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
javaChannel.configureBlocking(false);
LOGGER.info("Bound TCP socket at port: {}", port);
}
/**
* Writes the pending {@link ByteBuffer} to the underlying channel sending data to the intended
* receiver of the packet.
*/
@Override
protected void doWrite(Object pendingWrite, SelectionKey key) throws IOException {
var pendingBuffer = (ByteBuffer) pendingWrite;
((SocketChannel) key.channel()).write(pendingBuffer);
}
}
| 4,279 | 35.271186 | 140 | java |
java-design-patterns | java-design-patterns-master/reactor/src/main/java/com/iluwatar/reactor/framework/ChannelHandler.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reactor.framework;
import java.nio.channels.SelectionKey;
/**
* Represents the <i>EventHandler</i> of Reactor pattern. It handles the incoming events dispatched
* to it by the {@link Dispatcher}. This is where the application logic resides.
*
* <p>A {@link ChannelHandler} can be associated with one or many {@link AbstractNioChannel}s, and
* whenever an event occurs on any of the associated channels, the handler is notified of the
* event.
*/
public interface ChannelHandler {
/**
* Called when the {@code channel} receives some data from remote peer.
*
* @param channel the channel from which the data was received.
* @param readObject the data read.
* @param key the key on which read event occurred.
*/
void handleChannelRead(AbstractNioChannel channel, Object readObject, SelectionKey key);
}
| 2,147 | 43.75 | 140 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.