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/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; import com.iluwatar.poison.pill.Message.Headers; import lombok.extern.slf4j.Slf4j; /** * Class responsible for receiving and handling submitted to the queue messages. */ @Slf4j public class Consumer { private final MqSubscribePoint queue; private final String name; public Consumer(String name, MqSubscribePoint queue) { this.name = name; this.queue = queue; } /** * Consume message. */ public void consume() { while (true) { try { var msg = queue.take(); if (Message.POISON_PILL.equals(msg)) { LOGGER.info("Consumer {} receive request to terminate.", name); break; } var sender = msg.getHeader(Headers.SENDER); var body = msg.getBody(); LOGGER.info("Message [{}] from [{}] received by [{}]", body, sender, name); } catch (InterruptedException e) { // allow thread to exit LOGGER.error("Exception caught.", e); return; } } } }
2,298
33.833333
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/main/java/com/iluwatar/poison/pill/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.poison.pill; import java.util.Map; /** * Interface that implements the Message pattern and represents an inbound or outbound message as * part of an {@link Producer}-{@link Consumer} exchange. */ public interface Message { Message POISON_PILL = new Message() { @Override public void addHeader(Headers header, String value) { throw poison(); } @Override public String getHeader(Headers header) { throw poison(); } @Override public Map<Headers, String> getHeaders() { throw poison(); } @Override public void setBody(String body) { throw poison(); } @Override public String getBody() { throw poison(); } private RuntimeException poison() { return new UnsupportedOperationException("Poison"); } }; /** * Enumeration of Type of Headers. */ enum Headers { DATE, SENDER } void addHeader(Headers header, String value); String getHeader(Headers header); Map<Headers, String> getHeaders(); void setBody(String body); String getBody(); }
2,385
27.070588
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; /** * Represents abstraction of channel (or pipe) that bounds {@link Producer} and {@link Consumer}. */ public interface MessageQueue extends MqPublishPoint, MqSubscribePoint { }
1,501
44.515152
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * Bounded blocking queue wrapper. */ public class SimpleMessageQueue implements MessageQueue { private final BlockingQueue<Message> queue; public SimpleMessageQueue(int bound) { queue = new ArrayBlockingQueue<>(bound); } @Override public void put(Message msg) throws InterruptedException { queue.put(msg); } @Override public Message take() throws InterruptedException { return queue.take(); } }
1,846
35.215686
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker; import static com.iluwatar.masterworker.ArrayUtilityMethods.matricesSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Random; import org.junit.jupiter.api.Test; /** * Testing divideData method in {@link ArrayInput} class. */ class ArrayInputTest { @Test void divideDataTest() { var rows = 10; var columns = 10; var inputMatrix = new int[rows][columns]; var rand = new Random(); for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { inputMatrix[i][j] = rand.nextInt(10); } } var i = new ArrayInput(inputMatrix); var table = i.divideData(4); var division1 = new int[][]{inputMatrix[0], inputMatrix[1], inputMatrix[2]}; var division2 = new int[][]{inputMatrix[3], inputMatrix[4], inputMatrix[5]}; var division3 = new int[][]{inputMatrix[6], inputMatrix[7]}; var division4 = new int[][]{inputMatrix[8], inputMatrix[9]}; assertTrue(matricesSame(table.get(0).data, division1) && matricesSame(table.get(1).data, division2) && matricesSame(table.get(2).data, division3) && matricesSame(table.get(3).data, division4)); } }
2,490
38.539683
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Testing utility methods in {@link ArrayUtilityMethods} class. */ class ArrayUtilityMethodsTest { @Test void arraysSameTest() { var arr1 = new int[]{1, 4, 2, 6}; var arr2 = new int[]{1, 4, 2, 6}; assertTrue(ArrayUtilityMethods.arraysSame(arr1, arr2)); } @Test void matricesSameTest() { var matrix1 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}}; var matrix2 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}}; assertTrue(ArrayUtilityMethods.matricesSame(matrix1, matrix2)); } }
1,927
36.076923
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker.system; import static org.junit.jupiter.api.Assertions.assertTrue; import com.iluwatar.masterworker.ArrayInput; import com.iluwatar.masterworker.ArrayResult; import com.iluwatar.masterworker.ArrayUtilityMethods; import org.junit.jupiter.api.Test; /** * Testing getResult method in {@link ArrayTransposeMasterWorker} class. */ class ArrayTransposeMasterWorkerTest { @Test void getResultTest() { var atmw = new ArrayTransposeMasterWorker(); var matrix = new int[][]{ {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5} }; var matrixTranspose = new int[][]{ {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5} }; var i = new ArrayInput(matrix); var r = (ArrayResult) atmw.getResult(i); assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose)); } }
2,265
35.548387
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker.system.systemworkers; import static org.junit.jupiter.api.Assertions.assertTrue; import com.iluwatar.masterworker.ArrayInput; import com.iluwatar.masterworker.ArrayUtilityMethods; import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster; import org.junit.jupiter.api.Test; /** * Testing executeOperation method in {@link ArrayTransposeWorker} class. */ class ArrayTransposeWorkerTest { @Test void executeOperationTest() { var atm = new ArrayTransposeMaster(1); var atw = new ArrayTransposeWorker(atm, 1); var matrix = new int[][]{{2, 4}, {3, 5}}; var matrixTranspose = new int[][]{{2, 3}, {4, 5}}; var i = new ArrayInput(matrix); atw.setReceivedData(atm, i); var r = atw.executeOperation(); assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose)); } }
2,147
39.528302
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker; /** * The abstract Result class, which contains 1 public field containing result data. * * @param <T> T will be type of data. */ public abstract class Result<T> { public final T data; public Result(T data) { this.data = data; } }
1,567
37.243902
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/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.masterworker; import com.iluwatar.masterworker.system.ArrayTransposeMasterWorker; import com.iluwatar.masterworker.system.MasterWorker; import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster; import com.iluwatar.masterworker.system.systemmaster.Master; import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker; import com.iluwatar.masterworker.system.systemworkers.Worker; import lombok.extern.slf4j.Slf4j; /** * <p>The <b><em>Master-Worker</em></b> pattern is used when the problem at hand can be solved by * dividing into multiple parts which need to go through the same computation and may need to be * aggregated to get final result. Parallel processing is performed using a system consisting of a * master and some number of workers, where a master divides the work among the workers, gets the * result back from them and assimilates all the results to give final result. The only * communication is between the master and the worker - none of the workers communicate among one * another and the user only communicates with the master to get required job done.</p> * <p>In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and * {@link Worker} which have to be extended by the classes which will perform the specific job at * hand (in this case finding transpose of matrix, done by {@link ArrayTransposeMasterWorker}, * {@link ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work * into parts to be given to the workers, collects the results from the workers and aggregates it * when all workers have responded before returning the solution. The Worker class extends the * Thread class to enable parallel processing, and does the work once the data has been received * from the Master. The MasterWorker contains a reference to the Master class, gets the input from * the App and passes it on to the Master. These 3 classes define the system which computes the * result. We also have 2 abstract classes {@link Input} and {@link Result}, which contain the input * data and result data respectively. The Input class also has an abstract method divideData which * defines how the data is to be divided into segments. These classes are extended by {@link * ArrayInput} and {@link ArrayResult}.</p> */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var mw = new ArrayTransposeMasterWorker(); var rows = 10; var columns = 20; var inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns); var input = new ArrayInput(inputMatrix); var result = (ArrayResult) mw.getResult(input); if (result != null) { ArrayUtilityMethods.printMatrix(inputMatrix); ArrayUtilityMethods.printMatrix(result.data); } else { LOGGER.info("Please enter non-zero input"); } } }
4,258
50.313253
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Class ArrayInput extends abstract class {@link Input} and contains data of type int[][]. */ public class ArrayInput extends Input<int[][]> { public ArrayInput(int[][] data) { super(data); } static int[] makeDivisions(int[][] data, int num) { var initialDivision = data.length / num; //equally dividing var divisions = new int[num]; Arrays.fill(divisions, initialDivision); if (initialDivision * num != data.length) { var extra = data.length - initialDivision * num; var l = 0; //equally dividing extra among all parts while (extra > 0) { divisions[l] = divisions[l] + 1; extra--; if (l == num - 1) { l = 0; } else { l++; } } } return divisions; } @Override public List<Input<int[][]>> divideData(int num) { if (this.data == null) { return null; } else { var divisions = makeDivisions(this.data, num); var result = new ArrayList<Input<int[][]>>(num); var rowsDone = 0; //number of rows divided so far for (var i = 0; i < num; i++) { var rows = divisions[i]; if (rows != 0) { var divided = new int[rows][this.data[0].length]; System.arraycopy(this.data, rowsDone, divided, 0, rows); rowsDone += rows; var dividedInput = new ArrayInput(divided); result.add(dividedInput); } else { break; //rest of divisions will also be 0 } } return result; } } }
2,932
33.104651
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker; import java.util.List; /** * The abstract Input class, having 1 public field which contains input data, and abstract method * divideData. * * @param <T> T will be type of data. */ public abstract class Input<T> { public final T data; public Input(T data) { this.data = data; } public abstract List<Input<T>> divideData(int num); }
1,673
35.391304
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker; import java.security.SecureRandom; import lombok.extern.slf4j.Slf4j; /** * Class ArrayUtilityMethods has some utility methods for matrices and arrays. */ @Slf4j public class ArrayUtilityMethods { private static final SecureRandom RANDOM = new SecureRandom(); /** * Method arraysSame compares 2 arrays @param a1 and @param a2 and @return whether their values * are equal (boolean). */ public static boolean arraysSame(int[] a1, int[] a2) { //compares if 2 arrays have the same value if (a1.length != a2.length) { return false; } else { var answer = false; for (var i = 0; i < a1.length; i++) { if (a1[i] == a2[i]) { answer = true; } else { answer = false; break; } } return answer; } } /** * Method matricesSame compares 2 matrices @param m1 and @param m2 and @return whether their * values are equal (boolean). */ public static boolean matricesSame(int[][] m1, int[][] m2) { if (m1.length != m2.length) { return false; } else { var answer = false; for (var i = 0; i < m1.length; i++) { if (arraysSame(m1[i], m2[i])) { answer = true; } else { answer = false; break; } } return answer; } } /** * Method createRandomIntMatrix creates a random matrix of size @param rows and @param columns. * * @return it (int[][]). */ public static int[][] createRandomIntMatrix(int rows, int columns) { var matrix = new int[rows][columns]; for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { //filling cells in matrix matrix[i][j] = RANDOM.nextInt(10); } } return matrix; } /** * Method printMatrix prints input matrix @param matrix. */ public static void printMatrix(int[][] matrix) { //prints out int[][] for (var ints : matrix) { for (var j = 0; j < matrix[0].length; j++) { LOGGER.info(ints[j] + " "); } LOGGER.info(""); } } }
3,403
28.6
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker; /** * Class ArrayResult extends abstract class {@link Result} and contains data of type int[][]. */ public class ArrayResult extends Result<int[][]> { public ArrayResult(int[][] data) { super(data); } }
1,535
40.513514
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker.system; import com.iluwatar.masterworker.Input; import com.iluwatar.masterworker.Result; import com.iluwatar.masterworker.system.systemmaster.Master; /** * The abstract MasterWorker class which contains reference to master. */ public abstract class MasterWorker { private final Master master; public MasterWorker(int numOfWorkers) { this.master = setMaster(numOfWorkers); } abstract Master setMaster(int numOfWorkers); public Result<?> getResult(Input<?> input) { this.master.doWork(input); return this.master.getFinalResult(); } }
1,883
36.68
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker.system; import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster; import com.iluwatar.masterworker.system.systemmaster.Master; /** * Class ArrayTransposeMasterWorker extends abstract class {@link MasterWorker} and specifically * solves the problem of finding transpose of input array. */ public class ArrayTransposeMasterWorker extends MasterWorker { public ArrayTransposeMasterWorker() { super(4); } @Override Master setMaster(int numOfWorkers) { return new ArrayTransposeMaster(numOfWorkers); } }
1,860
39.456522
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker.system.systemmaster; import com.iluwatar.masterworker.ArrayResult; import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker; import com.iluwatar.masterworker.system.systemworkers.Worker; import java.util.ArrayList; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Class ArrayTransposeMaster extends abstract class {@link Master} and contains definition of * aggregateData, which will obtain final result from all data obtained and for setWorkers. */ public class ArrayTransposeMaster extends Master { public ArrayTransposeMaster(int numOfWorkers) { super(numOfWorkers); } @Override ArrayList<Worker> setWorkers(int num) { //i+1 will be id return IntStream.range(0, num) .mapToObj(i -> new ArrayTransposeWorker(this, i + 1)) .collect(Collectors.toCollection(() -> new ArrayList<>(num))); } @Override ArrayResult aggregateData() { // number of rows in final result is number of rows in any of obtained results from workers var allResultData = this.getAllResultData(); var rows = ((ArrayResult) allResultData.elements().nextElement()).data.length; var elements = allResultData.elements(); var columns = 0; // columns = sum of number of columns in all results obtained from workers while (elements.hasMoreElements()) { columns += ((ArrayResult) elements.nextElement()).data[0].length; } var resultData = new int[rows][columns]; var columnsDone = 0; //columns aggregated so far var workers = this.getWorkers(); for (var i = 0; i < this.getExpectedNumResults(); i++) { //result obtained from ith worker var worker = workers.get(i); var workerId = worker.getWorkerId(); var work = ((ArrayResult) allResultData.get(workerId)).data; for (var m = 0; m < work.length; m++) { //m = row number, n = columns number System.arraycopy(work[m], 0, resultData[m], columnsDone, work[0].length); } columnsDone += work[0].length; } return new ArrayResult(resultData); } }
3,383
41.3
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker.system.systemmaster; import com.iluwatar.masterworker.Input; import com.iluwatar.masterworker.Result; import com.iluwatar.masterworker.system.systemworkers.Worker; import java.util.Hashtable; import java.util.List; /** * The abstract Master class which contains private fields numOfWorkers (number of workers), workers * (arraylist of workers), expectedNumResults (number of divisions of input data, same as expected * number of results), allResultData (hashtable of results obtained from workers, mapped by their * ids) and finalResult (aggregated from allResultData). */ public abstract class Master { private final int numOfWorkers; private final List<Worker> workers; private final Hashtable<Integer, Result<?>> allResultData; private int expectedNumResults; private Result<?> finalResult; Master(int numOfWorkers) { this.numOfWorkers = numOfWorkers; this.workers = setWorkers(numOfWorkers); this.expectedNumResults = 0; this.allResultData = new Hashtable<>(numOfWorkers); this.finalResult = null; } public Result<?> getFinalResult() { return this.finalResult; } Hashtable<Integer, Result<?>> getAllResultData() { return this.allResultData; } int getExpectedNumResults() { return this.expectedNumResults; } List<Worker> getWorkers() { return this.workers; } abstract List<Worker> setWorkers(int num); public void doWork(Input<?> input) { divideWork(input); } private void divideWork(Input<?> input) { var dividedInput = input.divideData(numOfWorkers); if (dividedInput != null) { this.expectedNumResults = dividedInput.size(); for (var i = 0; i < this.expectedNumResults; i++) { //ith division given to ith worker in this.workers this.workers.get(i).setReceivedData(this, dividedInput.get(i)); this.workers.get(i).start(); } for (var i = 0; i < this.expectedNumResults; i++) { try { this.workers.get(i).join(); } catch (InterruptedException e) { System.err.println("Error while executing thread"); } } } } public void receiveData(Result<?> data, Worker w) { //check if can receive..if yes: collectResult(data, w.getWorkerId()); } private void collectResult(Result<?> data, int workerId) { this.allResultData.put(workerId, data); if (this.allResultData.size() == this.expectedNumResults) { //all data received this.finalResult = aggregateData(); } } abstract Result<?> aggregateData(); }
3,860
33.783784
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.masterworker.system.systemworkers; import com.iluwatar.masterworker.ArrayInput; import com.iluwatar.masterworker.ArrayResult; import com.iluwatar.masterworker.system.systemmaster.Master; /** * Class ArrayTransposeWorker extends abstract class {@link Worker} and defines method * executeOperation(), to be performed on data received from master. */ public class ArrayTransposeWorker extends Worker { public ArrayTransposeWorker(Master master, int id) { super(master, id); } @Override ArrayResult executeOperation() { //number of rows in result matrix is equal to number of columns in input matrix and vice versa var arrayInput = (ArrayInput) this.getReceivedData(); final var rows = arrayInput.data[0].length; final var cols = arrayInput.data.length; var resultData = new int[rows][cols]; for (var i = 0; i < cols; i++) { for (var j = 0; j < rows; j++) { //flipping element positions along diagonal resultData[j][i] = arrayInput.data[i][j]; } } return new ArrayResult(resultData); } }
2,371
39.896552
140
java
java-design-patterns
java-design-patterns-master/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/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.masterworker.system.systemworkers; import com.iluwatar.masterworker.Input; import com.iluwatar.masterworker.Result; import com.iluwatar.masterworker.system.systemmaster.Master; /** * The abstract Worker class which extends Thread class to enable parallel processing. Contains * fields master(holding reference to master), workerId (unique id) and receivedData(from master). */ public abstract class Worker extends Thread { private final Master master; private final int workerId; private Input<?> receivedData; Worker(Master master, int id) { this.master = master; this.workerId = id; this.receivedData = null; } public int getWorkerId() { return this.workerId; } Input<?> getReceivedData() { return this.receivedData; } public void setReceivedData(Master m, Input<?> i) { //check if ready to receive..if yes: this.receivedData = i; } abstract Result<?> executeOperation(); private void sendToMaster(Result<?> data) { this.master.receiveData(data, this); } public void run() { //from Thread class var work = executeOperation(); sendToMaster(work); } }
2,442
33.408451
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; /** * Date: 12/10/15 - 11:31 PM * * @author Jeroen Meulemeester */ class SpaceStationMirTest extends CollisionTest<SpaceStationMir> { @Override final SpaceStationMir getTestedObject() { return new SpaceStationMir(1, 2, 3, 4); } /** * Test the constructor parameters */ @Test void testConstructor() { final var mir = new SpaceStationMir(1, 2, 3, 4); assertEquals(1, mir.getLeft()); assertEquals(2, mir.getTop()); assertEquals(3, mir.getRight()); assertEquals(4, mir.getBottom()); assertFalse(mir.isOnFire()); assertFalse(mir.isDamaged()); assertEquals("SpaceStationMir at [1,2,3,4] damaged=false onFire=false", mir.toString()); } /** * Test what happens we collide with an asteroid */ @Test void testCollideFlamingAsteroid() { testCollision( new FlamingAsteroid(1, 1, 3, 4), false, true, false, false ); } /** * Test what happens we collide with an meteoroid */ @Test void testCollideMeteoroid() { testCollision( new Meteoroid(1, 1, 3, 4), false, false, false, false ); } /** * Test what happens we collide with ISS */ @Test void testCollideSpaceStationIss() { testCollision( new SpaceStationIss(1, 1, 3, 4), true, false, false, false ); } /** * Test what happens we collide with MIR */ @Test void testCollideSpaceStationMir() { testCollision( new SpaceStationMir(1, 1, 3, 4), true, false, false, false ); } }
3,039
27.411215
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Date: 12/10/15 - 11:31 PM * * @author Jeroen Meulemeester */ class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> { @Override final FlamingAsteroid getTestedObject() { return new FlamingAsteroid(1, 2, 3, 4); } /** * Test the constructor parameters */ @Test void testConstructor() { final var asteroid = new FlamingAsteroid(1, 2, 3, 4); assertEquals(1, asteroid.getLeft()); assertEquals(2, asteroid.getTop()); assertEquals(3, asteroid.getRight()); assertEquals(4, asteroid.getBottom()); assertTrue(asteroid.isOnFire()); assertFalse(asteroid.isDamaged()); assertEquals("FlamingAsteroid at [1,2,3,4] damaged=false onFire=true", asteroid.toString()); } /** * Test what happens we collide with an asteroid */ @Test void testCollideFlamingAsteroid() { testCollision( new FlamingAsteroid(1, 2, 3, 4), false, true, false, true ); } /** * Test what happens we collide with an meteoroid */ @Test void testCollideMeteoroid() { testCollision( new Meteoroid(1, 1, 3, 4), false, false, false, true ); } /** * Test what happens we collide with ISS */ @Test void testCollideSpaceStationIss() { testCollision( new SpaceStationIss(1, 1, 3, 4), true, true, false, true ); } /** * Test what happens we collide with MIR */ @Test void testCollideSpaceStationMir() { testCollision( new SpaceStationMir(1, 1, 3, 4), true, true, false, true ); } }
3,130
27.990741
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Unit test for Rectangle */ class RectangleTest { /** * Test if the values passed through the constructor matches the values fetched from the getters */ @Test void testConstructor() { final var rectangle = new Rectangle(1, 2, 3, 4); assertEquals(1, rectangle.getLeft()); assertEquals(2, rectangle.getTop()); assertEquals(3, rectangle.getRight()); assertEquals(4, rectangle.getBottom()); } /** * Test if the values passed through the constructor matches the values in the {@link * #toString()} */ @Test void testToString() throws Exception { final var rectangle = new Rectangle(1, 2, 3, 4); assertEquals("[1,2,3,4]", rectangle.toString()); } /** * Test if the {@link Rectangle} class can detect if it intersects with another rectangle. */ @Test void testIntersection() { assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(0, 0, 1, 1))); assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-1, -5, 7, 8))); assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(2, 2, 3, 3))); assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-2, -2, -1, -1))); } }
2,745
37.138889
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Objects; /** * Date: 12/10/15 - 8:37 PM Test for Collision * * @param <O> Type of GameObject * @author Jeroen Meulemeester */ public abstract class CollisionTest<O extends GameObject> { /** * Get the tested object * * @return The tested object, should never return 'null' */ abstract O getTestedObject(); /** * Collide the tested item with the other given item and verify if the damage and fire state is as * expected * * @param other The other object we have to collide with * @param otherDamaged Indicates if the other object should be damaged after the collision * @param otherOnFire Indicates if the other object should be burning after the collision * @param thisDamaged Indicates if the test object should be damaged after the collision * @param thisOnFire Indicates if the other object should be burning after the collision */ void testCollision(final GameObject other, final boolean otherDamaged, final boolean otherOnFire, final boolean thisDamaged, final boolean thisOnFire) { Objects.requireNonNull(other); Objects.requireNonNull(getTestedObject()); final var tested = getTestedObject(); tested.collision(other); testOnFire(other, tested, otherOnFire); testDamaged(other, tested, otherDamaged); testOnFire(tested, other, thisOnFire); testDamaged(tested, other, thisDamaged); } /** * Test if the fire state of the target matches the expected state after colliding with the given * object * * @param target The target object * @param other The other object * @param expectTargetOnFire The expected state of fire on the target object */ private void testOnFire(final GameObject target, final GameObject other, final boolean expectTargetOnFire) { final var targetName = target.getClass().getSimpleName(); final var otherName = other.getClass().getSimpleName(); final var errorMessage = expectTargetOnFire ? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!" : "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!"; assertEquals(expectTargetOnFire, target.isOnFire(), errorMessage); } /** * Test if the damage state of the target matches the expected state after colliding with the * given object * * @param target The target object * @param other The other object * @param expectedDamage The expected state of damage on the target object */ private void testDamaged(final GameObject target, final GameObject other, final boolean expectedDamage) { final var targetName = target.getClass().getSimpleName(); final var otherName = other.getClass().getSimpleName(); final var errorMessage = expectedDamage ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" : "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!"; assertEquals(expectedDamage, target.isDamaged(), errorMessage); } }
4,583
39.566372
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; /** * Date: 12/10/15 - 11:31 PM * * @author Jeroen Meulemeester */ class SpaceStationIssTest extends CollisionTest<SpaceStationIss> { @Override final SpaceStationIss getTestedObject() { return new SpaceStationIss(1, 2, 3, 4); } /** * Test the constructor parameters */ @Test void testConstructor() { final var iss = new SpaceStationIss(1, 2, 3, 4); assertEquals(1, iss.getLeft()); assertEquals(2, iss.getTop()); assertEquals(3, iss.getRight()); assertEquals(4, iss.getBottom()); assertFalse(iss.isOnFire()); assertFalse(iss.isDamaged()); assertEquals("SpaceStationIss at [1,2,3,4] damaged=false onFire=false", iss.toString()); } /** * Test what happens we collide with an asteroid */ @Test void testCollideFlamingAsteroid() { testCollision( new FlamingAsteroid(1, 1, 3, 4), false, true, false, false ); } /** * Test what happens we collide with an meteoroid */ @Test void testCollideMeteoroid() { testCollision( new Meteoroid(1, 1, 3, 4), false, false, false, false ); } /** * Test what happens we collide with ISS */ @Test void testCollideSpaceStationIss() { testCollision( new SpaceStationIss(1, 1, 3, 4), true, false, false, false ); } /** * Test what happens we collide with MIR */ @Test void testCollideSpaceStationMir() { testCollision( new SpaceStationMir(1, 1, 3, 4), true, false, false, false ); } }
3,039
27.411215
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; /** * Date: 12/10/15 - 11:31 PM * * @author Jeroen Meulemeester */ class MeteoroidTest extends CollisionTest<Meteoroid> { @Override final Meteoroid getTestedObject() { return new Meteoroid(1, 2, 3, 4); } /** * Test the constructor parameters */ @Test void testConstructor() { final var meteoroid = new Meteoroid(1, 2, 3, 4); assertEquals(1, meteoroid.getLeft()); assertEquals(2, meteoroid.getTop()); assertEquals(3, meteoroid.getRight()); assertEquals(4, meteoroid.getBottom()); assertFalse(meteoroid.isOnFire()); assertFalse(meteoroid.isDamaged()); assertEquals("Meteoroid at [1,2,3,4] damaged=false onFire=false", meteoroid.toString()); } /** * Test what happens we collide with an asteroid */ @Test void testCollideFlamingAsteroid() { testCollision( new FlamingAsteroid(1, 1, 3, 4), false, true, false, false ); } /** * Test what happens we collide with an meteoroid */ @Test void testCollideMeteoroid() { testCollision( new Meteoroid(1, 1, 3, 4), false, false, false, false ); } /** * Test what happens we collide with ISS */ @Test void testCollideSpaceStationIss() { testCollision( new SpaceStationIss(1, 1, 3, 4), true, false, false, false ); } /** * Test what happens we collide with MIR */ @Test void testCollideSpaceStationMir() { testCollision( new SpaceStationMir(1, 1, 3, 4), true, false, false, false ); } }
3,051
27.523364
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/test/java/com/iluwatar/doubledispatch/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.doubledispatch; 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,810
35.959184
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Rectangle has coordinates and can be checked for overlap against other Rectangles. */ @Getter @RequiredArgsConstructor public class Rectangle { private final int left; private final int top; private final int right; private final int bottom; boolean intersectsWith(Rectangle r) { return !(r.getLeft() > getRight() || r.getRight() < getLeft() || r.getTop() > getBottom() || r .getBottom() < getTop()); } @Override public String toString() { return String.format("[%d,%d,%d,%d]", getLeft(), getTop(), getRight(), getBottom()); } }
1,958
36.673077
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/main/java/com/iluwatar/doubledispatch/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.doubledispatch; import java.util.List; import lombok.extern.slf4j.Slf4j; /** * When a message with a parameter is sent to an object, the resultant behaviour is defined by the * implementation of that method in the receiver. Sometimes the behaviour must also be determined by * the type of the parameter. * * <p>One way to implement this would be to create multiple instanceof-checks for the methods * parameter. However, this creates a maintenance issue. When new types are added we would also need * to change the method's implementation and add a new instanceof-check. This violates the single * responsibility principle - a class should have only one reason to change. * * <p>Instead of the instanceof-checks a better way is to make another virtual call on the * parameter object. This way new functionality can be easily added without the need to modify * existing implementation (open-closed principle). * * <p>In this example we have hierarchy of objects ({@link GameObject}) that can collide to each * other. Each object has its own coordinates which are checked against the other objects' * coordinates. If there is an overlap, then the objects collide utilizing the Double Dispatch * pattern. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // initialize game objects and print their status var objects = List.of( new FlamingAsteroid(0, 0, 5, 5), new SpaceStationMir(1, 1, 2, 2), new Meteoroid(10, 10, 15, 15), new SpaceStationIss(12, 12, 14, 14) ); objects.forEach(o -> LOGGER.info(o.toString())); LOGGER.info(""); // collision check objects.forEach(o1 -> objects.forEach(o2 -> { if (o1 != o2 && o1.intersectsWith(o2)) { o1.collision(o2); } })); LOGGER.info(""); // output eventual object statuses objects.forEach(o -> LOGGER.info(o.toString())); LOGGER.info(""); } }
3,310
39.876543
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; /** * Game objects have coordinates and some other status information. */ public abstract class GameObject extends Rectangle { private boolean damaged; private boolean onFire; public GameObject(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @Override public String toString() { return String.format("%s at %s damaged=%b onFire=%b", this.getClass().getSimpleName(), super.toString(), isDamaged(), isOnFire()); } public boolean isOnFire() { return onFire; } public void setOnFire(boolean onFire) { this.onFire = onFire; } public boolean isDamaged() { return damaged; } public void setDamaged(boolean damaged) { this.damaged = damaged; } public abstract void collision(GameObject gameObject); public abstract void collisionResolve(FlamingAsteroid asteroid); public abstract void collisionResolve(Meteoroid meteoroid); public abstract void collisionResolve(SpaceStationMir mir); public abstract void collisionResolve(SpaceStationIss iss); }
2,377
32.492958
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; /** * Space station ISS game object. */ public class SpaceStationIss extends SpaceStationMir { public SpaceStationIss(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @Override public void collision(GameObject gameObject) { gameObject.collisionResolve(this); } }
1,637
38.95122
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; import com.iluwatar.doubledispatch.constants.AppConstants; import lombok.extern.slf4j.Slf4j; /** * Meteoroid game object. */ @Slf4j public class Meteoroid extends GameObject { public Meteoroid(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @Override public void collision(GameObject gameObject) { gameObject.collisionResolve(this); } @Override public void collisionResolve(FlamingAsteroid asteroid) { LOGGER.info(AppConstants.HITS, asteroid.getClass().getSimpleName(), this.getClass() .getSimpleName()); } @Override public void collisionResolve(Meteoroid meteoroid) { LOGGER.info(AppConstants.HITS, meteoroid.getClass().getSimpleName(), this.getClass() .getSimpleName()); } @Override public void collisionResolve(SpaceStationMir mir) { LOGGER.info(AppConstants.HITS, mir.getClass().getSimpleName(), this.getClass().getSimpleName()); } @Override public void collisionResolve(SpaceStationIss iss) { LOGGER.info(AppConstants.HITS, iss.getClass().getSimpleName(), this.getClass().getSimpleName()); } }
2,435
35.358209
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; import com.iluwatar.doubledispatch.constants.AppConstants; import lombok.extern.slf4j.Slf4j; /** * Space station Mir game object. */ @Slf4j public class SpaceStationMir extends GameObject { public SpaceStationMir(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @Override public void collision(GameObject gameObject) { gameObject.collisionResolve(this); } @Override public void collisionResolve(FlamingAsteroid asteroid) { LOGGER.info(AppConstants.HITS + " {} is damaged! {} is set on fire!", asteroid.getClass() .getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass() .getSimpleName()); setDamaged(true); setOnFire(true); } @Override public void collisionResolve(Meteoroid meteoroid) { LOGGER.info(AppConstants.HITS + " {} is damaged!", meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } @Override public void collisionResolve(SpaceStationMir mir) { LOGGER.info(AppConstants.HITS + " {} is damaged!", mir.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } @Override public void collisionResolve(SpaceStationIss iss) { LOGGER.info(AppConstants.HITS, " {} is damaged!", iss.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } }
2,867
36.736842
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch; /** * Flaming asteroid game object. */ public class FlamingAsteroid extends Meteoroid { public FlamingAsteroid(int left, int top, int right, int bottom) { super(left, top, right, bottom); setOnFire(true); } @Override public void collision(GameObject gameObject) { gameObject.collisionResolve(this); } }
1,651
38.333333
140
java
java-design-patterns
java-design-patterns-master/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.doubledispatch.constants; /** * Constants class to define all constants. */ public class AppConstants { public static final String HITS = "{} hits {}."; }
1,466
42.147059
140
java
java-design-patterns
java-design-patterns-master/layers/src/test/java/com/iluwatar/layers/entity/CakeTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.layers.entity; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashSet; import java.util.Set; import entity.Cake; import entity.CakeLayer; import entity.CakeTopping; import org.junit.jupiter.api.Test; /** * Date: 12/15/15 - 8:02 PM * * @author Jeroen Meulemeester */ class CakeTest { @Test void testSetId() { final var cake = new Cake(); assertNull(cake.getId()); final var expectedId = 1234L; cake.setId(expectedId); assertEquals(expectedId, cake.getId()); } @Test void testSetTopping() { final var cake = new Cake(); assertNull(cake.getTopping()); final var expectedTopping = new CakeTopping("DummyTopping", 1000); cake.setTopping(expectedTopping); assertEquals(expectedTopping, cake.getTopping()); } @Test void testSetLayers() { final var cake = new Cake(); assertNotNull(cake.getLayers()); assertTrue(cake.getLayers().isEmpty()); final var expectedLayers = Set.of( new CakeLayer("layer1", 1000), new CakeLayer("layer2", 2000), new CakeLayer("layer3", 3000)); cake.setLayers(expectedLayers); assertEquals(expectedLayers, cake.getLayers()); } @Test void testAddLayer() { final var cake = new Cake(); assertNotNull(cake.getLayers()); assertTrue(cake.getLayers().isEmpty()); final Set<CakeLayer> initialLayers = new HashSet<>(); initialLayers.add(new CakeLayer("layer1", 1000)); initialLayers.add(new CakeLayer("layer2", 2000)); cake.setLayers(initialLayers); assertEquals(initialLayers, cake.getLayers()); final var newLayer = new CakeLayer("layer3", 3000); cake.addLayer(newLayer); final Set<CakeLayer> expectedLayers = new HashSet<>(); expectedLayers.addAll(initialLayers); expectedLayers.addAll(initialLayers); expectedLayers.add(newLayer); assertEquals(expectedLayers, cake.getLayers()); } @Test void testToString() { final var topping = new CakeTopping("topping", 20); topping.setId(2345L); final var layer = new CakeLayer("layer", 100); layer.setId(3456L); final var cake = new Cake(); cake.setId(1234L); cake.setTopping(topping); cake.addLayer(layer); final var expected = "id=1234 topping=id=2345 name=topping calories=20 " + "layers=[id=3456 name=layer calories=100]"; assertEquals(expected, cake.toString()); } }
3,890
30.379032
140
java
java-design-patterns
java-design-patterns-master/layers/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.layers.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import com.iluwatar.layers.app.LayersApp; import dto.CakeInfo; import dto.CakeLayerInfo; import dto.CakeToppingInfo; import exception.CakeBakingException; import org.junit.jupiter.api.BeforeEach; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import service.CakeBakingServiceImpl; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; /** * Date: 12/15/15 - 9:55 PM * * @author Jeroen Meulemeester */ @SpringBootTest(classes = LayersApp.class) class CakeBakingServiceImplTest { private final CakeBakingServiceImpl cakeBakingService; @Autowired CakeBakingServiceImplTest(CakeBakingServiceImpl cakeBakingService) { this.cakeBakingService = cakeBakingService; } @BeforeEach void setUp() { cakeBakingService.deleteAllCakes(); cakeBakingService.deleteAllLayers(); cakeBakingService.deleteAllToppings(); } @Test void testLayers() { final var initialLayers = cakeBakingService.getAvailableLayers(); assertNotNull(initialLayers); assertTrue(initialLayers.isEmpty()); cakeBakingService.saveNewLayer(new CakeLayerInfo("Layer1", 1000)); cakeBakingService.saveNewLayer(new CakeLayerInfo("Layer2", 2000)); final var availableLayers = cakeBakingService.getAvailableLayers(); assertNotNull(availableLayers); assertEquals(2, availableLayers.size()); for (final var layer : availableLayers) { assertNotNull(layer.id); assertNotNull(layer.name); assertNotNull(layer.toString()); assertTrue(layer.calories > 0); } } @Test void testToppings() { final var initialToppings = cakeBakingService.getAvailableToppings(); assertNotNull(initialToppings); assertTrue(initialToppings.isEmpty()); cakeBakingService.saveNewTopping(new CakeToppingInfo("Topping1", 1000)); cakeBakingService.saveNewTopping(new CakeToppingInfo("Topping2", 2000)); final var availableToppings = cakeBakingService.getAvailableToppings(); assertNotNull(availableToppings); assertEquals(2, availableToppings.size()); for (final var topping : availableToppings) { assertNotNull(topping.id); assertNotNull(topping.name); assertNotNull(topping.toString()); assertTrue(topping.calories > 0); } } @Test void testBakeCakes() throws CakeBakingException { final var initialCakes = cakeBakingService.getAllCakes(); assertNotNull(initialCakes); assertTrue(initialCakes.isEmpty()); final var topping1 = new CakeToppingInfo("Topping1", 1000); final var topping2 = new CakeToppingInfo("Topping2", 2000); cakeBakingService.saveNewTopping(topping1); cakeBakingService.saveNewTopping(topping2); final var layer1 = new CakeLayerInfo("Layer1", 1000); final var layer2 = new CakeLayerInfo("Layer2", 2000); final var layer3 = new CakeLayerInfo("Layer3", 2000); cakeBakingService.saveNewLayer(layer1); cakeBakingService.saveNewLayer(layer2); cakeBakingService.saveNewLayer(layer3); cakeBakingService.bakeNewCake(new CakeInfo(topping1, List.of(layer1, layer2))); cakeBakingService.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer3))); final var allCakes = cakeBakingService.getAllCakes(); assertNotNull(allCakes); assertEquals(2, allCakes.size()); for (final var cakeInfo : allCakes) { assertNotNull(cakeInfo.id); assertNotNull(cakeInfo.cakeToppingInfo); assertNotNull(cakeInfo.cakeLayerInfos); assertNotNull(cakeInfo.toString()); assertFalse(cakeInfo.cakeLayerInfos.isEmpty()); assertTrue(cakeInfo.calculateTotalCalories() > 0); } } @Test void testBakeCakeMissingTopping() { final var layer1 = new CakeLayerInfo("Layer1", 1000); final var layer2 = new CakeLayerInfo("Layer2", 2000); cakeBakingService.saveNewLayer(layer1); cakeBakingService.saveNewLayer(layer2); final var missingTopping = new CakeToppingInfo("Topping1", 1000); assertThrows(CakeBakingException.class, () -> cakeBakingService.bakeNewCake(new CakeInfo(missingTopping, List.of(layer1, layer2)))); } @Test void testBakeCakeMissingLayer() { final var initialCakes = cakeBakingService.getAllCakes(); assertNotNull(initialCakes); assertTrue(initialCakes.isEmpty()); final var topping1 = new CakeToppingInfo("Topping1", 1000); cakeBakingService.saveNewTopping(topping1); final var layer1 = new CakeLayerInfo("Layer1", 1000); cakeBakingService.saveNewLayer(layer1); final var missingLayer = new CakeLayerInfo("Layer2", 2000); assertThrows(CakeBakingException.class, () -> cakeBakingService.bakeNewCake(new CakeInfo(topping1, List.of(layer1, missingLayer)))); } @Test void testBakeCakesUsedLayer() throws CakeBakingException { final var initialCakes = cakeBakingService.getAllCakes(); assertNotNull(initialCakes); assertTrue(initialCakes.isEmpty()); final var topping1 = new CakeToppingInfo("Topping1", 1000); final var topping2 = new CakeToppingInfo("Topping2", 2000); cakeBakingService.saveNewTopping(topping1); cakeBakingService.saveNewTopping(topping2); final var layer1 = new CakeLayerInfo("Layer1", 1000); final var layer2 = new CakeLayerInfo("Layer2", 2000); cakeBakingService.saveNewLayer(layer1); cakeBakingService.saveNewLayer(layer2); cakeBakingService.bakeNewCake(new CakeInfo(topping1, List.of(layer1, layer2))); assertThrows(CakeBakingException.class, () -> cakeBakingService.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer2)))); } }
7,280
35.58794
140
java
java-design-patterns
java-design-patterns-master/layers/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.layers.exception; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import exception.CakeBakingException; import org.junit.jupiter.api.Test; /** * Date: 12/15/15 - 7:57 PM * * @author Jeroen Meulemeester */ class CakeBakingExceptionTest { @Test void testConstructor() { final var exception = new CakeBakingException(); assertNull(exception.getMessage()); assertNull(exception.getCause()); } @Test void testConstructorWithMessage() { final var expectedMessage = "message"; final var exception = new CakeBakingException(expectedMessage); assertEquals(expectedMessage, exception.getMessage()); assertNull(exception.getCause()); } }
2,056
34.465517
140
java
java-design-patterns
java-design-patterns-master/layers/src/test/java/com/iluwatar/layers/app/LayersAppTests.java
package com.iluwatar.layers.app; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import static org.junit.jupiter.api.Assertions.assertNotNull; @SpringBootTest(classes = LayersApp.class) class LayersAppTests { private final ApplicationContext applicationContext; @Autowired LayersAppTests(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Test void contextLoads() { assertNotNull(applicationContext); } }
660
25.44
62
java
java-design-patterns
java-design-patterns-master/layers/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.layers.view; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import dto.CakeInfo; import dto.CakeLayerInfo; import dto.CakeToppingInfo; import service.CakeBakingService; 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; import view.CakeViewImpl; /** * Date: 12/15/15 - 10:04 PM * * @author Jeroen Meulemeester */ class CakeViewImplTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(CakeViewImpl.class); } @AfterEach void tearDown() { appender.stop(); } /** * Verify if the cake view renders the expected result */ @Test void testRender() { final var layers = List.of( new CakeLayerInfo("layer1", 1000), new CakeLayerInfo("layer2", 2000), new CakeLayerInfo("layer3", 3000)); final var cake = new CakeInfo(new CakeToppingInfo("topping", 1000), layers); final var cakes = List.of(cake); final var bakingService = mock(CakeBakingService.class); when(bakingService.getAllCakes()).thenReturn(cakes); final var cakeView = new CakeViewImpl(bakingService); assertEquals(0, appender.getLogSize()); cakeView.render(); assertEquals(cake.toString(), appender.getLastMessage()); } private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public String getLastMessage() { return log.get(log.size() - 1).getFormattedMessage(); } public int getLogSize() { return log.size(); } } }
3,465
29.13913
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/dao/CakeDao.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package dao; import entity.Cake; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * CRUD repository for cakes. */ @Repository public interface CakeDao extends JpaRepository<Cake, Long> {}
1,543
41.888889
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/dao/CakeLayerDao.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package dao; import entity.CakeLayer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * CRUD repository for cake layers. */ @Repository public interface CakeLayerDao extends JpaRepository<CakeLayer, Long> { }
1,566
40.236842
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/dao/CakeToppingDao.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package dao; import entity.CakeTopping; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * CRUD repository cake toppings. */ @Repository public interface CakeToppingDao extends JpaRepository<CakeTopping, Long> { }
1,572
38.325
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/entity/CakeTopping.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package entity; import jakarta.persistence.*; import lombok.*; /** * CakeTopping entity. */ @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder @EqualsAndHashCode public class CakeTopping { @Id @GeneratedValue private Long id; private String name; private int calories; @OneToOne(cascade = CascadeType.ALL) private Cake cake; public CakeTopping(String name, int calories) { this.setName(name); this.setCalories(calories); } @Override public String toString() { return String.format("id=%s name=%s calories=%d", id, name, calories); } }
1,924
28.615385
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/entity/Cake.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package entity; import java.util.HashSet; import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; import jakarta.persistence.CascadeType; import jakarta.persistence.FetchType; /** * Cake entity. */ @Entity public class Cake { @Id @GeneratedValue private Long id; @OneToOne(cascade = CascadeType.REMOVE) private CakeTopping topping; @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER) private Set<CakeLayer> layers; public Cake() { setLayers(new HashSet<>()); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public CakeTopping getTopping() { return topping; } public void setTopping(CakeTopping topping) { this.topping = topping; } public Set<CakeLayer> getLayers() { return layers; } public void setLayers(Set<CakeLayer> layers) { this.layers = layers; } public void addLayer(CakeLayer layer) { this.layers.add(layer); } @Override public String toString() { return String.format("id=%s topping=%s layers=%s", id, topping, layers.toString()); } }
2,620
28.122222
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/entity/CakeLayer.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package entity; import jakarta.persistence.*; import lombok.*; /** * CakeLayer entity. */ @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder @EqualsAndHashCode public class CakeLayer { @Id @GeneratedValue private Long id; private String name; private int calories; @ManyToOne(cascade = CascadeType.ALL) private Cake cake; public CakeLayer(String name, int calories) { this.setName(name); this.setCalories(calories); } @Override public String toString() { return String.format("id=%s name=%s calories=%d", id, name, calories); } }
1,918
28.984375
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/service/CakeBakingService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package service; import dto.CakeInfo; import dto.CakeLayerInfo; import dto.CakeToppingInfo; import exception.CakeBakingException; import org.springframework.stereotype.Service; import java.util.List; /** * Service for cake baking operations. */ @Service public interface CakeBakingService { /** * Bakes new cake according to parameters. */ void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException; /** * Get all cakes. */ List<CakeInfo> getAllCakes(); /** * Store new cake topping. */ void saveNewTopping(CakeToppingInfo toppingInfo); /** * Get available cake toppings. */ List<CakeToppingInfo> getAvailableToppings(); /** * Add new cake layer. */ void saveNewLayer(CakeLayerInfo layerInfo); /** * Get available cake layers. */ List<CakeLayerInfo> getAvailableLayers(); void deleteAllCakes(); void deleteAllLayers(); void deleteAllToppings(); }
2,270
28.115385
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/service/CakeBakingServiceImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package service; import dao.CakeDao; import dao.CakeLayerDao; import dao.CakeToppingDao; import dto.CakeInfo; import dto.CakeLayerInfo; import dto.CakeToppingInfo; import entity.Cake; import entity.CakeLayer; import entity.CakeTopping; import exception.CakeBakingException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Implementation of CakeBakingService. */ @Service @Transactional public class CakeBakingServiceImpl implements CakeBakingService { private final CakeDao cakeDao; private final CakeLayerDao cakeLayerDao; private final CakeToppingDao cakeToppingDao; @Autowired public CakeBakingServiceImpl(CakeDao cakeDao, CakeLayerDao cakeLayerDao, CakeToppingDao cakeToppingDao) { this.cakeDao = cakeDao; this.cakeLayerDao = cakeLayerDao; this.cakeToppingDao = cakeToppingDao; } @Override public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException { var allToppings = getAvailableToppingEntities(); var matchingToppings = allToppings.stream().filter(t -> t.getName().equals(cakeInfo.cakeToppingInfo.name)) .toList(); if (matchingToppings.isEmpty()) { throw new CakeBakingException(String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name)); } var allLayers = getAvailableLayerEntities(); Set<CakeLayer> foundLayers = new HashSet<>(); for (var info : cakeInfo.cakeLayerInfos) { var found = allLayers.stream().filter(layer -> layer.getName().equals(info.name)).findFirst(); if (found.isEmpty()) { throw new CakeBakingException(String.format("Layer %s is not available", info.name)); } else { foundLayers.add(found.get()); } } var topping = cakeToppingDao.findById(matchingToppings.iterator().next().getId()); if (topping.isPresent()) { var cake = new Cake(); cake.setTopping(topping.get()); cake.setLayers(foundLayers); cakeDao.save(cake); topping.get().setCake(cake); cakeToppingDao.save(topping.get()); Set<CakeLayer> foundLayersToUpdate = new HashSet<>(foundLayers); // copy set to avoid a ConcurrentModificationException for (var layer : foundLayersToUpdate) { layer.setCake(cake); cakeLayerDao.save(layer); } } else { throw new CakeBakingException(String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name)); } } @Override public void saveNewTopping(CakeToppingInfo toppingInfo) { cakeToppingDao.save(new CakeTopping(toppingInfo.name, toppingInfo.calories)); } @Override public void saveNewLayer(CakeLayerInfo layerInfo) { cakeLayerDao.save(new CakeLayer(layerInfo.name, layerInfo.calories)); } private List<CakeTopping> getAvailableToppingEntities() { List<CakeTopping> result = new ArrayList<>(); for (CakeTopping topping : cakeToppingDao.findAll()) { if (topping.getCake() == null) { result.add(topping); } } return result; } @Override public List<CakeToppingInfo> getAvailableToppings() { List<CakeToppingInfo> result = new ArrayList<>(); for (CakeTopping next : cakeToppingDao.findAll()) { if (next.getCake() == null) { result.add(new CakeToppingInfo(next.getId(), next.getName(), next.getCalories())); } } return result; } private List<CakeLayer> getAvailableLayerEntities() { List<CakeLayer> result = new ArrayList<>(); for (CakeLayer next : cakeLayerDao.findAll()) { if (next.getCake() == null) { result.add(next); } } return result; } @Override public List<CakeLayerInfo> getAvailableLayers() { List<CakeLayerInfo> result = new ArrayList<>(); for (CakeLayer next : cakeLayerDao.findAll()) { if (next.getCake() == null) { result.add(new CakeLayerInfo(next.getId(), next.getName(), next.getCalories())); } } return result; } @Override public void deleteAllCakes() { cakeDao.deleteAll(); } @Override public void deleteAllLayers() { cakeLayerDao.deleteAll(); } @Override public void deleteAllToppings() { cakeToppingDao.deleteAll(); } @Override public List<CakeInfo> getAllCakes() { List<CakeInfo> result = new ArrayList<>(); for (Cake cake : cakeDao.findAll()) { var cakeToppingInfo = new CakeToppingInfo(cake.getTopping().getId(), cake.getTopping().getName(), cake .getTopping().getCalories()); List<CakeLayerInfo> cakeLayerInfos = new ArrayList<>(); for (var layer : cake.getLayers()) { cakeLayerInfos.add(new CakeLayerInfo(layer.getId(), layer.getName(), layer.getCalories())); } var cakeInfo = new CakeInfo(cake.getId(), cakeToppingInfo, cakeLayerInfos); result.add(cakeInfo); } return result; } }
6,887
35.252632
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/exception/CakeBakingException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package exception; import org.springframework.stereotype.Component; /** * Custom exception used in cake baking. */ @Component public class CakeBakingException extends Exception { private static final long serialVersionUID = 1L; public CakeBakingException() { } public CakeBakingException(String message) { super(message); } }
1,645
36.409091
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/com/iluwatar/layers/Runner.java
package com.iluwatar.layers; import dto.CakeInfo; import dto.CakeLayerInfo; import dto.CakeToppingInfo; import exception.CakeBakingException; import lombok.extern.slf4j.Slf4j; import service.CakeBakingService; import view.CakeViewImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.util.List; @Component @Slf4j public class Runner implements CommandLineRunner { private final CakeBakingService cakeBakingService; public static final String STRAWBERRY = "strawberry"; @Autowired public Runner(CakeBakingService cakeBakingService) { this.cakeBakingService = cakeBakingService; } @Override public void run(String... args) { //initialize sample data initializeData(); // create view and render it var cakeView = new CakeViewImpl(cakeBakingService); cakeView.render(); } /** * Initializes the example data. */ private void initializeData() { cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200)); cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900)); cakeBakingService.saveNewLayer(new CakeLayerInfo(STRAWBERRY, 950)); cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950)); cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950)); cakeBakingService.saveNewLayer(new CakeLayerInfo(STRAWBERRY, 950)); cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350)); cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350)); var cake1 = new CakeInfo(new CakeToppingInfo("candies", 0), List.of( new CakeLayerInfo("chocolate", 0), new CakeLayerInfo("banana", 0), new CakeLayerInfo(STRAWBERRY, 0))); try { cakeBakingService.bakeNewCake(cake1); } catch (CakeBakingException e) { LOGGER.error("Cake baking exception", e); } var cake2 = new CakeInfo(new CakeToppingInfo("cherry", 0), List.of( new CakeLayerInfo("vanilla", 0), new CakeLayerInfo("lemon", 0), new CakeLayerInfo(STRAWBERRY, 0))); try { cakeBakingService.bakeNewCake(cake2); } catch (CakeBakingException e) { LOGGER.error("Cake baking exception", e); } } }
2,480
34.956522
78
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/com/iluwatar/layers/app/LayersApp.java
package com.iluwatar.layers.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @EnableJpaRepositories(basePackages = "dao") @EntityScan(basePackages = "entity") @ComponentScan(basePackages = {"com.iluwatar.layers", "service", "dto", "exception", "view" ,"dao"}) public class LayersApp { public static void main(String[] args) { SpringApplication.run(LayersApp.class, args); } }
699
32.333333
100
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/dto/CakeLayerInfo.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package dto; import java.util.Optional; /** * DTO for cake layers. */ public class CakeLayerInfo { public final Optional<Long> id; public final String name; public final int calories; /** * Constructor. */ public CakeLayerInfo(Long id, String name, int calories) { this.id = Optional.of(id); this.name = name; this.calories = calories; } /** * Constructor. */ public CakeLayerInfo(String name, int calories) { this.id = Optional.empty(); this.name = name; this.calories = calories; } @Override public String toString() { return String.format("CakeLayerInfo id=%d name=%s calories=%d", id.orElse(-1L), name, calories); } }
2,038
32.42623
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/dto/CakeInfo.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package dto; import java.util.List; import java.util.Optional; /** * DTO for cakes. */ public class CakeInfo { public final Optional<Long> id; public final CakeToppingInfo cakeToppingInfo; public final List<CakeLayerInfo> cakeLayerInfos; /** * Constructor. */ public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List<CakeLayerInfo> cakeLayerInfos) { this.id = Optional.of(id); this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } /** * Constructor. */ public CakeInfo(CakeToppingInfo cakeToppingInfo, List<CakeLayerInfo> cakeLayerInfos) { this.id = Optional.empty(); this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } /** * Calculate calories. */ public int calculateTotalCalories() { var total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0; total += cakeLayerInfos.stream().mapToInt(c -> c.calories).sum(); return total; } @Override public String toString() { return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.orElse(-1L), cakeToppingInfo, cakeLayerInfos, calculateTotalCalories()); } }
2,570
34.708333
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/dto/CakeToppingInfo.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package dto; import java.util.Optional; /** * DTO for cake toppings. */ public class CakeToppingInfo { public final Optional<Long> id; public final String name; public final int calories; /** * Constructor. */ public CakeToppingInfo(Long id, String name, int calories) { this.id = Optional.of(id); this.name = name; this.calories = calories; } /** * Constructor. */ public CakeToppingInfo(String name, int calories) { this.id = Optional.empty(); this.name = name; this.calories = calories; } @Override public String toString() { return String.format("CakeToppingInfo id=%d name=%s calories=%d", id.orElse(-1L), name, calories); } }
2,065
31.793651
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/view/CakeViewImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package view; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.CakeBakingService; /** * View implementation for displaying cakes. */ public class CakeViewImpl implements View { private final CakeBakingService cakeBakingService; private static final Logger LOGGER = LoggerFactory.getLogger(CakeViewImpl.class); public CakeViewImpl(CakeBakingService cakeBakingService) { this.cakeBakingService = cakeBakingService; } public void render() { cakeBakingService.getAllCakes().forEach(cake -> LOGGER.info(cake.toString())); } }
1,876
38.104167
140
java
java-design-patterns
java-design-patterns-master/layers/src/main/java/view/View.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package view; /** * View interface. */ public interface View { void render(); }
1,373
38.257143
140
java
java-design-patterns
java-design-patterns-master/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.stepbuilder; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Date: 12/29/15 - 9:21 PM * * @author Jeroen Meulemeester */ class CharacterStepBuilderTest { /** * Build a new wizard {@link Character} and verify if it has the expected attributes */ @Test void testBuildWizard() { final var character = CharacterStepBuilder.newBuilder() .name("Merlin") .wizardClass("alchemist") .withSpell("poison") .withAbility("invisibility") .withAbility("wisdom") .noMoreAbilities() .build(); assertEquals("Merlin", character.getName()); assertEquals("alchemist", character.getWizardClass()); assertEquals("poison", character.getSpell()); assertNotNull(character.toString()); final var abilities = character.getAbilities(); assertNotNull(abilities); assertEquals(2, abilities.size()); assertTrue(abilities.contains("invisibility")); assertTrue(abilities.contains("wisdom")); } /** * Build a new wizard {@link Character} without spell or abilities and verify if it has the * expected attributes */ @Test void testBuildPoorWizard() { final var character = CharacterStepBuilder.newBuilder() .name("Merlin") .wizardClass("alchemist") .noSpell() .build(); assertEquals("Merlin", character.getName()); assertEquals("alchemist", character.getWizardClass()); assertNull(character.getSpell()); assertNull(character.getAbilities()); assertNotNull(character.toString()); } /** * Build a new wizard {@link Character} and verify if it has the expected attributes */ @Test void testBuildWeakWizard() { final var character = CharacterStepBuilder.newBuilder() .name("Merlin") .wizardClass("alchemist") .withSpell("poison") .noAbilities() .build(); assertEquals("Merlin", character.getName()); assertEquals("alchemist", character.getWizardClass()); assertEquals("poison", character.getSpell()); assertNull(character.getAbilities()); assertNotNull(character.toString()); } /** * Build a new warrior {@link Character} and verify if it has the expected attributes */ @Test void testBuildWarrior() { final var character = CharacterStepBuilder.newBuilder() .name("Cuauhtemoc") .fighterClass("aztec") .withWeapon("spear") .withAbility("speed") .withAbility("strength") .noMoreAbilities() .build(); assertEquals("Cuauhtemoc", character.getName()); assertEquals("aztec", character.getFighterClass()); assertEquals("spear", character.getWeapon()); assertNotNull(character.toString()); final var abilities = character.getAbilities(); assertNotNull(abilities); assertEquals(2, abilities.size()); assertTrue(abilities.contains("speed")); assertTrue(abilities.contains("strength")); } /** * Build a new wizard {@link Character} without weapon and abilities and verify if it has the * expected attributes */ @Test void testBuildPoorWarrior() { final var character = CharacterStepBuilder.newBuilder() .name("Poor warrior") .fighterClass("none") .noWeapon() .build(); assertEquals("Poor warrior", character.getName()); assertEquals("none", character.getFighterClass()); assertNull(character.getWeapon()); assertNull(character.getAbilities()); assertNotNull(character.toString()); } /** * Build a new warrior {@link Character} without any abilities, but with a weapon and verify if it * has the expected attributes */ @Test void testBuildWeakWarrior() { final var character = CharacterStepBuilder.newBuilder() .name("Weak warrior") .fighterClass("none") .withWeapon("Slingshot") .noAbilities() .build(); assertEquals("Weak warrior", character.getName()); assertEquals("none", character.getFighterClass()); assertEquals("Slingshot", character.getWeapon()); assertNull(character.getAbilities()); assertNotNull(character.toString()); } }
5,675
31.25
140
java
java-design-patterns
java-design-patterns-master/step-builder/src/test/java/com/iluwatar/stepbuilder/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.stepbuilder; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,579
37.536585
140
java
java-design-patterns
java-design-patterns-master/step-builder/src/main/java/com/iluwatar/stepbuilder/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.stepbuilder; import lombok.extern.slf4j.Slf4j; /** * Step Builder Pattern * * <p><b>Intent</b> <br> * An extension of the Builder pattern that fully guides the user through the creation of the object * with no chances of confusion. <br> The user experience will be much more improved by the fact * that he will only see the next step methods available, NO build method until is the right time to * build the object. * * <p><b>Implementation</b> <br> * The concept is simple: * <ul> * * <li>Write creational steps inner classes or interfaces where each method knows what can be * displayed next.</li> * * <li>Implement all your steps interfaces in an inner static class.</li> * * <li>Last step is the BuildStep, in charge of creating the object you need to build.</li> * </ul> * * <p><b>Applicability</b> <br> * Use the Step Builder pattern when the algorithm for creating a complex object should be * independent of the parts that make up the object and how they're assembled the construction * process must allow different representations for the object that's constructed when in the * process of constructing the order is important. * <br> * * @see <a href="http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html">http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html</a> */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var warrior = CharacterStepBuilder .newBuilder() .name("Amberjill") .fighterClass("Paladin") .withWeapon("Sword") .noAbilities() .build(); LOGGER.info(warrior.toString()); var mage = CharacterStepBuilder .newBuilder() .name("Riobard") .wizardClass("Sorcerer") .withSpell("Fireball") .withAbility("Fire Aura") .withAbility("Teleport") .noMoreAbilities() .build(); LOGGER.info(mage.toString()); var thief = CharacterStepBuilder .newBuilder() .name("Desmond") .fighterClass("Rogue") .noWeapon() .build(); LOGGER.info(thief.toString()); } }
3,506
33.722772
153
java
java-design-patterns
java-design-patterns-master/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.stepbuilder; import java.util.ArrayList; import java.util.List; /** * The Step Builder class. */ public final class CharacterStepBuilder { private CharacterStepBuilder() { } public static NameStep newBuilder() { return new CharacterSteps(); } /** * First Builder Step in charge of the Character name. Next Step available : ClassStep */ public interface NameStep { ClassStep name(String name); } /** * This step is in charge of setting the Character class (fighter or wizard). Fighter choice : * Next Step available : WeaponStep Wizard choice : Next Step available : SpellStep */ public interface ClassStep { WeaponStep fighterClass(String fighterClass); SpellStep wizardClass(String wizardClass); } /** * This step is in charge of the weapon. Weapon choice : Next Step available : AbilityStep No * weapon choice : Next Step available : BuildStep */ public interface WeaponStep { AbilityStep withWeapon(String weapon); BuildStep noWeapon(); } /** * This step is in charge of the spell. Spell choice : Next Step available : AbilityStep No spell * choice : Next Step available : BuildStep */ public interface SpellStep { AbilityStep withSpell(String spell); BuildStep noSpell(); } /** * This step is in charge of abilities. Next Step available : BuildStep */ public interface AbilityStep { AbilityStep withAbility(String ability); BuildStep noMoreAbilities(); BuildStep noAbilities(); } /** * This is the final step in charge of building the Character Object. Validation should be here. */ public interface BuildStep { Character build(); } /** * Step Builder implementation. */ private static class CharacterSteps implements NameStep, ClassStep, WeaponStep, SpellStep, AbilityStep, BuildStep { private String name; private String fighterClass; private String wizardClass; private String weapon; private String spell; private final List<String> abilities = new ArrayList<>(); @Override public ClassStep name(String name) { this.name = name; return this; } @Override public WeaponStep fighterClass(String fighterClass) { this.fighterClass = fighterClass; return this; } @Override public SpellStep wizardClass(String wizardClass) { this.wizardClass = wizardClass; return this; } @Override public AbilityStep withWeapon(String weapon) { this.weapon = weapon; return this; } @Override public BuildStep noWeapon() { return this; } @Override public AbilityStep withSpell(String spell) { this.spell = spell; return this; } @Override public BuildStep noSpell() { return this; } @Override public AbilityStep withAbility(String ability) { this.abilities.add(ability); return this; } @Override public BuildStep noMoreAbilities() { return this; } @Override public BuildStep noAbilities() { return this; } @Override public Character build() { var character = new Character(name); if (fighterClass != null) { character.setFighterClass(fighterClass); } else { character.setWizardClass(wizardClass); } if (weapon != null) { character.setWeapon(weapon); } else { character.setSpell(spell); } if (!abilities.isEmpty()) { character.setAbilities(abilities); } return character; } } }
4,907
24.696335
140
java
java-design-patterns
java-design-patterns-master/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.stepbuilder; import java.util.List; import lombok.Getter; import lombok.Setter; /** * The class with many parameters. */ @Getter @Setter public class Character { private String name; private String fighterClass; private String wizardClass; private String weapon; private String spell; private List<String> abilities; public Character(String name) { this.name = name; } @Override public String toString() { return new StringBuilder() .append("This is a ") .append(fighterClass != null ? fighterClass : wizardClass) .append(" named ") .append(name) .append(" armed with a ") .append(weapon != null ? weapon : spell != null ? spell : "with nothing") .append(abilities != null ? " and wielding " + abilities + " abilities" : "") .append('.') .toString(); } }
2,172
31.924242
140
java
java-design-patterns
java-design-patterns-master/context-object/src/test/java/com/iluwatar/contect/object/ServiceContextTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.contect.object; import com.iluwatar.context.object.LayerA; import com.iluwatar.context.object.LayerB; import com.iluwatar.context.object.LayerC; import com.iluwatar.context.object.ServiceContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; /** * Date: 10/24/2022 - 3:18 * * @author Chak Chan */ public class ServiceContextTest { private static final String SERVICE = "SERVICE"; private LayerA layerA; @BeforeEach void initiateLayerA() { this.layerA = new LayerA(); } @Test void testSameContextPassedBetweenLayers() { ServiceContext context1 = layerA.getContext(); var layerB = new LayerB(layerA); ServiceContext context2 = layerB.getContext(); var layerC = new LayerC(layerB); ServiceContext context3 = layerC.getContext(); assertSame(context1, context2); assertSame(context2, context3); assertSame(context3, context1); } @Test void testScopedDataPassedBetweenLayers() { layerA.addAccountInfo(SERVICE); var layerB = new LayerB(layerA); var layerC = new LayerC(layerB); layerC.addSearchInfo(SERVICE); ServiceContext context = layerC.getContext(); assertEquals(SERVICE, context.getAccountService()); assertNull(context.getSessionService()); assertEquals(SERVICE, context.getSearchService()); } @Test void testLayerContexts() { assertAll( () -> assertNull(layerA.getContext().getAccountService()), () -> assertNull(layerA.getContext().getSearchService()), () -> assertNull(layerA.getContext().getSessionService()) ); layerA.addAccountInfo(SERVICE); assertAll( () -> assertEquals(SERVICE, layerA.getContext().getAccountService()), () -> assertNull(layerA.getContext().getSearchService()), () -> assertNull(layerA.getContext().getSessionService()) ); var layerB = new LayerB(layerA); layerB.addSessionInfo(SERVICE); assertAll( () -> assertEquals(SERVICE, layerB.getContext().getAccountService()), () -> assertEquals(SERVICE, layerB.getContext().getSessionService()), () -> assertNull(layerB.getContext().getSearchService()) ); var layerC = new LayerC(layerB); layerC.addSearchInfo(SERVICE); assertAll( () -> assertEquals(SERVICE, layerC.getContext().getAccountService()), () -> assertEquals(SERVICE, layerC.getContext().getSearchService()), () -> assertEquals(SERVICE, layerC.getContext().getSessionService()) ); } }
4,049
35.818182
140
java
java-design-patterns
java-design-patterns-master/context-object/src/test/java/com/iluwatar/contect/object/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.contect.object; import com.iluwatar.context.object.App; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; public class AppTest { /** * Test example app runs without error. */ @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[] {})); } }
1,656
38.452381
140
java
java-design-patterns
java-design-patterns-master/context-object/src/main/java/com/iluwatar/context/object/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.context.object; import lombok.extern.slf4j.Slf4j; /** * In the context object pattern, information and data from underlying protocol-specific classes/systems is decoupled * and stored into a protocol-independent object in an organised format. The pattern ensures the data contained within * the context object can be shared and further structured between different layers of a software system. * * <p> In this example we show how a context object {@link ServiceContext} can be initiated, edited and passed/retrieved * in different layers of the program ({@link LayerA}, {@link LayerB}, {@link LayerC}) through use of static methods. </p> */ @Slf4j public class App { private static final String SERVICE = "SERVICE"; /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { //Initiate first layer and add service information into context var layerA = new LayerA(); layerA.addAccountInfo(SERVICE); LOGGER.info("Context = {}", layerA.getContext()); //Initiate second layer and preserving information retrieved in first layer through passing context object var layerB = new LayerB(layerA); layerB.addSessionInfo(SERVICE); LOGGER.info("Context = {}", layerB.getContext()); //Initiate third layer and preserving information retrieved in first and second layer through passing context object var layerC = new LayerC(layerB); layerC.addSearchInfo(SERVICE); LOGGER.info("Context = {}", layerC.getContext()); } }
2,840
41.402985
140
java
java-design-patterns
java-design-patterns-master/context-object/src/main/java/com/iluwatar/context/object/ServiceContextFactory.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.context.object; /** * An interface to create context objects passed through layers. */ public class ServiceContextFactory { public static ServiceContext createContext() { return new ServiceContext(); } }
1,521
41.277778
140
java
java-design-patterns
java-design-patterns-master/context-object/src/main/java/com/iluwatar/context/object/LayerC.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.context.object; import lombok.Getter; /** * Layer C in the context object pattern. */ @Getter public class LayerC { public ServiceContext context; public LayerC(LayerB layerB) { this.context = layerB.getContext(); } public void addSearchInfo(String searchService) { context.setSearchService(searchService); } }
1,641
35.488889
140
java
java-design-patterns
java-design-patterns-master/context-object/src/main/java/com/iluwatar/context/object/LayerA.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.context.object; import lombok.Getter; /** * Layer A in the context object pattern. */ @Getter public class LayerA { private ServiceContext context; public LayerA() { context = ServiceContextFactory.createContext(); } public void addAccountInfo(String accountService) { context.setAccountService(accountService); } }
1,646
35.6
140
java
java-design-patterns
java-design-patterns-master/context-object/src/main/java/com/iluwatar/context/object/ServiceContext.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.context.object; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * Where context objects are defined. */ @Getter @Setter public class ServiceContext { String accountService; String sessionService; String searchService; }
1,560
36.166667
140
java
java-design-patterns
java-design-patterns-master/context-object/src/main/java/com/iluwatar/context/object/LayerB.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.context.object; import lombok.Getter; /** * Layer B in the context object pattern. */ @Getter public class LayerB { private ServiceContext context; public LayerB(LayerA layerA) { this.context = layerA.getContext(); } public void addSessionInfo(String sessionService) { context.setSessionService(sessionService); } }
1,646
35.6
140
java
java-design-patterns
java-design-patterns-master/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.datamapper; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; /** * Tests {@link Student}. */ final class StudentTest { /** * This API tests the equality behaviour of Student object Object Equality should work as per * logic defined in equals method * * @throws Exception if any execution error during test */ @Test void testEquality() throws Exception { /* Create some students */ final var firstStudent = new Student(1, "Adam", 'A'); final var secondStudent = new Student(2, "Donald", 'B'); final var secondSameStudent = new Student(2, "Donald", 'B'); /* Check equals functionality: should return 'true' */ assertEquals(firstStudent, firstStudent); /* Check equals functionality: should return 'false' */ assertNotEquals(firstStudent, secondStudent); /* Check equals functionality: should return 'true' */ assertEquals(secondStudent, secondSameStudent); } }
2,348
37.508197
140
java
java-design-patterns
java-design-patterns-master/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.datamapper; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; /** * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the * database. Its responsibility is to transfer data between the two and also to isolate them from * each other. With Data Mapper the in-memory objects needn't know even that there's a database * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , * Data Mapper itself is even unknown to the domain layer. * <p> */ class DataMapperTest { /** * This test verify that first data mapper is able to perform all CRUD operations on Student */ @Test void testFirstDataMapper() { /* Create new data mapper of first type */ final var mapper = new StudentDataMapperImpl(); /* Create new student */ var studentId = 1; var student = new Student(studentId, "Adam", 'A'); /* Add student in respectibe db */ mapper.insert(student); /* Check if student is added in db */ assertEquals(studentId, mapper.find(student.getStudentId()).get().getStudentId()); /* Update existing student object */ var updatedName = "AdamUpdated"; student = new Student(student.getStudentId(), updatedName, 'A'); /* Update student in respectibe db */ mapper.update(student); /* Check if student is updated in db */ assertEquals(updatedName, mapper.find(student.getStudentId()).get().getName()); /* Delete student in db */ mapper.delete(student); /* Result should be false */ assertFalse(mapper.find(student.getStudentId()).isPresent()); } }
3,125
38.56962
140
java
java-design-patterns
java-design-patterns-master/data-mapper/src/test/java/com/iluwatar/datamapper/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.datamapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that Data-Mapper example runs without errors. */ final 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((Executable) App::main); } }
1,889
36.8
140
java
java-design-patterns
java-design-patterns-master/data-mapper/src/main/java/com/iluwatar/datamapper/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.datamapper; import lombok.extern.slf4j.Slf4j; /** * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the * database. Its responsibility is to transfer data between the two and also to isolate them from * each other. With Data Mapper the in-memory objects needn't know even that there's a database * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , * Data Mapper itself is even unknown to the domain layer. * * <p>The below example demonstrates basic CRUD operations: Create, Read, Update, and Delete. */ @Slf4j public final class App { private static final String STUDENT_STRING = "App.main(), student : "; /** * Program entry point. * * @param args command line args. */ public static void main(final String... args) { /* Create new data mapper for type 'first' */ final var mapper = new StudentDataMapperImpl(); /* Create new student */ var student = new Student(1, "Adam", 'A'); /* Add student in respectibe store */ mapper.insert(student); LOGGER.debug(STUDENT_STRING + student + ", is inserted"); /* Find this student */ final var studentToBeFound = mapper.find(student.getStudentId()); LOGGER.debug(STUDENT_STRING + studentToBeFound + ", is searched"); /* Update existing student object */ student = new Student(student.getStudentId(), "AdamUpdated", 'A'); /* Update student in respectibe db */ mapper.update(student); LOGGER.debug(STUDENT_STRING + student + ", is updated"); LOGGER.debug(STUDENT_STRING + student + ", is going to be deleted"); /* Delete student in db */ mapper.delete(student); } private App() { } }
3,131
36.73494
140
java
java-design-patterns
java-design-patterns-master/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.datamapper; import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * Class defining Student. */ @EqualsAndHashCode(onlyExplicitlyIncluded = true) @ToString @Getter @Setter @AllArgsConstructor public final class Student implements Serializable { private static final long serialVersionUID = 1L; @EqualsAndHashCode.Include private int studentId; private String name; private char grade; }
1,822
34.057692
140
java
java-design-patterns
java-design-patterns-master/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.datamapper; /** * Using Runtime Exception for avoiding dependancy on implementation exceptions. This helps in * decoupling. * * @author amit.dixit */ public final class DataMapperException extends RuntimeException { private static final long serialVersionUID = 1L; /** * Constructs a new runtime exception with the specified detail message. The cause is not * initialized, and may subsequently be initialized by a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for later retrieval by the * {@link #getMessage()} method. */ public DataMapperException(final String message) { super(message); } }
2,000
40.6875
140
java
java-design-patterns
java-design-patterns-master/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.datamapper; import java.util.Optional; /** * Interface lists out the possible behaviour for all possible student mappers. */ public interface StudentDataMapper { Optional<Student> find(int studentId); void insert(Student student) throws DataMapperException; void update(Student student) throws DataMapperException; void delete(Student student) throws DataMapperException; }
1,695
39.380952
140
java
java-design-patterns
java-design-patterns-master/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.datamapper; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * Implementation of Actions on Students Data. */ public final class StudentDataMapperImpl implements StudentDataMapper { /* Note: Normally this would be in the form of an actual database */ private final List<Student> students = new ArrayList<>(); @Override public Optional<Student> find(int studentId) { return this.getStudents().stream().filter(x -> x.getStudentId() == studentId).findFirst(); } @Override public void update(Student studentToBeUpdated) throws DataMapperException { String name = studentToBeUpdated.getName(); Integer index = Optional.of(studentToBeUpdated) .map(Student::getStudentId) .flatMap(this::find) .map(students::indexOf) .orElseThrow(() -> new DataMapperException("Student [" + name + "] is not found")); students.set(index, studentToBeUpdated); } @Override public void insert(Student studentToBeInserted) throws DataMapperException { Optional<Student> student = find(studentToBeInserted.getStudentId()); if (student.isPresent()) { String name = studentToBeInserted.getName(); throw new DataMapperException("Student already [" + name + "] exists"); } students.add(studentToBeInserted); } @Override public void delete(Student studentToBeDeleted) throws DataMapperException { if (!students.remove(studentToBeDeleted)) { String name = studentToBeDeleted.getName(); throw new DataMapperException("Student [" + name + "] is not found"); } } public List<Student> getStudents() { return this.students; } }
2,969
37.076923
140
java
java-design-patterns
java-design-patterns-master/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.monostate; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; /** * Date: 12/21/15 - 12:26 PM * * @author Jeroen Meulemeester */ class LoadBalancerTest { @Test void testSameStateAmongstAllInstances() { final var firstBalancer = new LoadBalancer(); final var secondBalancer = new LoadBalancer(); firstBalancer.addServer(new Server("localhost", 8085, 6)); // Both should have the same number of servers. assertEquals(firstBalancer.getNoOfServers(), secondBalancer.getNoOfServers()); // Both Should have the same LastServedId assertEquals(firstBalancer.getLastServedId(), secondBalancer.getLastServedId()); } @Test void testServe() { final var server = mock(Server.class); when(server.getHost()).thenReturn("testhost"); when(server.getPort()).thenReturn(1234); doNothing().when(server).serve(any(Request.class)); final var loadBalancer = new LoadBalancer(); loadBalancer.addServer(server); verifyNoMoreInteractions(server); final var request = new Request("test"); for (var i = 0; i < loadBalancer.getNoOfServers() * 2; i++) { loadBalancer.serverRequest(request); } verify(server, times(2)).serve(request); verifyNoMoreInteractions(server); } }
2,917
35.936709
140
java
java-design-patterns
java-design-patterns-master/monostate/src/test/java/com/iluwatar/monostate/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.monostate; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * Application Test Entry */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,596
36.139535
140
java
java-design-patterns
java-design-patterns-master/monostate/src/main/java/com/iluwatar/monostate/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.monostate; /** * The MonoState pattern ensures that all instances of the class will have the same state. This can * be used a direct replacement of the Singleton pattern. * * <p>In the following example, The {@link LoadBalancer} class represents the app's logic. It * contains a series of Servers, which can handle requests of type {@link Request}. Two instances of * LoadBalancer are created. When a request is made to a server via the first LoadBalancer the state * change in the first load balancer affects the second. So if the first LoadBalancer selects the * Server 1, the second LoadBalancer on a new request will select the Second server. If a third * LoadBalancer is created and a new request is made to it, then it will select the third server as * the second load balancer has already selected the second server. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var loadBalancer1 = new LoadBalancer(); var loadBalancer2 = new LoadBalancer(); loadBalancer1.serverRequest(new Request("Hello")); loadBalancer2.serverRequest(new Request("Hello World")); } }
2,496
45.240741
140
java
java-design-patterns
java-design-patterns-master/monostate/src/main/java/com/iluwatar/monostate/Request.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.monostate; /** * The Request class. A {@link Server} can handle an instance of a Request. */ public class Request { public final String value; public Request(String value) { this.value = value; } }
1,518
38.973684
140
java
java-design-patterns
java-design-patterns-master/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.monostate; import java.util.ArrayList; import java.util.List; /** * The LoadBalancer class. This implements the MonoState pattern. It holds a series of servers. Upon * receiving a new Request, it delegates the call to the servers in a Round Robin Fashion. Since all * instances of the class share the same state, all instances will delegate to the same server on * receiving a new Request. */ public class LoadBalancer { private static final List<Server> SERVERS = new ArrayList<>(); private static int lastServedId; static { var id = 0; for (var port : new int[]{8080, 8081, 8082, 8083, 8084}) { SERVERS.add(new Server("localhost", port, ++id)); } } /** * Add new server. */ public final void addServer(Server server) { synchronized (SERVERS) { SERVERS.add(server); } } public final int getNoOfServers() { return SERVERS.size(); } public int getLastServedId() { return lastServedId; } /** * Handle request. */ public synchronized void serverRequest(Request request) { if (lastServedId >= SERVERS.size()) { lastServedId = 0; } var server = SERVERS.get(lastServedId++); server.serve(request); } }
2,518
31.294872
140
java
java-design-patterns
java-design-patterns-master/monostate/src/main/java/com/iluwatar/monostate/Server.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.monostate; import lombok.extern.slf4j.Slf4j; /** * The Server class. Each Server sits behind a LoadBalancer which delegates the call to the servers * in a simplistic Round Robin fashion. */ @Slf4j public class Server { public final String host; public final int port; public final int id; /** * Constructor. */ public Server(String host, int port, int id) { this.host = host; this.port = port; this.id = id; } public String getHost() { return host; } public int getPort() { return port; } public void serve(Request request) { LOGGER.info("Server ID {} associated to host : {} and port {}. Processed request with value {}", id, host, port, request.value); } }
2,036
31.854839
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantModelTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.model.view.controller.Fatigue; import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; /** * The type Giant model test. */ class GiantModelTest { /** * Verify if the health value is set properly though the constructor and setter */ @Test void testSetHealth() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Health.HEALTHY, model.getHealth()); var messageFormat = "Giant giant1, The giant looks %s, alert and saturated."; for (final var health : Health.values()) { model.setHealth(health); assertEquals(health, model.getHealth()); assertEquals(String.format(messageFormat, health), model.toString()); } } /** * Verify if the fatigue level is set properly though the constructor and setter */ @Test void testSetFatigue() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Fatigue.ALERT, model.getFatigue()); var messageFormat = "Giant giant1, The giant looks healthy, %s and saturated."; for (final var fatigue : Fatigue.values()) { model.setFatigue(fatigue); assertEquals(fatigue, model.getFatigue()); assertEquals(String.format(messageFormat, fatigue), model.toString()); } } /** * Verify if the nourishment level is set properly though the constructor and setter */ @Test void testSetNourishment() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Nourishment.SATURATED, model.getNourishment()); var messageFormat = "Giant giant1, The giant looks healthy, alert and %s."; for (final var nourishment : Nourishment.values()) { model.setNourishment(nourishment); assertEquals(nourishment, model.getNourishment()); assertEquals(String.format(messageFormat, nourishment), model.toString()); } } }
3,458
38.758621
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantViewTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import com.iluwatar.model.view.controller.Fatigue; import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; /** * The type Giant view test. */ class GiantViewTest { /** * Test dispaly giant. */ @Test void testDispalyGiant() { GiantModel giantModel = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); GiantView giantView = new GiantView(); assertDoesNotThrow(() -> giantView.displayGiant(giantModel)); } }
1,947
37.96
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantControllerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.model.view.controller.Fatigue; import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; /** * The type Giant controller test. */ class GiantControllerTest { /** * Test set command. */ @Test void testSetCommand() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); GiantView giantView = new GiantView(); Dispatcher dispatcher = new Dispatcher(giantView); assertEquals(Nourishment.SATURATED, model.getNourishment()); dispatcher.addAction(action); GiantController controller = new GiantController(dispatcher); controller.setCommand(new Command(Fatigue.ALERT, Health.HEALTHY, Nourishment.HUNGRY), 0); assertEquals(Fatigue.ALERT, model.getFatigue()); assertEquals(Health.HEALTHY, model.getHealth()); assertEquals(Nourishment.HUNGRY, model.getNourishment()); } /** * Test update view. */ @Test void testUpdateView() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); GiantView giantView = new GiantView(); Dispatcher dispatcher = new Dispatcher(giantView); GiantController giantController = new GiantController(dispatcher); assertDoesNotThrow(() -> giantController.updateView(model)); } }
2,884
38.520548
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/test/java/com/iluwatar/servicetoworker/DispatcherTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.model.view.controller.Fatigue; import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; /** * The type Dispatcher test. */ class DispatcherTest { /** * Test perform action. */ @Test void testPerformAction() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); GiantView giantView = new GiantView(); Dispatcher dispatcher = new Dispatcher(giantView); assertEquals(Nourishment.SATURATED, model.getNourishment()); dispatcher.addAction(action); for (final var nourishment : Nourishment.values()) { for (final var fatigue : Fatigue.values()) { for (final var health : Health.values()) { Command cmd = new Command(fatigue, health, nourishment); dispatcher.performAction(cmd, 0); assertEquals(nourishment, model.getNourishment()); assertEquals(fatigue, model.getFatigue()); assertEquals(health, model.getHealth()); } } } } @Test void testUpdateView() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); GiantView giantView = new GiantView(); Dispatcher dispatcher = new Dispatcher(giantView); assertDoesNotThrow(() -> dispatcher.updateView(model)); } }
2,901
36.688312
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/test/java/com/iluwatar/servicetoworker/ActionTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.model.view.controller.Fatigue; import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; /** * The type Action test. */ class ActionTest { /** * Verify if the health value is set properly though the constructor and setter */ @Test void testSetHealth() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); assertEquals(Health.HEALTHY, model.getHealth()); var messageFormat = "Giant giant1, The giant looks %s, alert and saturated."; for (final var health : Health.values()) { action.setHealth(health); assertEquals(health, model.getHealth()); assertEquals(String.format(messageFormat, health), model.toString()); } } /** * Verify if the fatigue level is set properly though the constructor and setter */ @Test void testSetFatigue() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); assertEquals(Fatigue.ALERT, model.getFatigue()); var messageFormat = "Giant giant1, The giant looks healthy, %s and saturated."; for (final var fatigue : Fatigue.values()) { action.setFatigue(fatigue); assertEquals(fatigue, model.getFatigue()); assertEquals(String.format(messageFormat, fatigue), model.toString()); } } /** * Verify if the nourishment level is set properly though the constructor and setter */ @Test void testSetNourishment() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); assertEquals(Nourishment.SATURATED, model.getNourishment()); var messageFormat = "Giant giant1, The giant looks healthy, alert and %s."; for (final var nourishment : Nourishment.values()) { action.setNourishment(nourishment); assertEquals(nourishment, model.getNourishment()); assertEquals(String.format(messageFormat, nourishment), model.toString()); } } /** * Test update model. */ @Test void testUpdateModel() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); assertEquals(Nourishment.SATURATED, model.getNourishment()); for (final var nourishment : Nourishment.values()) { for (final var fatigue : Fatigue.values()) { for (final var health : Health.values()) { Command cmd = new Command(fatigue, health, nourishment); action.updateModel(cmd); assertEquals(nourishment, model.getNourishment()); assertEquals(fatigue, model.getFatigue()); assertEquals(health, model.getHealth()); } } } } }
4,309
37.482143
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/test/java/com/iluwatar/servicetoworker/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.servicetoworker; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,594
37.902439
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/main/java/com/iluwatar/servicetoworker/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.servicetoworker; import com.iluwatar.model.view.controller.Fatigue; import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; /** * The front controller intercepts all requests and performs common functions using decorators. The * front controller passes request information to the dispatcher, which uses the request and an * internal model to chooses and execute appropriate actions. The actions process user input, * translating it into appropriate updates to the model. The model applies business rules and stores * the data persistently. Based on the user input and results of the actions, the dispatcher chooses * a view. The view transforms the updated model data into a form suitable for the user. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // create model, view and controller var giant1 = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); var giant2 = new GiantModel("giant2", Health.DEAD, Fatigue.SLEEPING, Nourishment.STARVING); var action1 = new Action(giant1); var action2 = new Action(giant2); var view = new GiantView(); var dispatcher = new Dispatcher(view); dispatcher.addAction(action1); dispatcher.addAction(action2); var controller = new GiantController(dispatcher); // initial display controller.updateView(giant1); controller.updateView(giant2); // controller receives some interactions that affect the giant controller.setCommand(new Command(Fatigue.SLEEPING, Health.HEALTHY, Nourishment.STARVING), 0); controller.setCommand(new Command(Fatigue.ALERT, Health.HEALTHY, Nourishment.HUNGRY), 1); // redisplay controller.updateView(giant1); controller.updateView(giant2); // controller receives some interactions that affect the giant } }
3,235
43.944444
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Command.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import com.iluwatar.model.view.controller.Fatigue; import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; /** * The type Command. * Instantiates a new Command. * * @param fatigue the fatigue * @param health the health * @param nourishment the nourishment */ public record Command(Fatigue fatigue, Health health, Nourishment nourishment) { }
1,731
41.243902
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/main/java/com/iluwatar/servicetoworker/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.servicetoworker; import java.util.ArrayList; import java.util.List; import lombok.Getter; /** * The type Dispatcher, which encapsulates worker and view selection based on request information * and/or an internal navigation model. */ public class Dispatcher { @Getter private final GiantView giantView; private final List<Action> actions; /** * Instantiates a new Dispatcher. * * @param giantView the giant view */ public Dispatcher(GiantView giantView) { this.giantView = giantView; this.actions = new ArrayList<>(); } /** * Add an action. * * @param action the action */ void addAction(Action action) { actions.add(action); } /** * Perform an action. * * @param s the s * @param actionIndex the action index */ public void performAction(Command s, int actionIndex) { actions.get(actionIndex).updateModel(s); } /** * Update view. * * @param giantModel the giant model */ public void updateView(GiantModel giantModel) { giantView.displayGiant(giantModel); } }
2,386
28.8375
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Action.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import com.iluwatar.model.view.controller.Fatigue; import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; /** * The type Action (Worker), which can process user input and perform a specific update on the * model. */ public class Action { public GiantModel giant; /** * Instantiates a new Action. * * @param giant the giant */ public Action(GiantModel giant) { this.giant = giant; } /** * Update model based on command. * * @param command the command */ public void updateModel(Command command) { setFatigue(command.fatigue()); setHealth(command.health()); setNourishment(command.nourishment()); } /** * Sets health. * * @param health the health */ public void setHealth(Health health) { giant.setHealth(health); } /** * Sets fatigue. * * @param fatigue the fatigue */ public void setFatigue(Fatigue fatigue) { giant.setFatigue(fatigue); } /** * Sets nourishment. * * @param nourishment the nourishment */ public void setNourishment(Nourishment nourishment) { giant.setNourishment(nourishment); } }
2,501
28.093023
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantView.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import lombok.extern.slf4j.Slf4j; /** * GiantView displays the giant. */ @Slf4j public class GiantView { /** * Display the GiantModel simply. * * @param giant the giant */ public void displayGiant(GiantModel giant) { LOGGER.info(giant.toString()); } }
1,601
35.409091
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantModel.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import com.iluwatar.model.view.controller.Fatigue; import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import lombok.Getter; /** * GiantModel contains the giant data. */ public class GiantModel { private final com.iluwatar.model.view.controller.GiantModel model; @Getter private final String name; /** * Instantiates a new Giant model. * * @param name the name * @param health the health * @param fatigue the fatigue * @param nourishment the nourishment */ GiantModel(String name, Health health, Fatigue fatigue, Nourishment nourishment) { this.name = name; this.model = new com.iluwatar.model.view.controller.GiantModel(health, fatigue, nourishment); } /** * Gets health. * * @return the health */ Health getHealth() { return model.getHealth(); } /** * Sets health. * * @param health the health */ void setHealth(Health health) { model.setHealth(health); } /** * Gets fatigue. * * @return the fatigue */ Fatigue getFatigue() { return model.getFatigue(); } void setFatigue(Fatigue fatigue) { model.setFatigue(fatigue); } /** * Gets nourishment. * * @return the nourishment */ Nourishment getNourishment() { return model.getNourishment(); } /** * Sets nourishment. * * @param nourishment the nourishment */ void setNourishment(Nourishment nourishment) { model.setNourishment(nourishment); } @Override public String toString() { return String .format("Giant %s, The giant looks %s, %s and %s.", name, model.getHealth(), model.getFatigue(), model.getNourishment()); } }
3,068
26.648649
140
java
java-design-patterns
java-design-patterns-master/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantController.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicetoworker; import lombok.Getter; /** * GiantController can update the giant data and redraw it using the view. Singleton object that * intercepts all requests and performs common functions. */ public class GiantController { public Dispatcher dispatcher; /** * Instantiates a new Giant controller. * * @param dispatcher the dispatcher */ public GiantController(Dispatcher dispatcher) { this.dispatcher = dispatcher; } /** * Sets command to control the dispatcher. * * @param s the s * @param index the index */ public void setCommand(Command s, int index) { dispatcher.performAction(s, index); } /** * Update view. This is a simple implementation, in fact, View can be implemented in a concrete * way * * @param giantModel the giant model */ public void updateView(GiantModel giantModel) { dispatcher.updateView(giantModel); } }
2,226
32.742424
140
java
java-design-patterns
java-design-patterns-master/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.currying; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.time.LocalDate; /** * Unit tests for the Book class */ class BookCurryingTest { private static Book expectedBook; @BeforeAll public static void initialiseBook() { expectedBook = new Book(Genre.FANTASY, "Dave", "Into the Night", LocalDate.of(2002, 4, 7)); } /** * Tests that the expected book can be created via curried functions */ @Test void createsExpectedBook() { Book builderCurriedBook = Book.builder() .withGenre(Genre.FANTASY) .withAuthor("Dave") .withTitle("Into the Night") .withPublicationDate(LocalDate.of(2002, 4, 7)); Book funcCurriedBook = Book.book_creator .apply(Genre.FANTASY) .apply("Dave") .apply("Into the Night") .apply(LocalDate.of(2002, 4, 7)); assertEquals(expectedBook, builderCurriedBook); assertEquals(expectedBook, funcCurriedBook); } /** * Tests that an intermediate curried function can be used to create the expected book */ @Test void functionCreatesExpectedBook() { Book.AddTitle daveFantasyBookFunc = Book.builder() .withGenre(Genre.FANTASY) .withAuthor("Dave"); Book curriedBook = daveFantasyBookFunc.withTitle("Into the Night") .withPublicationDate(LocalDate.of(2002, 4, 7)); assertEquals(expectedBook, curriedBook); } }
2,811
32.879518
140
java
java-design-patterns
java-design-patterns-master/currying/src/test/java/com/iluwatar/currying/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.currying; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; /** * Tests that the App can be run without throwing any exceptions. */ class AppTest { @Test void executesWithoutExceptions() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,600
39.025
140
java
java-design-patterns
java-design-patterns-master/currying/src/main/java/com/iluwatar/currying/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.currying; import java.time.LocalDate; import lombok.extern.slf4j.Slf4j; /** * Currying decomposes a function with multiple arguments in multiple functions that * take a single argument. A curried function which has only been passed some of its * arguments is called a partial application. Partial application is useful since it can * be used to create specialised functions in a concise way. * * <p>In this example, a librarian uses a curried book builder function create books belonging to * desired genres and written by specific authors. */ @Slf4j public class App { /** * Main entry point of the program. */ public static void main(String[] args) { LOGGER.info("Librarian begins their work."); // Defining genre book functions Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY); Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR); Book.AddAuthor scifiBookFunc = Book.builder().withGenre(Genre.SCIFI); // Defining author book functions Book.AddTitle kingFantasyBooksFunc = fantasyBookFunc.withAuthor("Stephen King"); Book.AddTitle kingHorrorBooksFunc = horrorBookFunc.withAuthor("Stephen King"); Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling"); // Creates books by Stephen King (horror and fantasy genres) Book shining = kingHorrorBooksFunc.withTitle("The Shining") .withPublicationDate(LocalDate.of(1977, 1, 28)); Book darkTower = kingFantasyBooksFunc.withTitle("The Dark Tower: Gunslinger") .withPublicationDate(LocalDate.of(1982, 6, 10)); // Creates fantasy books by J.K. Rowling Book chamberOfSecrets = rowlingFantasyBooksFunc.withTitle("Harry Potter and the Chamber of Secrets") .withPublicationDate(LocalDate.of(1998, 7, 2)); // Create sci-fi books Book dune = scifiBookFunc.withAuthor("Frank Herbert") .withTitle("Dune") .withPublicationDate(LocalDate.of(1965, 8, 1)); Book foundation = scifiBookFunc.withAuthor("Isaac Asimov") .withTitle("Foundation") .withPublicationDate(LocalDate.of(1942, 5, 1)); LOGGER.info("Stephen King Books:"); LOGGER.info(shining.toString()); LOGGER.info(darkTower.toString()); LOGGER.info("J.K. Rowling Books:"); LOGGER.info(chamberOfSecrets.toString()); LOGGER.info("Sci-fi Books:"); LOGGER.info(dune.toString()); LOGGER.info(foundation.toString()); } }
3,778
42.94186
140
java
java-design-patterns
java-design-patterns-master/currying/src/main/java/com/iluwatar/currying/Genre.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.currying; /** * Enum representing different book genres. */ public enum Genre { FANTASY, HORROR, SCIFI; }
1,420
39.6
140
java