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/specification/src/main/java/com/iluwatar/specification/property/Mass.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specification.property;
import lombok.EqualsAndHashCode;
/**
* Mass property.
*/
@EqualsAndHashCode
public class Mass {
private final double value;
private final String title;
public Mass(double value) {
this.value = value;
this.title = value + "kg"; // Implicit call to Double.toString(value)
}
public final boolean greaterThan(Mass other) {
return this.value > other.value;
}
public final boolean smallerThan(Mass other) {
return this.value < other.value;
}
public final boolean greaterThanOrEq(Mass other) {
return this.value >= other.value;
}
public final boolean smallerThanOrEq(Mass other) {
return this.value <= other.value;
}
@Override
public String toString() {
return title;
}
}
| 2,064 | 30.769231 | 140 | java |
java-design-patterns | java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/property/Color.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specification.property;
/**
* Color property.
*/
public enum Color {
DARK("dark"), LIGHT("light"), GREEN("green"), RED("red");
private final String title;
Color(String title) {
this.title = title;
}
@Override
public String toString() {
return title;
}
}
| 1,588 | 34.311111 | 140 | java |
java-design-patterns | java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/property/Size.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specification.property;
/**
* Size property.
*/
public enum Size {
SMALL("small"), NORMAL("normal"), LARGE("large");
private final String title;
Size(String title) {
this.title = title;
}
@Override
public String toString() {
return title;
}
}
| 1,577 | 34.066667 | 140 | java |
java-design-patterns | java-design-patterns-master/specification/src/main/java/com/iluwatar/specification/property/Movement.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.specification.property;
/**
* Movement property.
*/
public enum Movement {
WALKING("walking"), SWIMMING("swimming"), FLYING("flying");
private final String title;
Movement(String title) {
this.title = title;
}
@Override
public String toString() {
return title;
}
}
| 1,599 | 34.555556 | 140 | java |
java-design-patterns | java-design-patterns-master/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pipeline;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
/**
* Test for {@link Pipeline}
*/
class PipelineTest {
@Test
void testAddHandlersToPipeline() {
var filters = new Pipeline<>(new RemoveAlphabetsHandler())
.addHandler(new RemoveDigitsHandler())
.addHandler(new ConvertToCharArrayHandler());
assertArrayEquals(
new char[]{'#', '!', '(', '&', '%', '#', '!'},
filters.execute("#H!E(L&L0O%THE3R#34E!")
);
}
}
| 1,828 | 37.104167 | 140 | java |
java-design-patterns | java-design-patterns-master/pipeline/src/test/java/com/iluwatar/pipeline/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.pipeline;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application Test
*/
class AppTest {
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,587 | 37.731707 | 140 | java |
java-design-patterns | java-design-patterns-master/pipeline/src/main/java/com/iluwatar/pipeline/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.pipeline;
/**
* The Pipeline pattern uses ordered stages to process a sequence of input values. Each implemented
* task is represented by a stage of the pipeline. You can think of pipelines as similar to assembly
* lines in a factory, where each item in the assembly line is constructed in stages. The partially
* assembled item is passed from one assembly stage to another. The outputs of the assembly line
* occur in the same order as that of the inputs.
*
* <p>Classes used in this example are suffixed with "Handlers", and synonymously refers to the
* "stage".
*/
public class App {
/**
* Specify the initial input type for the first stage handler and the expected output type of the
* last stage handler as type parameters for Pipeline. Use the fluent builder by calling
* addHandler to add more stage handlers on the pipeline.
*/
public static void main(String[] args) {
/*
Suppose we wanted to pass through a String to a series of filtering stages and convert it
as a char array on the last stage.
- Stage handler 1 (pipe): Removing the alphabets, accepts a String input and returns the
processed String output. This will be used by the next handler as its input.
- Stage handler 2 (pipe): Removing the digits, accepts a String input and returns the
processed String output. This shall also be used by the last handler we have.
- Stage handler 3 (pipe): Converting the String input to a char array handler. We would
be returning a different type in here since that is what's specified by the requirement.
This means that at any stages along the pipeline, the handler can return any type of data
as long as it fulfills the requirements for the next handler's input.
Suppose we wanted to add another handler after ConvertToCharArrayHandler. That handler
then is expected to receive an input of char[] array since that is the type being returned
by the previous handler, ConvertToCharArrayHandler.
*/
var filters = new Pipeline<>(new RemoveAlphabetsHandler())
.addHandler(new RemoveDigitsHandler())
.addHandler(new ConvertToCharArrayHandler());
filters.execute("GoYankees123!");
}
}
| 3,535 | 50.246377 | 140 | java |
java-design-patterns | java-design-patterns-master/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pipeline;
import java.util.function.IntPredicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Stage handler that returns a new instance of String without the alphabet characters of the input
* string.
*/
class RemoveAlphabetsHandler implements Handler<String, String> {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoveAlphabetsHandler.class);
@Override
public String process(String input) {
var inputWithoutAlphabets = new StringBuilder();
var isAlphabetic = (IntPredicate) Character::isAlphabetic;
input.chars()
.filter(isAlphabetic.negate())
.mapToObj(x -> (char) x)
.forEachOrdered(inputWithoutAlphabets::append);
var inputWithoutAlphabetsStr = inputWithoutAlphabets.toString();
LOGGER.info(
String.format(
"Current handler: %s, input is %s of type %s, output is %s, of type %s",
RemoveAlphabetsHandler.class, input,
String.class, inputWithoutAlphabetsStr, String.class
)
);
return inputWithoutAlphabetsStr;
}
} | 2,378 | 39.322034 | 140 | java |
java-design-patterns | java-design-patterns-master/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pipeline;
/**
* Main Pipeline class that initially sets the current handler. Processed output of the initial
* handler is then passed as the input to the next stage handlers.
*
* @param <I> the type of the input for the first stage handler
* @param <O> the final stage handler's output type
*/
class Pipeline<I, O> {
private final Handler<I, O> currentHandler;
Pipeline(Handler<I, O> currentHandler) {
this.currentHandler = currentHandler;
}
<K> Pipeline<I, K> addHandler(Handler<O, K> newHandler) {
return new Pipeline<>(input -> newHandler.process(currentHandler.process(input)));
}
O execute(I input) {
return currentHandler.process(input);
}
} | 1,989 | 39.612245 | 140 | java |
java-design-patterns | java-design-patterns-master/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pipeline;
import java.util.function.IntPredicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Stage handler that returns a new instance of String without the digit characters of the input
* string.
*/
class RemoveDigitsHandler implements Handler<String, String> {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoveDigitsHandler.class);
@Override
public String process(String input) {
var inputWithoutDigits = new StringBuilder();
var isDigit = (IntPredicate) Character::isDigit;
input.chars()
.filter(isDigit.negate())
.mapToObj(x -> (char) x)
.forEachOrdered(inputWithoutDigits::append);
var inputWithoutDigitsStr = inputWithoutDigits.toString();
LOGGER.info(
String.format(
"Current handler: %s, input is %s of type %s, output is %s, of type %s",
RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class
)
);
return inputWithoutDigitsStr;
}
} | 2,321 | 39.034483 | 140 | java |
java-design-patterns | java-design-patterns-master/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pipeline;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Stage handler that converts an input String to its char[] array counterpart.
*/
class ConvertToCharArrayHandler implements Handler<String, char[]> {
private static final Logger LOGGER = LoggerFactory.getLogger(ConvertToCharArrayHandler.class);
@Override
public char[] process(String input) {
var characters = input.toCharArray();
var string = Arrays.toString(characters);
LOGGER.info(
String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
ConvertToCharArrayHandler.class, input, String.class, string, Character[].class)
);
return characters;
}
}
| 2,037 | 39.76 | 140 | java |
java-design-patterns | java-design-patterns-master/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pipeline;
/**
* Forms a contract to all stage handlers to accept a certain type of input and return a processed
* output.
*
* @param <I> the input type of the handler
* @param <O> the processed output type of the handler
*/
interface Handler<I, O> {
O process(I input);
} | 1,585 | 43.055556 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/test/java/com/iluwatar/iterator/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.iterator;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application Test
*/
class AppTest {
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
} | 1,587 | 38.7 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator.bst;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
@TestInstance(Lifecycle.PER_CLASS)
class BstIteratorTest {
private TreeNode<Integer> nonEmptyRoot;
private TreeNode<Integer> emptyRoot;
@BeforeAll
void createTrees() {
nonEmptyRoot = new TreeNode<>(5);
nonEmptyRoot.insert(3);
nonEmptyRoot.insert(7);
nonEmptyRoot.insert(1);
nonEmptyRoot.insert(4);
nonEmptyRoot.insert(6);
emptyRoot = null;
}
@Test
void nextForEmptyTree() {
var iter = new BstIterator<>(emptyRoot);
assertThrows(NoSuchElementException.class, iter::next,
"next() should throw an IllegalStateException if hasNext() is false.");
}
@Test
void nextOverEntirePopulatedTree() {
var iter = new BstIterator<>(nonEmptyRoot);
assertEquals(Integer.valueOf(1), iter.next().getVal(), "First Node is 1.");
assertEquals(Integer.valueOf(3), iter.next().getVal(), "Second Node is 3.");
assertEquals(Integer.valueOf(4), iter.next().getVal(), "Third Node is 4.");
assertEquals(Integer.valueOf(5), iter.next().getVal(), "Fourth Node is 5.");
assertEquals(Integer.valueOf(6), iter.next().getVal(), "Fifth Node is 6.");
assertEquals(Integer.valueOf(7), iter.next().getVal(), "Sixth Node is 7.");
}
@Test
void hasNextForEmptyTree() {
var iter = new BstIterator<>(emptyRoot);
assertFalse(iter.hasNext(), "hasNext() should return false for empty tree.");
}
@Test
void hasNextForPopulatedTree() {
var iter = new BstIterator<>(nonEmptyRoot);
assertTrue(iter.hasNext(), "hasNext() should return true for populated tree.");
}
@Test
void nextAndHasNextOverEntirePopulatedTree() {
var iter = new BstIterator<>(nonEmptyRoot);
assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(1), iter.next().getVal(), "First Node is 1.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(3), iter.next().getVal(), "Second Node is 3.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(4), iter.next().getVal(), "Third Node is 4.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(5), iter.next().getVal(), "Fourth Node is 5.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(6), iter.next().getVal(), "Fifth Node is 6.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(7), iter.next().getVal(), "Sixth Node is 7.");
assertFalse(iter.hasNext(), "Iterator hasNext() should be false, end of tree.");
}
}
| 4,416 | 41.066667 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator.list;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/**
* Date: 12/14/15 - 2:58 PM
*
* @author Jeroen Meulemeester
*/
class TreasureChestTest {
/**
* Create a list of all expected items in the chest.
*
* @return The set of all expected items in the chest
*/
public static List<Object[]> dataProvider() {
return List.of(
new Object[]{new Item(ItemType.POTION, "Potion of courage")},
new Object[]{new Item(ItemType.RING, "Ring of shadows")},
new Object[]{new Item(ItemType.POTION, "Potion of wisdom")},
new Object[]{new Item(ItemType.POTION, "Potion of blood")},
new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")},
new Object[]{new Item(ItemType.POTION, "Potion of rust")},
new Object[]{new Item(ItemType.POTION, "Potion of healing")},
new Object[]{new Item(ItemType.RING, "Ring of armor")},
new Object[]{new Item(ItemType.WEAPON, "Steel halberd")},
new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")}
);
}
/**
* Test if the expected item can be retrieved from the chest using the {@link
* TreasureChestItemIterator}
*/
@ParameterizedTest
@MethodSource("dataProvider")
void testIterator(Item expectedItem) {
final var chest = new TreasureChest();
final var iterator = chest.iterator(expectedItem.getType());
assertNotNull(iterator);
while (iterator.hasNext()) {
final var item = iterator.next();
assertNotNull(item);
assertEquals(expectedItem.getType(), item.getType());
final var name = item.toString();
assertNotNull(name);
if (expectedItem.toString().equals(name)) {
return;
}
}
fail("Expected to find item [" + expectedItem + "] using iterator, but we didn't.");
}
/**
* Test if the expected item can be retrieved from the chest using the {@link
* TreasureChest#getItems()} method
*/
@ParameterizedTest
@MethodSource("dataProvider")
void testGetItems(Item expectedItem) throws Exception {
final var chest = new TreasureChest();
final var items = chest.getItems();
assertNotNull(items);
for (final var item : items) {
assertNotNull(item);
assertNotNull(item.getType());
assertNotNull(item.toString());
final var sameType = expectedItem.getType() == item.getType();
final var sameName = expectedItem.toString().equals(item.toString());
if (sameType && sameName) {
return;
}
}
fail("Expected to find item [" + expectedItem + "] in the item list, but we didn't.");
}
} | 4,169 | 34.948276 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/main/java/com/iluwatar/iterator/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.iterator;
import static com.iluwatar.iterator.list.ItemType.ANY;
import static com.iluwatar.iterator.list.ItemType.POTION;
import static com.iluwatar.iterator.list.ItemType.RING;
import static com.iluwatar.iterator.list.ItemType.WEAPON;
import com.iluwatar.iterator.bst.BstIterator;
import com.iluwatar.iterator.bst.TreeNode;
import com.iluwatar.iterator.list.ItemType;
import com.iluwatar.iterator.list.TreasureChest;
import lombok.extern.slf4j.Slf4j;
/**
* The Iterator pattern is a design pattern in which an iterator is used to traverse a container and
* access the container's elements. The Iterator pattern decouples algorithms from containers.
*
* <p>In this example the Iterator ({@link Iterator}) adds abstraction layer on top of a collection
* ({@link TreasureChest}). This way the collection can change its internal implementation without
* affecting its clients.
*/
@Slf4j
public class App {
private static final TreasureChest TREASURE_CHEST = new TreasureChest();
private static void demonstrateTreasureChestIteratorForType(ItemType itemType) {
LOGGER.info("------------------------");
LOGGER.info("Item Iterator for ItemType " + itemType + ": ");
var itemIterator = TREASURE_CHEST.iterator(itemType);
while (itemIterator.hasNext()) {
LOGGER.info(itemIterator.next().toString());
}
}
private static void demonstrateBstIterator() {
LOGGER.info("------------------------");
LOGGER.info("BST Iterator: ");
var root = buildIntegerBst();
var bstIterator = new BstIterator<>(root);
while (bstIterator.hasNext()) {
LOGGER.info("Next node: " + bstIterator.next().getVal());
}
}
private static TreeNode<Integer> buildIntegerBst() {
var root = new TreeNode<>(8);
root.insert(3);
root.insert(10);
root.insert(1);
root.insert(6);
root.insert(14);
root.insert(4);
root.insert(7);
root.insert(13);
return root;
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
demonstrateTreasureChestIteratorForType(RING);
demonstrateTreasureChestIteratorForType(POTION);
demonstrateTreasureChestIteratorForType(WEAPON);
demonstrateTreasureChestIteratorForType(ANY);
demonstrateBstIterator();
}
}
| 3,609 | 35.464646 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/main/java/com/iluwatar/iterator/Iterator.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator;
/**
* Iterator interface to be implemented by iterators over various data structures.
*
* @param <T> generically typed for various objects
*/
public interface Iterator<T> {
boolean hasNext();
T next();
}
| 1,530 | 39.289474 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator.bst;
/**
* TreeNode Class, representing one node in a Binary Search Tree. Allows for a generically typed
* value.
*
* @param <T> generically typed to accept various data types for the val property
*/
public class TreeNode<T extends Comparable<T>> {
private final T val;
private TreeNode<T> left;
private TreeNode<T> right;
/**
* Creates a TreeNode with a given value, and null children.
*
* @param val The value of the given node
*/
public TreeNode(T val) {
this.val = val;
this.left = null;
this.right = null;
}
public T getVal() {
return val;
}
public TreeNode<T> getLeft() {
return left;
}
private void setLeft(TreeNode<T> left) {
this.left = left;
}
public TreeNode<T> getRight() {
return right;
}
private void setRight(TreeNode<T> right) {
this.right = right;
}
/**
* Inserts new TreeNode based on a given value into the subtree represented by self.
*
* @param valToInsert The value to insert as a new TreeNode
*/
public void insert(T valToInsert) {
var parent = getParentNodeOfValueToBeInserted(valToInsert);
parent.insertNewChild(valToInsert);
}
/**
* Fetch the Parent TreeNode for a given value to insert into the BST.
*
* @param valToInsert Value of the new TreeNode to be inserted
* @return Parent TreeNode of `valToInsert`
*/
private TreeNode<T> getParentNodeOfValueToBeInserted(T valToInsert) {
TreeNode<T> parent = null;
var curr = this;
while (curr != null) {
parent = curr;
curr = curr.traverseOneLevelDown(valToInsert);
}
return parent;
}
/**
* Returns left or right child of self based on a value that would be inserted; maintaining the
* integrity of the BST.
*
* @param value The value of the TreeNode that would be inserted beneath self
* @return The child TreeNode of self which represents the subtree where `value` would be inserted
*/
private TreeNode<T> traverseOneLevelDown(T value) {
if (this.isGreaterThan(value)) {
return this.left;
}
return this.right;
}
/**
* Add a new Child TreeNode of given value to self. WARNING: This method is destructive (will
* overwrite existing tree structure, if any), and should be called only by this class's insert()
* method.
*
* @param valToInsert Value of the new TreeNode to be inserted
*/
private void insertNewChild(T valToInsert) {
if (this.isLessThanOrEqualTo(valToInsert)) {
this.setRight(new TreeNode<>(valToInsert));
} else {
this.setLeft(new TreeNode<>(valToInsert));
}
}
private boolean isGreaterThan(T val) {
return this.val.compareTo(val) > 0;
}
private boolean isLessThanOrEqualTo(T val) {
return this.val.compareTo(val) < 1;
}
@Override
public String toString() {
return val.toString();
}
}
| 4,177 | 28.631206 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator.bst;
import com.iluwatar.iterator.Iterator;
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
/**
* An in-order implementation of a BST Iterator. For example, given a BST with Integer values,
* expect to retrieve TreeNodes according to the Integer's natural ordering (1, 2, 3...)
*
* @param <T> This Iterator has been implemented with generic typing to allow for TreeNodes of
* different value types
*/
public class BstIterator<T extends Comparable<T>> implements Iterator<TreeNode<T>> {
private final ArrayDeque<TreeNode<T>> pathStack;
public BstIterator(TreeNode<T> root) {
pathStack = new ArrayDeque<>();
pushPathToNextSmallest(root);
}
/**
* This BstIterator manages to use O(h) extra space, where h is the height of the tree It achieves
* this by maintaining a stack of the nodes to handle (pushing all left nodes first), before
* handling self or right node.
*
* @param node TreeNode that acts as root of the subtree we're interested in.
*/
private void pushPathToNextSmallest(TreeNode<T> node) {
while (node != null) {
pathStack.push(node);
node = node.getLeft();
}
}
/**
* Checks if there exists next element.
*
* @return true if this iterator has a "next" element
*/
@Override
public boolean hasNext() {
return !pathStack.isEmpty();
}
/**
* Gets the next element.
*
* @return TreeNode next. The next element according to our in-order traversal of the given BST
* @throws NoSuchElementException if this iterator does not have a next element
*/
@Override
public TreeNode<T> next() throws NoSuchElementException {
if (pathStack.isEmpty()) {
throw new NoSuchElementException();
}
var next = pathStack.pop();
pushPathToNextSmallest(next.getRight());
return next;
}
}
| 3,161 | 34.931818 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator.list;
import com.iluwatar.iterator.Iterator;
/**
* TreasureChestItemIterator.
*/
public class TreasureChestItemIterator implements Iterator<Item> {
private final TreasureChest chest;
private int idx;
private final ItemType type;
/**
* Constructor.
*/
public TreasureChestItemIterator(TreasureChest chest, ItemType type) {
this.chest = chest;
this.type = type;
this.idx = -1;
}
@Override
public boolean hasNext() {
return findNextIdx() != -1;
}
@Override
public Item next() {
idx = findNextIdx();
if (idx != -1) {
return chest.getItems().get(idx);
}
return null;
}
private int findNextIdx() {
var items = chest.getItems();
var tempIdx = idx;
while (true) {
tempIdx++;
if (tempIdx >= items.size()) {
tempIdx = -1;
break;
}
if (type.equals(ItemType.ANY) || items.get(tempIdx).getType().equals(type)) {
break;
}
}
return tempIdx;
}
}
| 2,299 | 28.87013 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator.list;
/**
* ItemType enumeration.
*/
public enum ItemType {
ANY, WEAPON, RING, POTION
}
| 1,409 | 39.285714 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator.list;
import com.iluwatar.iterator.Iterator;
import java.util.ArrayList;
import java.util.List;
/**
* TreasureChest, the collection class.
*/
public class TreasureChest {
private final List<Item> items;
/**
* Constructor.
*/
public TreasureChest() {
items = List.of(
new Item(ItemType.POTION, "Potion of courage"),
new Item(ItemType.RING, "Ring of shadows"),
new Item(ItemType.POTION, "Potion of wisdom"),
new Item(ItemType.POTION, "Potion of blood"),
new Item(ItemType.WEAPON, "Sword of silver +1"),
new Item(ItemType.POTION, "Potion of rust"),
new Item(ItemType.POTION, "Potion of healing"),
new Item(ItemType.RING, "Ring of armor"),
new Item(ItemType.WEAPON, "Steel halberd"),
new Item(ItemType.WEAPON, "Dagger of poison"));
}
public Iterator<Item> iterator(ItemType itemType) {
return new TreasureChestItemIterator(this, itemType);
}
/**
* Get all items.
*/
public List<Item> getItems() {
return new ArrayList<>(items);
}
}
| 2,373 | 34.432836 | 140 | java |
java-design-patterns | java-design-patterns-master/iterator/src/main/java/com/iluwatar/iterator/list/Item.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator.list;
/**
* Item.
*/
public class Item {
private ItemType type;
private final String name;
public Item(ItemType type, String name) {
this.setType(type);
this.name = name;
}
@Override
public String toString() {
return name;
}
public ItemType getType() {
return type;
}
public final void setType(ItemType type) {
this.type = type;
}
}
| 1,697 | 31.037736 | 140 | java |
java-design-patterns | java-design-patterns-master/unit-of-work/src/test/java/com/iluwatar/unitofwork/ArmsDealerTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.unitofwork;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
/**
* tests {@link ArmsDealer}
*/
class ArmsDealerTest {
private final Weapon weapon1 = new Weapon(1, "battle ram");
private final Weapon weapon2 = new Weapon(1, "wooden lance");
private final Map<String, List<Weapon>> context = new HashMap<>();
private final WeaponDatabase weaponDatabase = mock(WeaponDatabase.class);
private final ArmsDealer armsDealer = new ArmsDealer(context, weaponDatabase);;
@Test
void shouldSaveNewStudentWithoutWritingToDb() {
armsDealer.registerNew(weapon1);
armsDealer.registerNew(weapon2);
assertEquals(2, context.get(UnitActions.INSERT.getActionValue()).size());
verifyNoMoreInteractions(weaponDatabase);
}
@Test
void shouldSaveDeletedStudentWithoutWritingToDb() {
armsDealer.registerDeleted(weapon1);
armsDealer.registerDeleted(weapon2);
assertEquals(2, context.get(UnitActions.DELETE.getActionValue()).size());
verifyNoMoreInteractions(weaponDatabase);
}
@Test
void shouldSaveModifiedStudentWithoutWritingToDb() {
armsDealer.registerModified(weapon1);
armsDealer.registerModified(weapon2);
assertEquals(2, context.get(UnitActions.MODIFY.getActionValue()).size());
verifyNoMoreInteractions(weaponDatabase);
}
@Test
void shouldSaveAllLocalChangesToDb() {
context.put(UnitActions.INSERT.getActionValue(), List.of(weapon1));
context.put(UnitActions.MODIFY.getActionValue(), List.of(weapon1));
context.put(UnitActions.DELETE.getActionValue(), List.of(weapon1));
armsDealer.commit();
verify(weaponDatabase, times(1)).insert(weapon1);
verify(weaponDatabase, times(1)).modify(weapon1);
verify(weaponDatabase, times(1)).delete(weapon1);
}
@Test
void shouldNotWriteToDbIfContextIsNull() {
var weaponRepository = new ArmsDealer(null, weaponDatabase);
weaponRepository.commit();
verifyNoMoreInteractions(weaponDatabase);
}
@Test
void shouldNotWriteToDbIfNothingToCommit() {
var weaponRepository = new ArmsDealer(new HashMap<>(), weaponDatabase);
weaponRepository.commit();
verifyNoMoreInteractions(weaponDatabase);
}
@Test
void shouldNotInsertToDbIfNoRegisteredStudentsToBeCommitted() {
context.put(UnitActions.MODIFY.getActionValue(), List.of(weapon1));
context.put(UnitActions.DELETE.getActionValue(), List.of(weapon1));
armsDealer.commit();
verify(weaponDatabase, never()).insert(weapon1);
}
@Test
void shouldNotModifyToDbIfNotRegisteredStudentsToBeCommitted() {
context.put(UnitActions.INSERT.getActionValue(), List.of(weapon1));
context.put(UnitActions.DELETE.getActionValue(), List.of(weapon1));
armsDealer.commit();
verify(weaponDatabase, never()).modify(weapon1);
}
@Test
void shouldNotDeleteFromDbIfNotRegisteredStudentsToBeCommitted() {
context.put(UnitActions.INSERT.getActionValue(), List.of(weapon1));
context.put(UnitActions.MODIFY.getActionValue(), List.of(weapon1));
armsDealer.commit();
verify(weaponDatabase, never()).delete(weapon1);
}
}
| 4,729 | 33.028777 | 140 | java |
java-design-patterns | java-design-patterns-master/unit-of-work/src/test/java/com/iluwatar/unitofwork/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.unitofwork;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
/**
* AppTest
*/
class AppTest {
@Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,569 | 37.292683 | 140 | java |
java-design-patterns | java-design-patterns-master/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitActions.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.unitofwork;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* Enum representing unit actions.
*/
@Getter
@RequiredArgsConstructor
public enum UnitActions {
INSERT("INSERT"),
DELETE("DELETE"),
MODIFY("MODIFY");
private final String actionValue;
}
| 1,581 | 36.666667 | 140 | java |
java-design-patterns | java-design-patterns-master/unit-of-work/src/main/java/com/iluwatar/unitofwork/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.unitofwork;
import java.util.HashMap;
import java.util.List;
/**
* {@link App} Application demonstrating unit of work pattern.
*/
public class App {
/**
* Program entry point.
*
* @param args no argument sent
*/
public static void main(String[] args) {
// create some weapons
var enchantedHammer = new Weapon(1, "enchanted hammer");
var brokenGreatSword = new Weapon(2, "broken great sword");
var silverTrident = new Weapon(3, "silver trident");
// create repository
var weaponRepository = new ArmsDealer(new HashMap<String, List<Weapon>>(),
new WeaponDatabase());
// perform operations on the weapons
weaponRepository.registerNew(enchantedHammer);
weaponRepository.registerModified(silverTrident);
weaponRepository.registerDeleted(brokenGreatSword);
weaponRepository.commit();
}
}
| 2,168 | 37.052632 | 140 | java |
java-design-patterns | java-design-patterns-master/unit-of-work/src/main/java/com/iluwatar/unitofwork/WeaponDatabase.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.unitofwork;
/**
* Act as database for weapon records.
*/
public class WeaponDatabase {
public void insert(Weapon weapon) {
//Some insert logic to DB
}
public void modify(Weapon weapon) {
//Some modify logic to DB
}
public void delete(Weapon weapon) {
//Some delete logic to DB
}
}
| 1,616 | 35.75 | 140 | java |
java-design-patterns | java-design-patterns-master/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitOfWork.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.unitofwork;
/**
* UnitOfWork interface.
*
* @param <T> Any generic entity
*/
public interface UnitOfWork<T> {
/**
* Any register new operation occurring on UnitOfWork is only going to be performed on commit.
*/
void registerNew(T entity);
/**
* Any register modify operation occurring on UnitOfWork is only going to be performed on commit.
*/
void registerModified(T entity);
/**
* Any register delete operation occurring on UnitOfWork is only going to be performed on commit.
*/
void registerDeleted(T entity);
/**
* All UnitOfWork operations batched together executed in commit only.
*/
void commit();
} | 1,960 | 35.314815 | 140 | java |
java-design-patterns | java-design-patterns-master/unit-of-work/src/main/java/com/iluwatar/unitofwork/Weapon.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.unitofwork;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* {@link Weapon} is an entity.
*/
@Getter
@RequiredArgsConstructor
public class Weapon {
private final Integer id;
private final String name;
}
| 1,535 | 37.4 | 140 | java |
java-design-patterns | java-design-patterns-master/unit-of-work/src/main/java/com/iluwatar/unitofwork/ArmsDealer.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.unitofwork;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* {@link ArmsDealer} Weapon repository that supports unit of work for weapons.
*/
@Slf4j
@RequiredArgsConstructor
public class ArmsDealer implements UnitOfWork<Weapon> {
private final Map<String, List<Weapon>> context;
private final WeaponDatabase weaponDatabase;
@Override
public void registerNew(Weapon weapon) {
LOGGER.info("Registering {} for insert in context.", weapon.getName());
register(weapon, UnitActions.INSERT.getActionValue());
}
@Override
public void registerModified(Weapon weapon) {
LOGGER.info("Registering {} for modify in context.", weapon.getName());
register(weapon, UnitActions.MODIFY.getActionValue());
}
@Override
public void registerDeleted(Weapon weapon) {
LOGGER.info("Registering {} for delete in context.", weapon.getName());
register(weapon, UnitActions.DELETE.getActionValue());
}
private void register(Weapon weapon, String operation) {
var weaponsToOperate = context.get(operation);
if (weaponsToOperate == null) {
weaponsToOperate = new ArrayList<>();
}
weaponsToOperate.add(weapon);
context.put(operation, weaponsToOperate);
}
/**
* All UnitOfWork operations are batched and executed together on commit only.
*/
@Override
public void commit() {
if (context == null || context.size() == 0) {
return;
}
LOGGER.info("Commit started");
if (context.containsKey(UnitActions.INSERT.getActionValue())) {
commitInsert();
}
if (context.containsKey(UnitActions.MODIFY.getActionValue())) {
commitModify();
}
if (context.containsKey(UnitActions.DELETE.getActionValue())) {
commitDelete();
}
LOGGER.info("Commit finished.");
}
private void commitInsert() {
var weaponsToBeInserted = context.get(UnitActions.INSERT.getActionValue());
for (var weapon : weaponsToBeInserted) {
LOGGER.info("Inserting a new weapon {} to sales rack.", weapon.getName());
weaponDatabase.insert(weapon);
}
}
private void commitModify() {
var modifiedWeapons = context.get(UnitActions.MODIFY.getActionValue());
for (var weapon : modifiedWeapons) {
LOGGER.info("Scheduling {} for modification work.", weapon.getName());
weaponDatabase.modify(weapon);
}
}
private void commitDelete() {
var deletedWeapons = context.get(UnitActions.DELETE.getActionValue());
for (var weapon : deletedWeapons) {
LOGGER.info("Scrapping {}.", weapon.getName());
weaponDatabase.delete(weapon);
}
}
}
| 3,993 | 33.136752 | 140 | java |
java-design-patterns | java-design-patterns-master/memento/src/test/java/com/iluwatar/memento/StarTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.memento;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* Date: 12/20/15 - 10:08 AM
*
* @author Jeroen Meulemeester
*/
class StarTest {
/**
* Verify the stages of a dying sun, without going back in time
*/
@Test
void testTimePasses() {
final var star = new Star(StarType.SUN, 1, 2);
assertEquals("sun age: 1 years mass: 2 tons", star.toString());
star.timePasses();
assertEquals("red giant age: 2 years mass: 16 tons", star.toString());
star.timePasses();
assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString());
star.timePasses();
assertEquals("supernova age: 8 years mass: 1024 tons", star.toString());
star.timePasses();
assertEquals("dead star age: 16 years mass: 8192 tons", star.toString());
star.timePasses();
assertEquals("dead star age: 64 years mass: 0 tons", star.toString());
star.timePasses();
assertEquals("dead star age: 256 years mass: 0 tons", star.toString());
}
/**
* Verify some stage of a dying sun, but go back in time to test the memento
*/
@Test
void testSetMemento() {
final var star = new Star(StarType.SUN, 1, 2);
final var firstMemento = star.getMemento();
assertEquals("sun age: 1 years mass: 2 tons", star.toString());
star.timePasses();
final var secondMemento = star.getMemento();
assertEquals("red giant age: 2 years mass: 16 tons", star.toString());
star.timePasses();
final var thirdMemento = star.getMemento();
assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString());
star.timePasses();
assertEquals("supernova age: 8 years mass: 1024 tons", star.toString());
star.setMemento(thirdMemento);
assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString());
star.timePasses();
assertEquals("supernova age: 8 years mass: 1024 tons", star.toString());
star.setMemento(secondMemento);
assertEquals("red giant age: 2 years mass: 16 tons", star.toString());
star.setMemento(firstMemento);
assertEquals("sun age: 1 years mass: 2 tons", star.toString());
}
}
| 3,471 | 33.72 | 140 | java |
java-design-patterns | java-design-patterns-master/memento/src/test/java/com/iluwatar/memento/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.memento;
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,575 | 37.439024 | 140 | java |
java-design-patterns | java-design-patterns-master/memento/src/main/java/com/iluwatar/memento/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.memento;
import java.util.Stack;
import lombok.extern.slf4j.Slf4j;
/**
* The Memento pattern is a software design pattern that provides the ability to restore an object
* to its previous state (undo via rollback).
*
* <p>The Memento pattern is implemented with three objects: the originator, a caretaker and a
* memento. The originator is some object that has an internal state. The caretaker is going to do
* something to the originator, but wants to be able to undo the change. The caretaker first asks
* the originator for a memento object. Then it does whatever operation (or sequence of operations)
* it was going to do. To roll back to the state before the operations, it returns the memento
* object to the originator. The memento object itself is an opaque object (one which the caretaker
* cannot, or should not, change). When using this pattern, care should be taken if the originator
* may change other objects or resources - the memento pattern operates on a single object.
*
* <p>In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that
* contains the state of the object. Later on the memento can be set back to the object restoring
* the state.
*/
@Slf4j
public class App {
/**
* Program entry point.
*/
public static void main(String[] args) {
var states = new Stack<StarMemento>();
var star = new Star(StarType.SUN, 10000000, 500000);
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
LOGGER.info(star.toString());
while (states.size() > 0) {
star.setMemento(states.pop());
LOGGER.info(star.toString());
}
}
}
| 3,248 | 41.75 | 140 | java |
java-design-patterns | java-design-patterns-master/memento/src/main/java/com/iluwatar/memento/StarType.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.memento;
/**
* StarType enumeration.
*/
public enum StarType {
SUN("sun"),
RED_GIANT("red giant"),
WHITE_DWARF("white dwarf"),
SUPERNOVA("supernova"),
DEAD("dead star");
private final String title;
StarType(String title) {
this.title = title;
}
@Override
public String toString() {
return title;
}
}
| 1,641 | 33.208333 | 140 | java |
java-design-patterns | java-design-patterns-master/memento/src/main/java/com/iluwatar/memento/StarMemento.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.memento;
/**
* External interface to memento.
*/
public interface StarMemento {
}
| 1,391 | 41.181818 | 140 | java |
java-design-patterns | java-design-patterns-master/memento/src/main/java/com/iluwatar/memento/Star.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.memento;
/**
* Star uses "mementos" to store and restore state.
*/
public class Star {
private StarType type;
private int ageYears;
private int massTons;
/**
* Constructor.
*/
public Star(StarType startType, int startAge, int startMass) {
this.type = startType;
this.ageYears = startAge;
this.massTons = startMass;
}
/**
* Makes time pass for the star.
*/
public void timePasses() {
ageYears *= 2;
massTons *= 8;
switch (type) {
case RED_GIANT -> type = StarType.WHITE_DWARF;
case SUN -> type = StarType.RED_GIANT;
case SUPERNOVA -> type = StarType.DEAD;
case WHITE_DWARF -> type = StarType.SUPERNOVA;
case DEAD -> {
ageYears *= 2;
massTons = 0;
}
default -> {
}
}
}
StarMemento getMemento() {
var state = new StarMementoInternal();
state.setAgeYears(ageYears);
state.setMassTons(massTons);
state.setType(type);
return state;
}
void setMemento(StarMemento memento) {
var state = (StarMementoInternal) memento;
this.type = state.getType();
this.ageYears = state.getAgeYears();
this.massTons = state.getMassTons();
}
@Override
public String toString() {
return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons);
}
/**
* StarMemento implementation.
*/
private static class StarMementoInternal implements StarMemento {
private StarType type;
private int ageYears;
private int massTons;
public StarType getType() {
return type;
}
public void setType(StarType type) {
this.type = type;
}
public int getAgeYears() {
return ageYears;
}
public void setAgeYears(int ageYears) {
this.ageYears = ageYears;
}
public int getMassTons() {
return massTons;
}
public void setMassTons(int massTons) {
this.massTons = massTons;
}
}
}
| 3,255 | 26.361345 | 140 | java |
java-design-patterns | java-design-patterns-master/thread-local-storage/src/test/java/ThreadLocalTest.java | import com.iluwatar.WithThreadLocal;
import com.iluwatar.WithoutThreadLocal;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadLocalTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
@BeforeEach
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@AfterEach
public void restoreStreams() {
System.setOut(originalOut);
}
@Test
public void withoutThreadLocal() throws InterruptedException {
int initialValue = 1234567890;
int threadSize = 2;
ExecutorService executor = Executors.newFixedThreadPool(threadSize);
WithoutThreadLocal threadLocal = new WithoutThreadLocal(initialValue);
for (int i = 0; i < threadSize; i++) {
executor.submit(threadLocal);
}
executor.awaitTermination(3, TimeUnit.SECONDS);
List<String> lines = outContent.toString().lines().toList();
//Matches only first thread, the second has changed by first thread value
Assertions.assertFalse(lines.stream()
.allMatch(line -> line.endsWith(String.valueOf(initialValue))));
}
@Test
public void withThreadLocal() throws InterruptedException {
int initialValue = 1234567890;
int threadSize = 2;
ExecutorService executor = Executors.newFixedThreadPool(threadSize);
WithThreadLocal threadLocal = new WithThreadLocal(ThreadLocal.withInitial(() -> initialValue));
for (int i = 0; i < threadSize; i++) {
executor.submit(threadLocal);
}
executor.awaitTermination(3, TimeUnit.SECONDS);
threadLocal.remove();
List<String> lines = outContent.toString().lines().toList();
Assertions.assertTrue(lines.stream()
.allMatch(line -> line.endsWith(String.valueOf(initialValue))));
}
}
| 2,275 | 32.470588 | 103 | java |
java-design-patterns | java-design-patterns-master/thread-local-storage/src/main/java/com/iluwatar/AbstractThreadLocalExample.java | package com.iluwatar;
import java.security.SecureRandom;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Class with main logic.
*/
public abstract class AbstractThreadLocalExample implements Runnable {
private static final SecureRandom RND = new SecureRandom();
private static final Integer RANDOM_THREAD_PARK_START = 1_000_000_000;
private static final Integer RANDOM_THREAD_PARK_END = 2_000_000_000;
@Override
public void run() {
long nanosToPark = RND.nextInt(RANDOM_THREAD_PARK_START, RANDOM_THREAD_PARK_END);
LockSupport.parkNanos(nanosToPark);
System.out.println(getThreadName() + ", before value changing: " + getter().get());
setter().accept(RND.nextInt());
}
/**
* Setter for our value.
*
* @return consumer
*/
protected abstract Consumer<Integer> setter();
/**
* Getter for our value.
*
* @return supplier
*/
protected abstract Supplier<Integer> getter();
private String getThreadName() {
return Thread.currentThread().getName();
}
}
| 1,100 | 23.466667 | 87 | java |
java-design-patterns | java-design-patterns-master/thread-local-storage/src/main/java/com/iluwatar/WithoutThreadLocal.java | package com.iluwatar;
import java.util.function.Consumer;
import java.util.function.Supplier;
import lombok.AllArgsConstructor;
/**
* Example of runnable without usage of {@link ThreadLocal}.
*/
@AllArgsConstructor
public class WithoutThreadLocal extends AbstractThreadLocalExample {
private Integer value;
@Override
protected Consumer<Integer> setter() {
return integer -> value = integer;
}
@Override
protected Supplier<Integer> getter() {
return () -> value;
}
}
| 495 | 18.84 | 68 | java |
java-design-patterns | java-design-patterns-master/thread-local-storage/src/main/java/com/iluwatar/WithThreadLocal.java | package com.iluwatar;
import java.util.function.Consumer;
import java.util.function.Supplier;
import lombok.AllArgsConstructor;
/**
* Example of runnable with use of {@link ThreadLocal}.
*/
@AllArgsConstructor
public class WithThreadLocal extends AbstractThreadLocalExample {
private final ThreadLocal<Integer> value;
/**
* Removes the current thread's value for this thread-local variable.
*/
public void remove() {
this.value.remove();
}
@Override
protected Consumer<Integer> setter() {
return value::set;
}
@Override
protected Supplier<Integer> getter() {
return value::get;
}
}
| 628 | 18.65625 | 71 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Tests for {@link DataBus}.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
class DataBusTest {
@Mock
private Member member;
@Mock
private DataType event;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void publishedEventIsReceivedBySubscribedMember() {
//given
final var dataBus = DataBus.getInstance();
dataBus.subscribe(member);
//when
dataBus.publish(event);
//then
then(member).should().accept(event);
}
@Test
void publishedEventIsNotReceivedByMemberAfterUnsubscribing() {
//given
final var dataBus = DataBus.getInstance();
dataBus.subscribe(member);
dataBus.unsubscribe(member);
//when
dataBus.publish(event);
//then
then(member).should(never()).accept(event);
}
}
| 2,346 | 29.480519 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.members;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.databus.data.MessageData;
import com.iluwatar.databus.data.StartingData;
import java.time.LocalDateTime;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link MessageCollectorMember}.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
class MessageCollectorMemberTest {
@Test
void collectMessageFromMessageData() {
//given
final var message = "message";
final var messageData = new MessageData(message);
final var collector = new MessageCollectorMember("collector");
//when
collector.accept(messageData);
//then
assertTrue(collector.getMessages().contains(message));
}
@Test
void collectIgnoresMessageFromOtherDataTypes() {
//given
final var startingData = new StartingData(LocalDateTime.now());
final var collector = new MessageCollectorMember("collector");
//when
collector.accept(startingData);
//then
assertEquals(0, collector.getMessages().size());
}
}
| 2,408 | 35.5 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.members;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.iluwatar.databus.DataBus;
import com.iluwatar.databus.data.MessageData;
import com.iluwatar.databus.data.StartingData;
import com.iluwatar.databus.data.StoppingData;
import java.time.LocalDateTime;
import java.time.Month;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link StatusMember}.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
class StatusMemberTest {
@Test
void statusRecordsTheStartTime() {
//given
final var startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9);
final var startingData = new StartingData(startTime);
final var statusMember = new StatusMember(1);
//when
statusMember.accept(startingData);
//then
assertEquals(startTime, statusMember.getStarted());
}
@Test
void statusRecordsTheStopTime() {
//given
final var stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12);
final var stoppingData = new StoppingData(stop);
stoppingData.setDataBus(DataBus.getInstance());
final var statusMember = new StatusMember(1);
//when
statusMember.accept(stoppingData);
//then
assertEquals(stop, statusMember.getStopped());
}
@Test
void statusIgnoresMessageData() {
//given
final var messageData = new MessageData("message");
final var statusMember = new StatusMember(1);
//when
statusMember.accept(messageData);
//then
assertNull(statusMember.getStarted());
assertNull(statusMember.getStopped());
}
}
| 2,906 | 34.024096 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/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.databus;
import com.iluwatar.databus.data.MessageData;
import com.iluwatar.databus.data.StartingData;
import com.iluwatar.databus.data.StoppingData;
import com.iluwatar.databus.members.MessageCollectorMember;
import com.iluwatar.databus.members.StatusMember;
import java.time.LocalDateTime;
/**
* The Data Bus pattern.
*
* @author Paul Campbell (pcampbell@kemitix.net)
* @see <a href="http://wiki.c2.com/?DataBusPattern">http://wiki.c2.com/?DataBusPattern</a>
* <p>The Data-Bus pattern provides a method where different parts of an application may
* pass messages between each other without needing to be aware of the other's existence.</p>
* <p>Similar to the {@code ObserverPattern}, members register themselves with the {@link
* DataBus} and may then receive each piece of data that is published to the Data-Bus. The
* member may react to any given message or not.</p>
* <p>It allows for Many-to-Many distribution of data, as there may be any number of
* publishers to a Data-Bus, and any number of members receiving the data. All members will
* receive the same data, the order each receives a given piece of data, is an implementation
* detail.</p>
* <p>Members may unsubscribe from the Data-Bus to stop receiving data.</p>
* <p>This example of the pattern implements a Synchronous Data-Bus, meaning that
* when data is published to the Data-Bus, the publish method will not return until all members
* have received the data and returned.</p>
* <p>The {@link DataBus} class is a Singleton.</p>
* <p>Members of the Data-Bus must implement the {@link Member} interface.</p>
* <p>Data to be published via the Data-Bus must implement the {@link DataType} interface.</p>
* <p>The {@code data} package contains example {@link DataType} implementations.</p>
* <p>The {@code members} package contains example {@link Member} implementations.</p>
* <p>The {@link StatusMember} demonstrates using the DataBus to publish a message
* to the Data-Bus when it receives a message.</p>
*/
class App {
public static void main(String[] args) {
final var bus = DataBus.getInstance();
bus.subscribe(new StatusMember(1));
bus.subscribe(new StatusMember(2));
final var foo = new MessageCollectorMember("Foo");
final var bar = new MessageCollectorMember("Bar");
bus.subscribe(foo);
bus.publish(StartingData.of(LocalDateTime.now()));
bus.publish(MessageData.of("Only Foo should see this"));
bus.subscribe(bar);
bus.publish(MessageData.of("Foo and Bar should see this"));
bus.unsubscribe(foo);
bus.publish(MessageData.of("Only Bar should see this"));
bus.publish(StoppingData.of(LocalDateTime.now()));
}
}
| 4,054 | 50.987179 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/DataType.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
The MIT License (MIT)
Copyright (c) 2016 Paul Campbell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.iluwatar.databus;
/**
* Events are sent via the Data-Bus.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
public interface DataType {
/**
* Returns the data-bus the event is being sent on.
*
* @return The data-bus
*/
DataBus getDataBus();
/**
* Set the data-bus the event will be sent on.
*
* @param dataBus The data-bus
*/
void setDataBus(DataBus dataBus);
}
| 2,788 | 37.205479 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
The MIT License (MIT)
Copyright (c) 2016 Paul Campbell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.iluwatar.databus;
import lombok.Getter;
import lombok.Setter;
/**
* Base for data to send via the Data-Bus.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
@Getter
@Setter
public class AbstractDataType implements DataType {
private DataBus dataBus;
}
| 2,648 | 39.753846 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/Member.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
The MIT License (MIT)
Copyright (c) 2016 Paul Campbell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.iluwatar.databus;
import java.util.function.Consumer;
/**
* Members receive events from the Data-Bus.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
public interface Member extends Consumer<DataType> {
void accept(DataType event);
}
| 2,631 | 41.451613 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/DataBus.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus;
import java.util.HashSet;
import java.util.Set;
/**
* The Data-Bus implementation.
*
* <p>This implementation uses a Singleton.</p>
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
public class DataBus {
private static final DataBus INSTANCE = new DataBus();
private final Set<Member> listeners = new HashSet<>();
public static DataBus getInstance() {
return INSTANCE;
}
/**
* Register a member with the data-bus to start receiving events.
*
* @param member The member to register
*/
public void subscribe(final Member member) {
this.listeners.add(member);
}
/**
* Deregister a member to stop receiving events.
*
* @param member The member to deregister
*/
public void unsubscribe(final Member member) {
this.listeners.remove(member);
}
/**
* Publish and event to all members.
*
* @param event The event
*/
public void publish(final DataType event) {
event.setDataBus(this);
listeners.forEach(listener -> listener.accept(event));
}
}
| 2,348 | 30.32 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.members;
import com.iluwatar.databus.DataType;
import com.iluwatar.databus.Member;
import com.iluwatar.databus.data.MessageData;
import com.iluwatar.databus.data.StartingData;
import com.iluwatar.databus.data.StoppingData;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Receiver of Data-Bus events.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
@Getter
@Slf4j
@RequiredArgsConstructor
public class StatusMember implements Member {
private final int id;
private LocalDateTime started;
private LocalDateTime stopped;
@Override
public void accept(final DataType data) {
if (data instanceof StartingData) {
handleEvent((StartingData) data);
} else if (data instanceof StoppingData) {
handleEvent((StoppingData) data);
}
}
private void handleEvent(StartingData data) {
started = data.getWhen();
LOGGER.info("Receiver {} sees application started at {}", id, started);
}
private void handleEvent(StoppingData data) {
stopped = data.getWhen();
LOGGER.info("Receiver {} sees application stopping at {}", id, stopped);
LOGGER.info("Receiver {} sending goodbye message", id);
data.getDataBus().publish(MessageData.of(String.format("Goodbye cruel world from #%d!", id)));
}
}
| 2,651 | 34.36 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.members;
import com.iluwatar.databus.DataType;
import com.iluwatar.databus.Member;
import com.iluwatar.databus.data.MessageData;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
/**
* Receiver of Data-Bus events that collects the messages from each {@link MessageData}.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
@Slf4j
public class MessageCollectorMember implements Member {
private final String name;
private final List<String> messages = new ArrayList<>();
public MessageCollectorMember(String name) {
this.name = name;
}
@Override
public void accept(final DataType data) {
if (data instanceof MessageData) {
handleEvent((MessageData) data);
}
}
private void handleEvent(MessageData data) {
LOGGER.info("{} sees message {}", name, data.getMessage());
messages.add(data.getMessage());
}
public List<String> getMessages() {
return List.copyOf(messages);
}
}
| 2,282 | 33.590909 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.data;
import com.iluwatar.databus.AbstractDataType;
import com.iluwatar.databus.DataType;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* An event raised when applications starts, containing the start time of the application.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
@RequiredArgsConstructor
@Getter
public class StartingData extends AbstractDataType {
private final LocalDateTime when;
public static DataType of(final LocalDateTime when) {
return new StartingData(when);
}
}
| 1,870 | 37.979167 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.data;
import com.iluwatar.databus.AbstractDataType;
import com.iluwatar.databus.DataType;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* An event raised when applications stops, containing the stop time of the application.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
@RequiredArgsConstructor
@Getter
public class StoppingData extends AbstractDataType {
private final LocalDateTime when;
public static DataType of(final LocalDateTime when) {
return new StoppingData(when);
}
}
| 1,868 | 37.9375 | 140 | java |
java-design-patterns | java-design-patterns-master/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.data;
import com.iluwatar.databus.AbstractDataType;
import com.iluwatar.databus.DataType;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* An event raised when a string message is sent.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
@Getter
@AllArgsConstructor
public class MessageData extends AbstractDataType {
private final String message;
public static DataType of(final String message) {
return new MessageData(message);
}
}
| 1,780 | 36.893617 | 140 | java |
java-design-patterns | java-design-patterns-master/data-transfer-object/src/test/java/com/iluwatar/datatransfer/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.datatransfer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
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,779 | 38.555556 | 140 | java |
java-design-patterns | java-design-patterns-master/data-transfer-object/src/test/java/com/iluwatar/datatransfer/customer/CustomerResourceTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.datatransfer.customer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import com.iluwatar.datatransfer.customer.CustomerDto;
import com.iluwatar.datatransfer.customer.CustomerResource;
import org.junit.jupiter.api.Test;
/**
* tests {@link CustomerResource}.
*/
class CustomerResourceTest {
@Test
void shouldGetAllCustomers() {
var customers = List.of(new CustomerDto("1", "Melody", "Yates"));
var customerResource = new CustomerResource(customers);
var allCustomers = customerResource.getAllCustomers();
assertEquals(1, allCustomers.size());
assertEquals("1", allCustomers.get(0).getId());
assertEquals("Melody", allCustomers.get(0).getFirstName());
assertEquals("Yates", allCustomers.get(0).getLastName());
}
@Test
void shouldSaveCustomer() {
var customer = new CustomerDto("1", "Rita", "Reynolds");
var customerResource = new CustomerResource(new ArrayList<>());
customerResource.save(customer);
var allCustomers = customerResource.getAllCustomers();
assertEquals("1", allCustomers.get(0).getId());
assertEquals("Rita", allCustomers.get(0).getFirstName());
assertEquals("Reynolds", allCustomers.get(0).getLastName());
}
@Test
void shouldDeleteCustomer() {
var customer = new CustomerDto("1", "Terry", "Nguyen");
var customers = new ArrayList<>(List.of(customer));
var customerResource = new CustomerResource(customers);
customerResource.delete(customer.getId());
var allCustomers = customerResource.getAllCustomers();
assertTrue(allCustomers.isEmpty());
}
} | 3,000 | 37.474359 | 140 | java |
java-design-patterns | java-design-patterns-master/data-transfer-object/src/main/java/com/iluwatar/datatransfer/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.datatransfer;
import com.iluwatar.datatransfer.customer.CustomerDto;
import com.iluwatar.datatransfer.customer.CustomerResource;
import com.iluwatar.datatransfer.product.Product;
import com.iluwatar.datatransfer.product.ProductDto;
import com.iluwatar.datatransfer.product.ProductResource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
/**
* The Data Transfer Object pattern is a design pattern in which an data transfer object is used to
* serve related information together to avoid multiple call for each piece of information.
*
* <p>In the first example, {@link App} is a customer details consumer i.e. client to
* request for customer details to server. {@link CustomerResource} act as server to serve customer
* information. {@link CustomerDto} is data transfer object to share customer information.
*
* <p>In the second example, {@link App} is a product details consumer i.e. client to
* request for product details to server. {@link ProductResource} acts as server to serve
* product information. {@link ProductDto} is data transfer object to share product information.
*
* <p>The pattern implementation is a bit different in each of the examples. The first can be
* thought as a traditional example and the second is an enum based implementation.
*
*/
@Slf4j
public class App {
/**
* Method as act client and request to server for details.
*
* @param args program argument.
*/
public static void main(String[] args) {
// Example 1: Customer DTO
var customerOne = new CustomerDto("1", "Kelly", "Brown");
var customerTwo = new CustomerDto("2", "Alfonso", "Bass");
var customers = new ArrayList<>(List.of(customerOne, customerTwo));
var customerResource = new CustomerResource(customers);
LOGGER.info("All customers:-");
var allCustomers = customerResource.getAllCustomers();
printCustomerDetails(allCustomers);
LOGGER.info("----------------------------------------------------------");
LOGGER.info("Deleting customer with id {1}");
customerResource.delete(customerOne.getId());
allCustomers = customerResource.getAllCustomers();
printCustomerDetails(allCustomers);
LOGGER.info("----------------------------------------------------------");
LOGGER.info("Adding customer three}");
var customerThree = new CustomerDto("3", "Lynda", "Blair");
customerResource.save(customerThree);
allCustomers = customerResource.getAllCustomers();
printCustomerDetails(allCustomers);
// Example 2: Product DTO
Product tv = Product.builder().id(1L).name("TV").supplier("Sony").price(1000D).cost(1090D).build();
Product microwave =
Product.builder()
.id(2L)
.name("microwave")
.supplier("Delonghi")
.price(1000D)
.cost(1090D).build();
Product refrigerator =
Product.builder()
.id(3L)
.name("refrigerator")
.supplier("Botsch")
.price(1000D)
.cost(1090D).build();
Product airConditioner =
Product.builder()
.id(4L)
.name("airConditioner")
.supplier("LG")
.price(1000D)
.cost(1090D).build();
List<Product> products =
new ArrayList<>(Arrays.asList(tv, microwave, refrigerator, airConditioner));
ProductResource productResource = new ProductResource(products);
LOGGER.info(
"####### List of products including sensitive data just for admins: \n {}",
Arrays.toString(productResource.getAllProductsForAdmin().toArray()));
LOGGER.info(
"####### List of products for customers: \n {}",
Arrays.toString(productResource.getAllProductsForCustomer().toArray()));
LOGGER.info("####### Going to save Sony PS5 ...");
ProductDto.Request.Create createProductRequestDto =
new ProductDto.Request.Create()
.setName("PS5")
.setCost(1000D)
.setPrice(1220D)
.setSupplier("Sony");
productResource.save(createProductRequestDto);
LOGGER.info(
"####### List of products after adding PS5: {}",
Arrays.toString(productResource.getProducts().toArray()));
}
private static void printCustomerDetails(List<CustomerDto> allCustomers) {
allCustomers.forEach(customer -> LOGGER.info(customer.getFirstName()));
}
}
| 5,731 | 39.652482 | 140 | java |
java-design-patterns | java-design-patterns-master/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.datatransfer.product;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* {@link Product} is a entity class for product entity. This class act as entity in the demo.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public final class Product {
private Long id;
private String name;
private Double price;
private Double cost;
private String supplier;
@Override
public String toString() {
return "Product{"
+ "id=" + id
+ ", name='" + name + '\''
+ ", price=" + price
+ ", cost=" + cost
+ ", supplier='" + supplier + '\''
+ '}';
}
}
| 2,005 | 34.192982 | 140 | java |
java-design-patterns | java-design-patterns-master/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.datatransfer.product;
import java.util.List;
/**
* The resource class which serves product information. This class act as server in the demo. Which
* has all product details.
*/
public class ProductResource {
private final List<Product> products;
/**
* Initialise resource with existing products.
*
* @param products initialize resource with existing products. Act as database.
*/
public ProductResource(final List<Product> products) {
this.products = products;
}
/**
* Get all products.
*
* @return : all products in list but in the scheme of private dto.
*/
public List<ProductDto.Response.Private> getAllProductsForAdmin() {
return products
.stream()
.map(p -> new ProductDto.Response.Private().setId(p.getId()).setName(p.getName())
.setCost(p.getCost())
.setPrice(p.getPrice()))
.toList();
}
/**
* Get all products.
*
* @return : all products in list but in the scheme of public dto.
*/
public List<ProductDto.Response.Public> getAllProductsForCustomer() {
return products
.stream()
.map(p -> new ProductDto.Response.Public().setId(p.getId()).setName(p.getName())
.setPrice(p.getPrice()))
.toList();
}
/**
* Save new product.
*
* @param createProductDto save new product to list.
*/
public void save(ProductDto.Request.Create createProductDto) {
products.add(Product.builder()
.id((long) (products.size() + 1))
.name(createProductDto.getName())
.supplier(createProductDto.getSupplier())
.price(createProductDto.getPrice())
.cost(createProductDto.getCost())
.build());
}
/**
* List of all products in an entity representation.
*
* @return : all the products entity that stored in the products list
*/
public List<Product> getProducts() {
return products;
}
}
| 3,293 | 33.3125 | 140 | java |
java-design-patterns | java-design-patterns-master/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductDto.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.datatransfer.product;
/**
* {@link ProductDto} is a data transfer object POJO.
* Instead of sending individual information to
* client We can send related information together in POJO.
*
* <p>Dto will not have any business logic in it.
*/
public enum ProductDto {
;
/**
* This is Request class which consist of Create or any other request DTO's
* you might want to use in your API.
*/
public enum Request {
;
/**
* This is Create dto class for requesting create new product.
*/
public static final class Create implements Name, Price, Cost, Supplier {
private String name;
private Double price;
private Double cost;
private String supplier;
@Override
public String getName() {
return name;
}
public Create setName(String name) {
this.name = name;
return this;
}
@Override
public Double getPrice() {
return price;
}
public Create setPrice(Double price) {
this.price = price;
return this;
}
@Override
public Double getCost() {
return cost;
}
public Create setCost(Double cost) {
this.cost = cost;
return this;
}
@Override
public String getSupplier() {
return supplier;
}
public Create setSupplier(String supplier) {
this.supplier = supplier;
return this;
}
}
}
/**
* This is Response class which consist of any response DTO's
* you might want to provide to your clients.
*/
public enum Response {
;
/**
* This is Public dto class for API response with the lowest data security.
*/
public static final class Public implements Id, Name, Price {
private Long id;
private String name;
private Double price;
@Override
public Long getId() {
return id;
}
public Public setId(Long id) {
this.id = id;
return this;
}
@Override
public String getName() {
return name;
}
public Public setName(String name) {
this.name = name;
return this;
}
@Override
public Double getPrice() {
return price;
}
public Public setPrice(Double price) {
this.price = price;
return this;
}
@Override
public String toString() {
return "Public{"
+ "id="
+ id
+ ", name='"
+ name
+ '\''
+ ", price="
+ price
+ '}';
}
}
/**
* This is Private dto class for API response with the highest data security.
*/
public static final class Private implements Id, Name, Price, Cost {
private Long id;
private String name;
private Double price;
private Double cost;
@Override
public Long getId() {
return id;
}
public Private setId(Long id) {
this.id = id;
return this;
}
@Override
public String getName() {
return name;
}
public Private setName(String name) {
this.name = name;
return this;
}
@Override
public Double getPrice() {
return price;
}
public Private setPrice(Double price) {
this.price = price;
return this;
}
@Override
public Double getCost() {
return cost;
}
public Private setCost(Double cost) {
this.cost = cost;
return this;
}
@Override
public String toString() {
return "Private{"
+
"id="
+ id
+
", name='"
+ name
+ '\''
+
", price="
+ price
+
", cost="
+ cost
+
'}';
}
}
}
/**
* Use this interface whenever you want to provide the product Id in your DTO.
*/
private interface Id {
/**
* Unique identifier of the product.
*
* @return : id of the product.
*/
Long getId();
}
/**
* Use this interface whenever you want to provide the product Name in your DTO.
*/
private interface Name {
/**
* The name of the product.
*
* @return : name of the product.
*/
String getName();
}
/**
* Use this interface whenever you want to provide the product Price in your DTO.
*/
private interface Price {
/**
* The amount we sell a product for.
* <b>This data is not confidential</b>
*
* @return : price of the product.
*/
Double getPrice();
}
/**
* Use this interface whenever you want to provide the product Cost in your DTO.
*/
private interface Cost {
/**
* The amount that it costs us to purchase this product
* For the amount we sell a product for, see the {@link Price Price} parameter.
* <b>This data is confidential</b>
*
* @return : cost of the product.
*/
Double getCost();
}
/**
* Use this interface whenever you want to provide the product Supplier in your DTO.
*/
private interface Supplier {
/**
* The name of supplier of the product or its manufacturer.
* <b>This data is highly confidential</b>
*
* @return : supplier of the product.
*/
String getSupplier();
}
}
| 6,790 | 22.49827 | 140 | java |
java-design-patterns | java-design-patterns-master/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerDto.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.datatransfer.customer;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* {@link CustomerDto} is a data transfer object POJO. Instead of sending individual information to
* client We can send related information together in POJO.
*
* <p>Dto will not have any business logic in it.
*/
@Getter
@RequiredArgsConstructor
public class CustomerDto {
private final String id;
private final String firstName;
private final String lastName;
}
| 1,769 | 39.227273 | 140 | java |
java-design-patterns | java-design-patterns-master/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerResource.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.datatransfer.customer;
import java.util.List;
import lombok.RequiredArgsConstructor;
/**
* The resource class which serves customer information. This class act as server in the demo. Which
* has all customer details.
*/
@RequiredArgsConstructor
public class CustomerResource {
private final List<CustomerDto> customers;
/**
* Get all customers.
*
* @return : all customers in list.
*/
public List<CustomerDto> getAllCustomers() {
return customers;
}
/**
* Save new customer.
*
* @param customer save new customer to list.
*/
public void save(CustomerDto customer) {
customers.add(customer);
}
/**
* Delete customer with given id.
*
* @param customerId delete customer with id {@code customerId}
*/
public void delete(String customerId) {
customers.removeIf(customer -> customer.getId().equals(customerId));
}
} | 2,191 | 33.25 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Test Game Application
*/
class ApplicationTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link Application#main(String[])}
* throws an exception.
*/
@Test
void shouldExecuteGameApplicationWithoutException() {
assertDoesNotThrow(() -> Application.main(new String[]{}));
}
} | 1,841 | 37.375 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/main/java/com/iluwatar/data/locality/Application.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality;
import com.iluwatar.data.locality.game.GameEntity;
import lombok.extern.slf4j.Slf4j;
/**
* Use the Data Locality pattern is when you have a performance problem. Take advantage of that to
* improve performance by increasing data locality — keeping data in contiguous memory in the order
* that you process it.
*
* <p>Example: Game loop that processes a bunch of game entities. Those entities are decomposed
* into different domains — AI, physics, and rendering — using the Component pattern.
*/
@Slf4j
public class Application {
private static final int NUM_ENTITIES = 5;
/**
* Start game loop with each component have NUM_ENTITIES instance.
*/
public static void main(String[] args) {
LOGGER.info("Start Game Application using Data-Locality pattern");
var gameEntity = new GameEntity(NUM_ENTITIES);
gameEntity.start();
gameEntity.update();
}
}
| 2,207 | 40.660377 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality.game;
import com.iluwatar.data.locality.game.component.manager.AiComponentManager;
import com.iluwatar.data.locality.game.component.manager.PhysicsComponentManager;
import com.iluwatar.data.locality.game.component.manager.RenderComponentManager;
import lombok.extern.slf4j.Slf4j;
/**
* The game Entity maintains a big array of pointers . Each spin of the game loop, we need to run
* the following:
*
* <p>Update the AI components.
*
* <p>Update the physics components for them.
*
* <p>Render them using their render components.
*/
@Slf4j
public class GameEntity {
private final AiComponentManager aiComponentManager;
private final PhysicsComponentManager physicsComponentManager;
private final RenderComponentManager renderComponentManager;
/**
* Init components.
*/
public GameEntity(int numEntities) {
LOGGER.info("Init Game with #Entity : {}", numEntities);
aiComponentManager = new AiComponentManager(numEntities);
physicsComponentManager = new PhysicsComponentManager(numEntities);
renderComponentManager = new RenderComponentManager(numEntities);
}
/**
* start all component.
*/
public void start() {
LOGGER.info("Start Game");
aiComponentManager.start();
physicsComponentManager.start();
renderComponentManager.start();
}
/**
* update all component.
*/
public void update() {
LOGGER.info("Update Game Component");
// Process AI.
aiComponentManager.update();
// update physics.
physicsComponentManager.update();
// Draw to screen.
renderComponentManager.render();
}
}
| 2,913 | 33.282353 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality.game.component;
import lombok.extern.slf4j.Slf4j;
/**
* Implementation of Render Component of Game.
*/
@Slf4j
public class RenderComponent implements Component {
@Override
public void update() {
// do nothing
}
/**
* render.
*/
@Override
public void render() {
LOGGER.info("Render Component");
}
}
| 1,651 | 33.416667 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality.game.component;
import lombok.extern.slf4j.Slf4j;
/**
* Implementation of Physics Component of Game.
*/
@Slf4j
public class PhysicsComponent implements Component {
/**
* update physics component of game.
*/
@Override
public void update() {
LOGGER.info("Update physics component of game");
}
@Override
public void render() {
// do nothing
}
}
| 1,695 | 34.333333 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality.game.component;
import lombok.extern.slf4j.Slf4j;
/**
* Implementation of AI component for Game.
*/
@Slf4j
public class AiComponent implements Component {
/**
* Update ai component.
*/
@Override
public void update() {
LOGGER.info("update AI component");
}
@Override
public void render() {
// Do Nothing.
}
}
| 1,661 | 33.625 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality.game.component;
/**
* Implement different Game component update and render process.
*/
public interface Component {
void update();
void render();
}
| 1,476 | 40.027778 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality.game.component.manager;
import com.iluwatar.data.locality.game.component.Component;
import com.iluwatar.data.locality.game.component.PhysicsComponent;
import java.util.stream.IntStream;
import lombok.extern.slf4j.Slf4j;
/**
* Physics component Manager for Game.
*/
@Slf4j
public class PhysicsComponentManager {
private static final int MAX_ENTITIES = 10000;
private final int numEntities;
private final Component[] physicsComponents = new PhysicsComponent[MAX_ENTITIES];
public PhysicsComponentManager(int numEntities) {
this.numEntities = numEntities;
}
/**
* Start physics component of Game.
*/
public void start() {
LOGGER.info("Start Physics Game Component ");
IntStream.range(0, numEntities).forEach(i -> physicsComponents[i] = new PhysicsComponent());
}
/**
* Update physics component of Game.
*/
public void update() {
LOGGER.info("Update Physics Game Component ");
// Process physics.
IntStream.range(0, numEntities)
.filter(i -> physicsComponents.length > i && physicsComponents[i] != null)
.forEach(i -> physicsComponents[i].update());
}
}
| 2,454 | 35.102941 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality.game.component.manager;
import com.iluwatar.data.locality.game.component.AiComponent;
import com.iluwatar.data.locality.game.component.Component;
import java.util.stream.IntStream;
import lombok.extern.slf4j.Slf4j;
/**
* AI component manager for Game.
*/
@Slf4j
public class AiComponentManager {
private static final int MAX_ENTITIES = 10000;
private final int numEntities;
private final Component[] aiComponents = new AiComponent[MAX_ENTITIES];
public AiComponentManager(int numEntities) {
this.numEntities = numEntities;
}
/**
* start AI component of Game.
*/
public void start() {
LOGGER.info("Start AI Game Component");
IntStream.range(0, numEntities).forEach(i -> aiComponents[i] = new AiComponent());
}
/**
* Update AI component of Game.
*/
public void update() {
LOGGER.info("Update AI Game Component");
IntStream.range(0, numEntities)
.filter(i -> aiComponents.length > i && aiComponents[i] != null)
.forEach(i -> aiComponents[i].update());
}
}
| 2,352 | 34.651515 | 140 | java |
java-design-patterns | java-design-patterns-master/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.data.locality.game.component.manager;
import com.iluwatar.data.locality.game.component.Component;
import com.iluwatar.data.locality.game.component.RenderComponent;
import java.util.stream.IntStream;
import lombok.extern.slf4j.Slf4j;
/**
* Render component manager for Game.
*/
@Slf4j
public class RenderComponentManager {
private static final int MAX_ENTITIES = 10000;
private final int numEntities;
private final Component[] renderComponents = new RenderComponent[MAX_ENTITIES];
public RenderComponentManager(int numEntities) {
this.numEntities = numEntities;
}
/**
* Start render component.
*/
public void start() {
LOGGER.info("Start Render Game Component ");
IntStream.range(0, numEntities).forEach(i -> renderComponents[i] = new RenderComponent());
}
/**
* render component.
*/
public void render() {
LOGGER.info("Update Render Game Component ");
// Process Render.
IntStream.range(0, numEntities)
.filter(i -> renderComponents.length > i && renderComponents[i] != null)
.forEach(i -> renderComponents[i].render());
}
}
| 2,415 | 34.529412 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/test/java/com/iluwatar/commander/CommanderTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import com.iluwatar.commander.employeehandle.EmployeeDatabase;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException;
import com.iluwatar.commander.exceptions.PaymentDetailsErrorException;
import com.iluwatar.commander.exceptions.ShippingNotPossibleException;
import com.iluwatar.commander.messagingservice.MessagingDatabase;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentDatabase;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.shippingservice.ShippingDatabase;
import com.iluwatar.commander.shippingservice.ShippingService;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
class CommanderTest {
private final int numOfRetries = 1;
private final long retryDuration = 1_000;
private long queueTime = 1_00;
private long queueTaskTime = 1_000;
private long paymentTime = 6_000;
private long messageTime = 5_000;
private long employeeTime = 2_000;
private static final List<Exception> exceptionList = new ArrayList<>();
static {
exceptionList.add(new DatabaseUnavailableException());
exceptionList.add(new ShippingNotPossibleException());
exceptionList.add(new ItemUnavailableException());
exceptionList.add(new PaymentDetailsErrorException());
exceptionList.add(new IllegalStateException());
}
private Commander buildCommanderObject() {
return buildCommanderObject(false);
}
private Commander buildCommanderObject(boolean nonPaymentException) {
PaymentService paymentService = new PaymentService
(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
ShippingService shippingService;
MessagingService messagingService;
if (nonPaymentException) {
shippingService = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException());
messagingService = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException());
} else {
shippingService = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException());
messagingService = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException());
}
var employeeHandle = new EmployeeHandle
(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb = new QueueDatabase
(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
return new Commander(employeeHandle, paymentService, shippingService,
messagingService, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
}
private Commander buildCommanderObjectVanilla() {
PaymentService paymentService = new PaymentService
(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var shippingService = new ShippingService(new ShippingDatabase());
var messagingService = new MessagingService(new MessagingDatabase());
var employeeHandle = new EmployeeHandle
(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb = new QueueDatabase
(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
return new Commander(employeeHandle, paymentService, shippingService,
messagingService, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
}
private Commander buildCommanderObjectUnknownException() {
PaymentService paymentService = new PaymentService
(new PaymentDatabase(), new IllegalStateException());
var shippingService = new ShippingService(new ShippingDatabase());
var messagingService = new MessagingService(new MessagingDatabase());
var employeeHandle = new EmployeeHandle
(new EmployeeDatabase(), new IllegalStateException());
var qdb = new QueueDatabase
(new DatabaseUnavailableException(), new IllegalStateException());
return new Commander(employeeHandle, paymentService, shippingService,
messagingService, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
}
private Commander buildCommanderObjectNoPaymentException1() {
PaymentService paymentService = new PaymentService
(new PaymentDatabase());
var shippingService = new ShippingService(new ShippingDatabase());
var messagingService = new MessagingService(new MessagingDatabase());
var employeeHandle = new EmployeeHandle
(new EmployeeDatabase(), new IllegalStateException());
var qdb = new QueueDatabase
(new DatabaseUnavailableException(), new IllegalStateException());
return new Commander(employeeHandle, paymentService, shippingService,
messagingService, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
}
private Commander buildCommanderObjectNoPaymentException2() {
PaymentService paymentService = new PaymentService
(new PaymentDatabase());
var shippingService = new ShippingService(new ShippingDatabase());
var messagingService = new MessagingService(new MessagingDatabase(), new IllegalStateException());
var employeeHandle = new EmployeeHandle
(new EmployeeDatabase(), new IllegalStateException());
var qdb = new QueueDatabase
(new DatabaseUnavailableException(), new IllegalStateException());
return new Commander(employeeHandle, paymentService, shippingService,
messagingService, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
}
private Commander buildCommanderObjectNoPaymentException3() {
PaymentService paymentService = new PaymentService
(new PaymentDatabase());
var shippingService = new ShippingService(new ShippingDatabase());
var messagingService = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException());
var employeeHandle = new EmployeeHandle
(new EmployeeDatabase(), new IllegalStateException());
var qdb = new QueueDatabase
(new DatabaseUnavailableException(), new IllegalStateException());
return new Commander(employeeHandle, paymentService, shippingService,
messagingService, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
}
private Commander buildCommanderObjectWithDB() {
return buildCommanderObjectWithoutDB(false, false, new IllegalStateException());
}
private Commander buildCommanderObjectWithDB(boolean includeException, boolean includeDBException, Exception e) {
var l = includeDBException ? new DatabaseUnavailableException() : e;
PaymentService paymentService;
ShippingService shippingService;
MessagingService messagingService;
EmployeeHandle employeeHandle;
if (includeException) {
paymentService = new PaymentService
(new PaymentDatabase(), l);
shippingService = new ShippingService(new ShippingDatabase(), l);
messagingService = new MessagingService(new MessagingDatabase(), l);
employeeHandle = new EmployeeHandle
(new EmployeeDatabase(), l);
} else {
paymentService = new PaymentService
(null);
shippingService = new ShippingService(null);
messagingService = new MessagingService(null);
employeeHandle = new EmployeeHandle
(null);
}
return new Commander(employeeHandle, paymentService, shippingService,
messagingService, null, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
}
private Commander buildCommanderObjectWithoutDB() {
return buildCommanderObjectWithoutDB(false, false, new IllegalStateException());
}
private Commander buildCommanderObjectWithoutDB(boolean includeException, boolean includeDBException, Exception e) {
var l = includeDBException ? new DatabaseUnavailableException() : e;
PaymentService paymentService;
ShippingService shippingService;
MessagingService messagingService;
EmployeeHandle employeeHandle;
if (includeException) {
paymentService = new PaymentService
(null, l);
shippingService = new ShippingService(null, l);
messagingService = new MessagingService(null, l);
employeeHandle = new EmployeeHandle
(null, l);
} else {
paymentService = new PaymentService
(null);
shippingService = new ShippingService(null);
messagingService = new MessagingService(null);
employeeHandle = new EmployeeHandle
(null);
}
return new Commander(employeeHandle, paymentService, shippingService,
messagingService, null, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
}
@Test
void testPlaceOrderVanilla() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
Commander c = buildCommanderObjectVanilla();
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrder() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
Commander c = buildCommanderObject(true);
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrder2() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
Commander c = buildCommanderObject(false);
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderNoException1() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
Commander c = buildCommanderObjectNoPaymentException1();
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderNoException2() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
Commander c = buildCommanderObjectNoPaymentException2();
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderNoException3() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
Commander c = buildCommanderObjectNoPaymentException3();
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderNoException4() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
Commander c = buildCommanderObjectNoPaymentException3();
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
c.placeOrder(order);
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderUnknownException() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
messageTime *= d;
employeeTime *= d;
queueTime *= d;
Commander c = buildCommanderObjectUnknownException();
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderShortDuration() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
messageTime *= d;
employeeTime *= d;
queueTime *= d;
Commander c = buildCommanderObject(true);
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderShortDuration2() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
messageTime *= d;
employeeTime *= d;
queueTime *= d;
Commander c = buildCommanderObject(false);
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderNoExceptionShortMsgDuration() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
messageTime *= d;
employeeTime *= d;
queueTime *= d;
Commander c = buildCommanderObjectNoPaymentException1();
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderNoExceptionShortQueueDuration() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
messageTime *= d;
employeeTime *= d;
queueTime *= d;
Commander c = buildCommanderObjectUnknownException();
var order = new Order(new User("K", "J"), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderWithDatabase() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
messageTime *= d;
employeeTime *= d;
queueTime *= d;
Commander c = buildCommanderObjectWithDB();
var order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderWithDatabaseAndExceptions() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
messageTime *= d;
employeeTime *= d;
queueTime *= d;
for (Exception e : exceptionList) {
Commander c = buildCommanderObjectWithDB(true, true, e);
var order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
c = buildCommanderObjectWithDB(true, false, e);
order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
c = buildCommanderObjectWithDB(false, false, e);
order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
c = buildCommanderObjectWithDB(false, true, e);
order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
}
@Test
void testPlaceOrderWithoutDatabase() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
messageTime *= d;
employeeTime *= d;
queueTime *= d;
Commander c = buildCommanderObjectWithoutDB();
var order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
@Test
void testPlaceOrderWithoutDatabaseAndExceptions() throws Exception {
for (double d = 0.1; d < 2; d = d + 0.1) {
paymentTime *= d;
queueTaskTime *= d;
messageTime *= d;
employeeTime *= d;
queueTime *= d;
for (Exception e : exceptionList) {
Commander c = buildCommanderObjectWithoutDB(true, true, e);
var order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
c = buildCommanderObjectWithoutDB(true, false, e);
order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
c = buildCommanderObjectWithoutDB(false, false, e);
order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
c = buildCommanderObjectWithoutDB(false, true, e);
order = new Order(new User("K", null), "pen", 1f);
for (Order.MessageSent ms : Order.MessageSent.values()) {
c.placeOrder(order);
assertFalse(StringUtils.isBlank(order.id));
}
}
}
}
}
| 23,914 | 42.56102 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/test/java/com/iluwatar/commander/RetryTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class RetryTest {
@Test
void performTest() {
Retry.Operation op = (l) -> {
if (!l.isEmpty()) {
throw l.remove(0);
}
};
Retry.HandleErrorIssue<Order> handleError = (o, e) -> {
};
var r1 = new Retry<>(op, handleError, 3, 30000,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
var r2 = new Retry<>(op, handleError, 3, 30000,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
var arr1 = new ArrayList<>(List.of(new ItemUnavailableException(), new DatabaseUnavailableException()));
try {
r1.perform(arr1, order);
} catch (Exception e1) {
e1.printStackTrace();
}
var arr2 = new ArrayList<>(List.of(new DatabaseUnavailableException(), new ItemUnavailableException()));
try {
r2.perform(arr2, order);
} catch (Exception e1) {
e1.printStackTrace();
}
//r1 stops at ItemUnavailableException, r2 retries because it encounters DatabaseUnavailableException
assertTrue(arr1.size() == 1 && arr2.size() == 0);
}
}
| 2,766 | 39.101449 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import com.iluwatar.commander.employeehandle.EmployeeDatabase;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException;
import com.iluwatar.commander.messagingservice.MessagingDatabase;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentDatabase;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.shippingservice.ShippingDatabase;
import com.iluwatar.commander.shippingservice.ShippingService;
/**
* AppQueueFailCases class looks at possible cases when Queue Database is available/unavailable.
*/
public class AppQueueFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void queuePaymentTaskDatabaseUnavailableCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void queueMessageTaskDatabaseUnavailableCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void queueEmployeeDbTaskDatabaseUnavailableCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void queueSuccessCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms =
new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var aqfc = new AppQueueFailCases();
//aqfc.queuePaymentTaskDatabaseUnavailableCase();
//aqfc.queueMessageTaskDatabaseUnavailableCase();
//aqfc.queueEmployeeDbTaskDatabaseUnavailableCase();
aqfc.queueSuccessCase();
}
}
| 7,650 | 50.695946 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import com.iluwatar.commander.employeehandle.EmployeeDatabase;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException;
import com.iluwatar.commander.messagingservice.MessagingDatabase;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentDatabase;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.shippingservice.ShippingDatabase;
import com.iluwatar.commander.shippingservice.ShippingService;
/**
* AppEmployeeDbFailCases class looks at possible cases when Employee handle service is
* available/unavailable.
*/
public class AppEmployeeDbFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void employeeDatabaseUnavailableCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void employeeDbSuccessCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var aefc = new AppEmployeeDbFailCases();
//aefc.employeeDatabaseUnavailableCase();
aefc.employeeDbSuccessCase();
}
}
| 4,800 | 47.01 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/Retry.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
/**
* Retry pattern.
*
* @param <T> is the type of object passed into HandleErrorIssue as a parameter.
*/
public class Retry<T> {
/**
* Operation Interface will define method to be implemented.
*/
public interface Operation {
void operation(List<Exception> list) throws Exception;
}
/**
* HandleErrorIssue defines how to handle errors.
*
* @param <T> is the type of object to be passed into the method as parameter.
*/
public interface HandleErrorIssue<T> {
void handleIssue(T obj, Exception e);
}
private static final SecureRandom RANDOM = new SecureRandom();
private final Operation op;
private final HandleErrorIssue<T> handleError;
private final int maxAttempts;
private final long maxDelay;
private final AtomicInteger attempts;
private final Predicate<Exception> test;
private final List<Exception> errors;
Retry(Operation op, HandleErrorIssue<T> handleError, int maxAttempts,
long maxDelay, Predicate<Exception>... ignoreTests) {
this.op = op;
this.handleError = handleError;
this.maxAttempts = maxAttempts;
this.maxDelay = maxDelay;
this.attempts = new AtomicInteger();
this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false);
this.errors = new ArrayList<>();
}
/**
* Performing the operation with retries.
*
* @param list is the exception list
* @param obj is the parameter to be passed into handleIsuue method
*/
public void perform(List<Exception> list, T obj) {
do {
try {
op.operation(list);
return;
} catch (Exception e) {
this.errors.add(e);
if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) {
this.handleError.handleIssue(obj, e);
return; //return here...dont go further
}
try {
long testDelay =
(long) Math.pow(2, this.attempts.intValue()) * 1000 + RANDOM.nextInt(1000);
long delay = Math.min(testDelay, this.maxDelay);
Thread.sleep(delay);
} catch (InterruptedException f) {
//ignore
}
}
} while (true);
}
}
| 3,690 | 31.955357 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/Database.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
/**
* Database abstract class is extended by all databases in our example. The add and get methods are
* used by the respective service to add to database or get from database.
*
* @param <T> T is the type of object being held by database.
*/
public abstract class Database<T> {
public abstract T add(T obj) throws DatabaseUnavailableException;
public abstract T get(String id) throws DatabaseUnavailableException;
}
| 1,817 | 43.341463 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/Service.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/**
* Service class is an abstract class extended by all services in this example. They all have a
* public receiveRequest method to receive requests, which could also contain details of the user
* other than the implementation details (though we are not doing that here) and updateDb method
* which adds to their respective databases. There is a method to generate transaction/request id
* for the transactions/requests, which are then sent back. These could be stored by the {@link
* Commander} class in a separate database for reference (though we are not doing that here).
*/
public abstract class Service {
protected final Database database;
public ArrayList<Exception> exceptionsList;
private static final SecureRandom RANDOM = new SecureRandom();
private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final Hashtable<String, Boolean> USED_IDS = new Hashtable<>();
protected Service(Database db, Exception... exc) {
this.database = db;
this.exceptionsList = new ArrayList<>(List.of(exc));
}
public abstract String receiveRequest(Object... parameters) throws DatabaseUnavailableException;
protected abstract String updateDb(Object... parameters) throws DatabaseUnavailableException;
protected String generateId() {
StringBuilder random = new StringBuilder();
while (random.length() < 12) { // length of the random string.
int index = (int) (RANDOM.nextFloat() * ALL_CHARS.length());
random.append(ALL_CHARS.charAt(index));
}
String id = random.toString();
if (USED_IDS.get(id) != null) {
while (USED_IDS.get(id)) {
id = generateId();
}
}
return id;
}
}
| 3,205 | 42.324324 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import com.iluwatar.commander.employeehandle.EmployeeDatabase;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.PaymentDetailsErrorException;
import com.iluwatar.commander.messagingservice.MessagingDatabase;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentDatabase;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.shippingservice.ShippingDatabase;
import com.iluwatar.commander.shippingservice.ShippingService;
/**
* AppPaymentFailCases class looks at possible cases when Payment service is available/unavailable.
*/
public class AppPaymentFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void paymentNotPossibleCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new PaymentDetailsErrorException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase(new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void paymentDatabaseUnavailableCase() throws Exception {
//rest is successful
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void paymentSuccessCase() throws Exception {
//goes to message after 2 retries maybe - rest is successful for now
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms =
new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase(new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var apfc = new AppPaymentFailCases();
//apfc.paymentNotPossibleCase();
//apfc.paymentDatabaseUnavailableCase();
apfc.paymentSuccessCase();
}
}
| 5,206 | 45.491071 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/Order.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
/**
* Order class holds details of the order.
*/
public class Order { //can store all transactions ids also
enum PaymentStatus {
NOT_DONE,
TRYING,
DONE
}
enum MessageSent {
NONE_SENT,
PAYMENT_FAIL,
PAYMENT_TRYING,
PAYMENT_SUCCESSFUL
}
final User user;
final String item;
public final String id;
final float price;
final long createdTime;
private static final SecureRandom RANDOM = new SecureRandom();
private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final Map<String, Boolean> USED_IDS = new HashMap<>();
PaymentStatus paid;
MessageSent messageSent; //to avoid sending error msg on page and text more than once
boolean addedToEmployeeHandle; //to avoid creating more to enqueue
Order(User user, String item, float price) {
this.createdTime = System.currentTimeMillis();
this.user = user;
this.item = item;
this.price = price;
String id = createUniqueId();
if (USED_IDS.get(id) != null) {
while (USED_IDS.get(id)) {
id = createUniqueId();
}
}
this.id = id;
USED_IDS.put(this.id, true);
this.paid = PaymentStatus.TRYING;
this.messageSent = MessageSent.NONE_SENT;
this.addedToEmployeeHandle = false;
}
private String createUniqueId() {
StringBuilder random = new StringBuilder();
while (random.length() < 12) { // length of the random string.
int index = (int) (RANDOM.nextFloat() * ALL_CHARS.length());
random.append(ALL_CHARS.charAt(index));
}
return random.toString();
}
}
| 2,991 | 32.244444 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import com.iluwatar.commander.employeehandle.EmployeeDatabase;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException;
import com.iluwatar.commander.exceptions.ShippingNotPossibleException;
import com.iluwatar.commander.messagingservice.MessagingDatabase;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentDatabase;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.shippingservice.ShippingDatabase;
import com.iluwatar.commander.shippingservice.ShippingService;
/**
* AppShippingFailCases class looks at possible cases when Shipping service is
* available/unavailable.
*/
public class AppShippingFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void itemUnavailableCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void shippingNotPossibleCase() throws Exception {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ShippingNotPossibleException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void shippingDatabaseUnavailableCase() throws Exception {
//rest is successful
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void shippingSuccessCase() throws Exception {
//goes to payment after 2 retries maybe - rest is successful for now
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var asfc = new AppShippingFailCases();
//asfc.itemUnavailableCase();
//asfc.shippingNotPossibleCase();
//asfc.shippingDatabaseUnavailableCase();
asfc.shippingSuccessCase();
}
}
| 5,813 | 45.142857 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import com.iluwatar.commander.employeehandle.EmployeeDatabase;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.messagingservice.MessagingDatabase;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentDatabase;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.shippingservice.ShippingDatabase;
import com.iluwatar.commander.shippingservice.ShippingService;
/**
* AppMessagingFailCases class looks at possible cases when Messaging service is
* available/unavailable.
*/
public class AppMessagingFailCases {
private final int numOfRetries = 3;
private final long retryDuration = 30000;
private final long queueTime = 240000; //4 mins
private final long queueTaskTime = 60000; //1 min
private final long paymentTime = 120000; //2 mins
private final long messageTime = 150000; //2.5 mins
private final long employeeTime = 240000; //4 mins
void messagingDatabaseUnavailableCasePaymentSuccess() throws Exception {
//rest is successful
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void messagingDatabaseUnavailableCasePaymentError() throws Exception {
//rest is successful
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void messagingDatabaseUnavailableCasePaymentFailure() throws Exception {
//rest is successful
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c =
new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, queueTime, queueTaskTime,
paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void messagingSuccessCase() throws Exception {
//done here
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration,
queueTime, queueTaskTime, paymentTime, messageTime, employeeTime);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws Exception {
var amfc = new AppMessagingFailCases();
//amfc.messagingDatabaseUnavailableCasePaymentSuccess();
//amfc.messagingDatabaseUnavailableCasePaymentError();
//amfc.messagingDatabaseUnavailableCasePaymentFailure();
amfc.messagingSuccessCase();
}
}
| 7,520 | 49.14 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/Commander.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import com.iluwatar.commander.Order.MessageSent;
import com.iluwatar.commander.Order.PaymentStatus;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException;
import com.iluwatar.commander.exceptions.PaymentDetailsErrorException;
import com.iluwatar.commander.exceptions.ShippingNotPossibleException;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.queue.QueueTask;
import com.iluwatar.commander.queue.QueueTask.TaskType;
import com.iluwatar.commander.shippingservice.ShippingService;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>Commander pattern is used to handle all issues that can come up while making a
* distributed transaction. The idea is to have a commander, which coordinates the execution of all
* instructions and ensures proper completion using retries and taking care of idempotence. By
* queueing instructions while they haven't been done, we can ensure a state of 'eventual
* consistency'.</p>
* <p>In our example, we have an e-commerce application. When the user places an order,
* the shipping service is intimated first. If the service does not respond for some reason, the
* order is not placed. If response is received, the commander then calls for the payment service to
* be intimated. If this fails, the shipping still takes place (order converted to COD) and the item
* is queued. If the queue is also found to be unavailable, the payment is noted to be not done and
* this is added to an employee database. Three types of messages are sent to the user - one, if
* payment succeeds; two, if payment fails definitively; and three, if payment fails in the first
* attempt. If the message is not sent, this is also queued and is added to employee db. We also
* have a time limit for each instruction to be completed, after which, the instruction is not
* executed, thereby ensuring that resources are not held for too long. In the rare occasion in
* which everything fails, an individual would have to step in to figure out how to solve the
* issue.</p>
* <p>We have abstract classes {@link Database} and {@link Service} which are extended
* by all the databases and services. Each service has a database to be updated, and receives
* request from an outside user (the {@link Commander} class here). There are 5 microservices -
* {@link ShippingService}, {@link PaymentService}, {@link MessagingService}, {@link EmployeeHandle}
* and a {@link QueueDatabase}. We use retries to execute any instruction using {@link Retry} class,
* and idempotence is ensured by going through some checks before making requests to services and
* making change in {@link Order} class fields if request succeeds or definitively fails. There are
* 5 classes - {@link AppShippingFailCases}, {@link AppPaymentFailCases}, {@link
* AppMessagingFailCases}, {@link AppQueueFailCases} and {@link AppEmployeeDbFailCases}, which look
* at the different scenarios that may be encountered during the placing of an order.</p>
*/
public class Commander {
private final QueueDatabase queue;
private final EmployeeHandle employeeDb;
private final PaymentService paymentService;
private final ShippingService shippingService;
private final MessagingService messagingService;
private int queueItems = 0; //keeping track here only so don't need access to queue db to get this
private final int numOfRetries;
private final long retryDuration;
private final long queueTime;
private final long queueTaskTime;
private final long paymentTime;
private final long messageTime;
private final long employeeTime;
private boolean finalSiteMsgShown;
private static final Logger LOG = LoggerFactory.getLogger(Commander.class);
//we could also have another db where it stores all orders
private static final String ORDER_ID = "Order {}";
private static final String REQUEST_ID = " request Id: {}";
private static final String ERROR_CONNECTING_MSG_SVC =
": Error in connecting to messaging service ";
private static final String TRY_CONNECTING_MSG_SVC =
": Trying to connect to messaging service..";
Commander(EmployeeHandle empDb, PaymentService paymentService, ShippingService shippingService,
MessagingService messagingService, QueueDatabase qdb, int numOfRetries,
long retryDuration, long queueTime, long queueTaskTime, long paymentTime,
long messageTime, long employeeTime) {
this.paymentService = paymentService;
this.shippingService = shippingService;
this.messagingService = messagingService;
this.employeeDb = empDb;
this.queue = qdb;
this.numOfRetries = numOfRetries;
this.retryDuration = retryDuration;
this.queueTime = queueTime;
this.queueTaskTime = queueTaskTime;
this.paymentTime = paymentTime;
this.messageTime = messageTime;
this.employeeTime = employeeTime;
this.finalSiteMsgShown = false;
}
void placeOrder(Order order) throws Exception {
sendShippingRequest(order);
}
private void sendShippingRequest(Order order) throws Exception {
var list = shippingService.exceptionsList;
Retry.Operation op = (l) -> {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug(ORDER_ID + ": Error in connecting to shipping service, "
+ "trying again..", order.id);
} else {
LOG.debug(ORDER_ID + ": Error in creating shipping request..", order.id);
}
throw l.remove(0);
}
String transactionId = shippingService.receiveRequest(order.item, order.user.address);
//could save this transaction id in a db too
LOG.info(ORDER_ID + ": Shipping placed successfully, transaction id: {}",
order.id, transactionId);
LOG.info("Order has been placed and will be shipped to you. Please wait while we make your"
+ " payment... ");
sendPaymentRequest(order);
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (ShippingNotPossibleException.class.isAssignableFrom(err.getClass())) {
LOG.info("Shipping is currently not possible to your address. We are working on the problem"
+ " and will get back to you asap.");
finalSiteMsgShown = true;
LOG.info(ORDER_ID + ": Shipping not possible to address, trying to add problem "
+ "to employee db..", order.id);
employeeHandleIssue(o);
} else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) {
LOG.info("This item is currently unavailable. We will inform you as soon as the item "
+ "becomes available again.");
finalSiteMsgShown = true;
LOG.info(ORDER_ID + ": Item {}" + " unavailable, trying to add "
+ "problem to employee handle..", order.id, order.item);
employeeHandleIssue(o);
} else {
LOG.info("Sorry, there was a problem in creating your order. Please try later.");
LOG.error(ORDER_ID + ": Shipping service unavailable, order not placed..", order.id);
finalSiteMsgShown = true;
}
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
r.perform(list, order);
}
private void sendPaymentRequest(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.paymentTime) {
if (order.paid.equals(PaymentStatus.TRYING)) {
order.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(order);
LOG.error(ORDER_ID + ": Payment time for order over, failed and returning..", order.id);
} //if succeeded or failed, would have been dequeued, no attempt to make payment
return;
}
var list = paymentService.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug(ORDER_ID + ": Error in connecting to payment service,"
+ " trying again..", order.id);
} else {
LOG.debug(ORDER_ID + ": Error in creating payment request..", order.id);
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.TRYING)) {
var transactionId = paymentService.receiveRequest(order.price);
order.paid = PaymentStatus.DONE;
LOG.info(ORDER_ID + ": Payment successful, transaction Id: {}",
order.id, transactionId);
if (!finalSiteMsgShown) {
LOG.info("Payment made successfully, thank you for shopping with us!!");
finalSiteMsgShown = true;
}
sendSuccessMessage(order);
}
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. Your account/card details "
+ "may have been incorrect. "
+ "Meanwhile, your order has been converted to COD and will be shipped.");
finalSiteMsgShown = true;
}
LOG.error(ORDER_ID + ": Payment details incorrect, failed..", order.id);
o.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(o);
} else {
if (o.messageSent.equals(MessageSent.NONE_SENT)) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. We are on it, and will get back to you "
+ "asap. Don't worry, your order has been placed and will be shipped.");
finalSiteMsgShown = true;
}
LOG.warn(ORDER_ID + ": Payment error, going to queue..", order.id);
sendPaymentPossibleErrorMsg(o);
}
if (o.paid.equals(PaymentStatus.TRYING) && System
.currentTimeMillis() - o.createdTime < paymentTime) {
var qt = new QueueTask(o, TaskType.PAYMENT, -1);
updateQueue(qt);
}
}
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void updateQueue(QueueTask qt) {
if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) {
// since payment time is lesser than queuetime it would have already failed..
// additional check not needed
LOG.trace(ORDER_ID + ": Queue time for order over, failed..", qt.order.id);
return;
} else if (qt.taskType.equals(TaskType.PAYMENT) && !qt.order.paid.equals(PaymentStatus.TRYING)
|| qt.taskType.equals(TaskType.MESSAGING) && (qt.messageType == 1
&& !qt.order.messageSent.equals(MessageSent.NONE_SENT)
|| qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL)
|| qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL))
|| qt.taskType.equals(TaskType.EMPLOYEE_DB) && qt.order.addedToEmployeeHandle) {
LOG.trace(ORDER_ID + ": Not queueing task since task already done..", qt.order.id);
return;
}
var list = queue.exceptionsList;
Thread t = new Thread(() -> {
Retry.Operation op = (list1) -> {
if (!list1.isEmpty()) {
LOG.warn(ORDER_ID + ": Error in connecting to queue db, trying again..", qt.order.id);
throw list1.remove(0);
}
queue.add(qt);
queueItems++;
LOG.info(ORDER_ID + ": {}" + " task enqueued..", qt.order.id, qt.getType());
tryDoingTasksInQueue();
};
Retry.HandleErrorIssue<QueueTask> handleError = (qt1, err) -> {
if (qt1.taskType.equals(TaskType.PAYMENT)) {
qt1.order.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(qt1.order);
LOG.error(ORDER_ID + ": Unable to enqueue payment task,"
+ " payment failed..", qt1.order.id);
}
LOG.error(ORDER_ID + ": Unable to enqueue task of type {}"
+ ", trying to add to employee handle..", qt1.order.id, qt1.getType());
employeeHandleIssue(qt1.order);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, qt);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void tryDoingTasksInQueue() { //commander controls operations done to queue
var list = queue.exceptionsList;
var t2 = new Thread(() -> {
Retry.Operation op = (list1) -> {
if (!list1.isEmpty()) {
LOG.warn("Error in accessing queue db to do tasks, trying again..");
throw list1.remove(0);
}
doTasksInQueue();
};
Retry.HandleErrorIssue<QueueTask> handleError = (o, err) -> {
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, null);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t2.start();
}
private void tryDequeue() {
var list = queue.exceptionsList;
var t3 = new Thread(() -> {
Retry.Operation op = (list1) -> {
if (!list1.isEmpty()) {
LOG.warn("Error in accessing queue db to dequeue task, trying again..");
throw list1.remove(0);
}
queue.dequeue();
queueItems--;
};
Retry.HandleErrorIssue<QueueTask> handleError = (o, err) -> {
};
var r = new Retry<QueueTask>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, null);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t3.start();
}
private void sendSuccessMessage(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.messageTime) {
LOG.trace(ORDER_ID + ": Message time for order over, returning..", order.id);
return;
}
var list = messagingService.exceptionsList;
Thread t = new Thread(() -> {
Retry.Operation op = handleSuccessMessageRetryOperation(order);
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
handleSuccessMessageErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void handleSuccessMessageErrorIssue(Order order, Order o) {
if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent
.equals(MessageSent.PAYMENT_TRYING))
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.MESSAGING, 2);
updateQueue(qt);
LOG.info(ORDER_ID + ": Error in sending Payment Success message, trying to"
+ " queue task and add to employee handle..", order.id);
employeeHandleIssue(order);
}
}
private Retry.Operation handleSuccessMessageRetryOperation(Order order) {
return (l) -> {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC
+ "(Payment Success msg), trying again..", order.id);
} else {
LOG.debug(ORDER_ID + ": Error in creating Payment Success"
+ " messaging request..", order.id);
}
throw l.remove(0);
}
if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL)
&& !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
var requestId = messagingService.receiveRequest(2);
order.messageSent = MessageSent.PAYMENT_SUCCESSFUL;
LOG.info(ORDER_ID + ": Payment Success message sent,"
+ REQUEST_ID, order.id, requestId);
}
};
}
private void sendPaymentFailureMessage(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.messageTime) {
LOG.trace(ORDER_ID + ": Message time for order over, returning..", order.id);
return;
}
var list = messagingService.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
handlePaymentFailureRetryOperation(order, l);
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
handlePaymentErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void handlePaymentErrorIssue(Order order, Order o) {
if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent
.equals(MessageSent.PAYMENT_TRYING))
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.MESSAGING, 0);
updateQueue(qt);
LOG.warn(ORDER_ID + ": Error in sending Payment Failure message, "
+ "trying to queue task and add to employee handle..", order.id);
employeeHandleIssue(o);
}
}
private void handlePaymentFailureRetryOperation(Order order, List<Exception> l) throws Exception {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC
+ "(Payment Failure msg), trying again..", order.id);
} else {
LOG.debug(ORDER_ID + ": Error in creating Payment Failure"
+ " message request..", order.id);
}
throw l.remove(0);
}
if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL)
&& !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
var requestId = messagingService.receiveRequest(0);
order.messageSent = MessageSent.PAYMENT_FAIL;
LOG.info(ORDER_ID + ": Payment Failure message sent successfully,"
+ REQUEST_ID, order.id, requestId);
}
}
private void sendPaymentPossibleErrorMsg(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.messageTime) {
LOG.trace("Message time for order over, returning..");
return;
}
var list = messagingService.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
handlePaymentPossibleErrorMsgRetryOperation(order, l);
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
handlePaymentPossibleErrorMsgErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void handlePaymentPossibleErrorMsgErrorIssue(Order order, Order o) {
if (o.messageSent.equals(MessageSent.NONE_SENT) && order.paid
.equals(PaymentStatus.TRYING)
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.MESSAGING, 1);
updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in sending Payment Error message, "
+ "trying to queue task and add to employee handle..");
employeeHandleIssue(o);
}
}
private void handlePaymentPossibleErrorMsgRetryOperation(Order order, List<Exception> l)
throws Exception {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC
+ "(Payment Error msg), trying again..", order.id);
} else {
LOG.debug(ORDER_ID + ": Error in creating Payment Error"
+ " messaging request..", order.id);
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.TRYING) && order.messageSent
.equals(MessageSent.NONE_SENT)) {
var requestId = messagingService.receiveRequest(1);
order.messageSent = MessageSent.PAYMENT_TRYING;
LOG.info(ORDER_ID + ": Payment Error message sent successfully,"
+ REQUEST_ID, order.id, requestId);
}
}
private void employeeHandleIssue(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.employeeTime) {
LOG.trace(ORDER_ID + ": Employee handle time for order over, returning..", order.id);
return;
}
var list = employeeDb.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
if (!l.isEmpty()) {
LOG.warn(ORDER_ID + ": Error in connecting to employee handle,"
+ " trying again..", order.id);
throw l.remove(0);
}
if (!order.addedToEmployeeHandle) {
employeeDb.receiveRequest(order);
order.addedToEmployeeHandle = true;
LOG.info(ORDER_ID + ": Added order to employee database", order.id);
}
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (!o.addedToEmployeeHandle && System
.currentTimeMillis() - order.createdTime < employeeTime) {
var qt = new QueueTask(order, TaskType.EMPLOYEE_DB, -1);
updateQueue(qt);
LOG.warn(ORDER_ID + ": Error in adding to employee db,"
+ " trying to queue task..", order.id);
}
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void doTasksInQueue() throws Exception {
if (queueItems != 0) {
var qt = queue.peek(); //this should probably be cloned here
//this is why we have retry for doTasksInQueue
LOG.trace(ORDER_ID + ": Started doing task of type {}", qt.order.id, qt.getType());
if (qt.getFirstAttemptTime() == -1) {
qt.setFirstAttemptTime(System.currentTimeMillis());
}
if (System.currentTimeMillis() - qt.getFirstAttemptTime() >= queueTaskTime) {
tryDequeue();
LOG.trace(ORDER_ID + ": This queue task of type {}"
+ " does not need to be done anymore (timeout), dequeue..", qt.order.id, qt.getType());
} else {
if (qt.taskType.equals(TaskType.PAYMENT)) {
if (!qt.order.paid.equals(PaymentStatus.TRYING)) {
tryDequeue();
LOG.trace(ORDER_ID + ": This payment task already done, dequeueing..", qt.order.id);
} else {
sendPaymentRequest(qt.order);
LOG.debug(ORDER_ID + ": Trying to connect to payment service..", qt.order.id);
}
} else if (qt.taskType.equals(TaskType.MESSAGING)) {
if (qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL)
|| qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
tryDequeue();
LOG.trace(ORDER_ID + ": This messaging task already done, dequeue..", qt.order.id);
} else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NONE_SENT)
|| !qt.order.paid.equals(PaymentStatus.TRYING))) {
tryDequeue();
LOG.trace(ORDER_ID + ": This messaging task does not need to be done,"
+ " dequeue..", qt.order.id);
} else if (qt.messageType == 0) {
sendPaymentFailureMessage(qt.order);
LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id);
} else if (qt.messageType == 1) {
sendPaymentPossibleErrorMsg(qt.order);
LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id);
} else if (qt.messageType == 2) {
sendSuccessMessage(qt.order);
LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id);
}
} else if (qt.taskType.equals(TaskType.EMPLOYEE_DB)) {
if (qt.order.addedToEmployeeHandle) {
tryDequeue();
LOG.trace(ORDER_ID + ": This employee handle task already done,"
+ " dequeue..", qt.order.id);
} else {
employeeHandleIssue(qt.order);
LOG.debug(ORDER_ID + ": Trying to connect to employee handle..", qt.order.id);
}
}
}
}
if (queueItems == 0) {
LOG.trace("Queue is empty, returning..");
} else {
Thread.sleep(queueTaskTime / 3);
tryDoingTasksInQueue();
}
}
}
| 26,807 | 43.092105 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/User.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander;
import lombok.AllArgsConstructor;
/**
* User class contains details of user who places order.
*/
@AllArgsConstructor
public class User {
String name;
String address;
}
| 1,492 | 39.351351 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.paymentservice;
import com.iluwatar.commander.Database;
import com.iluwatar.commander.paymentservice.PaymentService.PaymentRequest;
import java.util.Hashtable;
import java.util.Map;
/**
* PaymentDatabase is where the PaymentRequest is added, along with details.
*/
public class PaymentDatabase extends Database<PaymentRequest> {
//0-fail, 1-error, 2-success
private final Map<String, PaymentRequest> data = new Hashtable<>();
@Override
public PaymentRequest add(PaymentRequest r) {
return data.put(r.transactionId, r);
}
@Override
public PaymentRequest get(String requestId) {
return data.get(requestId);
}
}
| 1,956 | 37.372549 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.paymentservice;
import com.iluwatar.commander.Service;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import lombok.RequiredArgsConstructor;
/**
* The PaymentService class receives request from the {@link com.iluwatar.commander.Commander} and
* adds to the {@link PaymentDatabase}.
*/
public class PaymentService extends Service {
@RequiredArgsConstructor
static class PaymentRequest {
final String transactionId;
final float payment;
boolean paid;
}
public PaymentService(PaymentDatabase db, Exception... exc) {
super(db, exc);
}
/**
* Public method which will receive request from {@link com.iluwatar.commander.Commander}.
*/
public String receiveRequest(Object... parameters) throws DatabaseUnavailableException {
//it could also be sending a userid, payment details here or something, not added here
var id = generateId();
var req = new PaymentRequest(id, (float) parameters[0]);
return updateDb(req);
}
protected String updateDb(Object... parameters) throws DatabaseUnavailableException {
var req = (PaymentRequest) parameters[0];
if (database.get(req.transactionId) == null || !req.paid) {
database.add(req);
req.paid = true;
return req.transactionId;
}
return null;
}
}
| 2,619 | 36.428571 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.messagingservice;
import com.iluwatar.commander.Service;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* The MessagingService is used to send messages to user regarding their order and payment status.
* In case an error is encountered in payment and this service is found to be unavailable, the order
* is added to the {@link com.iluwatar.commander.employeehandle.EmployeeDatabase}.
*/
@Slf4j
public class MessagingService extends Service {
enum MessageToSend {
PAYMENT_FAIL,
PAYMENT_TRYING,
PAYMENT_SUCCESSFUL
}
@RequiredArgsConstructor
static class MessageRequest {
final String reqId;
final MessageToSend msg;
}
public MessagingService(MessagingDatabase db, Exception... exc) {
super(db, exc);
}
/**
* Public method which will receive request from {@link com.iluwatar.commander.Commander}.
*/
public String receiveRequest(Object... parameters) throws DatabaseUnavailableException {
var messageToSend = (int) parameters[0];
var id = generateId();
MessageToSend msg;
if (messageToSend == 0) {
msg = MessageToSend.PAYMENT_FAIL;
} else if (messageToSend == 1) {
msg = MessageToSend.PAYMENT_TRYING;
} else { //messageToSend == 2
msg = MessageToSend.PAYMENT_SUCCESSFUL;
}
var req = new MessageRequest(id, msg);
return updateDb(req);
}
protected String updateDb(Object... parameters) throws DatabaseUnavailableException {
var req = (MessageRequest) parameters[0];
if (this.database.get(req.reqId) == null) { //idempotence, in case db fails here
database.add(req); //if successful:
LOGGER.info(sendMessage(req.msg));
return req.reqId;
}
return null;
}
String sendMessage(MessageToSend m) {
if (m.equals(MessageToSend.PAYMENT_SUCCESSFUL)) {
return "Msg: Your order has been placed and paid for successfully!"
+ " Thank you for shopping with us!";
} else if (m.equals(MessageToSend.PAYMENT_TRYING)) {
return "Msg: There was an error in your payment process,"
+ " we are working on it and will return back to you shortly."
+ " Meanwhile, your order has been placed and will be shipped.";
} else {
return "Msg: There was an error in your payment process."
+ " Your order is placed and has been converted to COD."
+ " Please reach us on CUSTOMER-CARE-NUBER in case of any queries."
+ " Thank you for shopping with us!";
}
}
}
| 3,886 | 37.485149 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.messagingservice;
import com.iluwatar.commander.Database;
import com.iluwatar.commander.messagingservice.MessagingService.MessageRequest;
import java.util.Hashtable;
import java.util.Map;
/**
* The MessagingDatabase is where the MessageRequest is added.
*/
public class MessagingDatabase extends Database<MessageRequest> {
private final Map<String, MessageRequest> data = new Hashtable<>();
@Override
public MessageRequest add(MessageRequest r) {
return data.put(r.reqId, r);
}
@Override
public MessageRequest get(String requestId) {
return data.get(requestId);
}
}
| 1,911 | 37.24 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.employeehandle;
import com.iluwatar.commander.Order;
import com.iluwatar.commander.Service;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
/**
* The EmployeeHandle class is the middle-man between {@link com.iluwatar.commander.Commander} and
* {@link EmployeeDatabase}.
*/
public class EmployeeHandle extends Service {
public EmployeeHandle(EmployeeDatabase db, Exception... exc) {
super(db, exc);
}
public String receiveRequest(Object... parameters) throws DatabaseUnavailableException {
return updateDb(parameters[0]);
}
protected String updateDb(Object... parameters) throws DatabaseUnavailableException {
var o = (Order) parameters[0];
if (database.get(o.id) == null) {
database.add(o);
return o.id; //true rcvd - change addedToEmployeeHandle to true else dont do anything
}
return null;
}
}
| 2,192 | 38.160714 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.employeehandle;
import com.iluwatar.commander.Database;
import com.iluwatar.commander.Order;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import java.util.HashMap;
import java.util.Map;
/**
* The Employee Database is where orders which have encountered some issue(s) are added.
*/
public class EmployeeDatabase extends Database<Order> {
private final Map<String, Order> data = new HashMap<>();
@Override
public Order add(Order o) throws DatabaseUnavailableException {
return data.put(o.id, o);
}
@Override
public Order get(String orderId) throws DatabaseUnavailableException {
return data.get(orderId);
}
}
| 1,977 | 38.56 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.shippingservice;
import com.iluwatar.commander.Database;
import com.iluwatar.commander.shippingservice.ShippingService.ShippingRequest;
import java.util.Hashtable;
import java.util.Map;
/**
* ShippingDatabase is where the ShippingRequest objects are added.
*/
public class ShippingDatabase extends Database<ShippingRequest> {
private final Map<String, ShippingRequest> data = new Hashtable<>();
@Override
public ShippingRequest add(ShippingRequest r) {
return data.put(r.transactionId, r);
}
public ShippingRequest get(String trasnactionId) {
return data.get(trasnactionId);
}
}
| 1,923 | 37.48 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.shippingservice;
import com.iluwatar.commander.Service;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import lombok.AllArgsConstructor;
/**
* ShippingService class receives request from {@link com.iluwatar.commander.Commander} class and
* adds it to the {@link ShippingDatabase}.
*/
public class ShippingService extends Service {
@AllArgsConstructor
static class ShippingRequest {
String transactionId;
String item;
String address;
}
public ShippingService(ShippingDatabase db, Exception... exc) {
super(db, exc);
}
/**
* Public method which will receive request from {@link com.iluwatar.commander.Commander}.
*/
public String receiveRequest(Object... parameters) throws DatabaseUnavailableException {
var id = generateId();
var item = (String) parameters[0];
var address = (String) parameters[1];
var req = new ShippingRequest(id, item, address);
return updateDb(req);
}
protected String updateDb(Object... parameters) throws DatabaseUnavailableException {
var req = (ShippingRequest) parameters[0];
if (this.database.get(req.transactionId) == null) {
database.add(req);
return req.transactionId;
}
return null;
}
}
| 2,558 | 35.557143 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.queue;
import com.iluwatar.commander.Order;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
/**
* QueueTask object is the object enqueued in queue.
*/
@RequiredArgsConstructor
public class QueueTask {
/**
* TaskType is the type of task to be done.
*/
public enum TaskType {
MESSAGING,
PAYMENT,
EMPLOYEE_DB
}
public final Order order;
public final TaskType taskType;
public final int messageType; //0-fail, 1-error, 2-success
/*we could have varargs Object instead to pass in any parameter instead of just message type
but keeping it simple here*/
@Getter
@Setter
private long firstAttemptTime = -1L; //when first time attempt made to do task
/**
* getType method.
*
* @return String representing type of task
*/
public String getType() {
if (!this.taskType.equals(TaskType.MESSAGING)) {
return this.taskType.toString();
} else {
if (this.messageType == 0) {
return "Payment Failure Message";
} else if (this.messageType == 1) {
return "Payment Error Message";
} else {
return "Payment Success Message";
}
}
}
}
| 2,495 | 31.842105 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.queue;
import com.iluwatar.commander.Database;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.IsEmptyException;
import java.util.ArrayList;
import java.util.List;
/**
* QueueDatabase id where the instructions to be implemented are queued.
*/
public class QueueDatabase extends Database<QueueTask> {
private final Queue<QueueTask> data;
public List<Exception> exceptionsList;
public QueueDatabase(Exception... exc) {
this.data = new Queue<>();
this.exceptionsList = new ArrayList<>(List.of(exc));
}
@Override
public QueueTask add(QueueTask t) {
data.enqueue(t);
return t;
//even if same thing queued twice, it is taken care of in other dbs
}
/**
* peek method returns object at front without removing it from queue.
*
* @return object at front of queue
* @throws IsEmptyException if queue is empty
*/
public QueueTask peek() throws IsEmptyException {
return this.data.peek();
}
/**
* dequeue method removes the object at front and returns it.
*
* @return object at front of queue
* @throws IsEmptyException if queue is empty
*/
public QueueTask dequeue() throws IsEmptyException {
return this.data.dequeue();
}
@Override
public QueueTask get(String taskId) {
return null;
}
}
| 2,687 | 31.780488 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/queue/Queue.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.queue;
import com.iluwatar.commander.exceptions.IsEmptyException;
/**
* Queue data structure implementation.
*
* @param <T> is the type of object the queue will hold.
*/
public class Queue<T> {
private Node<T> front;
private Node<T> rear;
private int size;
static class Node<V> {
V value;
Node<V> next;
Node(V obj, Node<V> b) {
value = obj;
next = b;
}
}
boolean isEmpty() {
return size == 0;
}
void enqueue(T obj) {
if (front == null) {
front = new Node<>(obj, null);
rear = front;
} else {
var temp = new Node<>(obj, null);
rear.next = temp;
rear = temp;
}
size++;
}
T dequeue() throws IsEmptyException {
if (isEmpty()) {
throw new IsEmptyException();
} else {
var temp = front;
front = front.next;
size = size - 1;
return temp.value;
}
}
T peek() throws IsEmptyException {
if (isEmpty()) {
throw new IsEmptyException();
} else {
return front.value;
}
}
}
| 2,356 | 26.729412 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.exceptions;
/**
* PaymentDetailsErrorException is thrown when the details entered are incorrect or payment cannot
* be made with the details given.
*/
public class PaymentDetailsErrorException extends Exception {
private static final long serialVersionUID = 867203L;
}
| 1,591 | 44.485714 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/exceptions/ItemUnavailableException.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.exceptions;
/**
* ItemUnavailableException is thrown when item is not available for shipping.
*/
public class ItemUnavailableException extends Exception {
private static final long serialVersionUID = 575940L;
}
| 1,532 | 44.088235 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/exceptions/IsEmptyException.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.exceptions;
/**
* IsEmptyException is thrown when it is attempted to dequeue from an empty queue.
*/
public class IsEmptyException extends Exception {
private static final long serialVersionUID = 123546L;
}
| 1,528 | 43.970588 | 140 | java |
java-design-patterns | java-design-patterns-master/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.commander.exceptions;
/**
* DatabaseUnavailableException is thrown when database is unavailable and nothing can be added or
* retrieved.
*/
public class DatabaseUnavailableException extends Exception {
private static final long serialVersionUID = 2459603L;
}
| 1,571 | 43.914286 | 140 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.