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/front-controller/src/main/java/com/iluwatar/front/controller/View.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.front.controller;
/**
* Views are the representations rendered for the user.
*/
public interface View {
void display();
}
| 1,433
| 41.176471
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.front.controller;
/**
* Command for archers.
*/
public class ArcherCommand implements Command {
@Override
public void process() {
new ArcherView().display();
}
}
| 1,481
| 39.054054
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/CatapultView.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.front.controller;
import lombok.extern.slf4j.Slf4j;
/**
* View for catapults.
*/
@Slf4j
public class CatapultView implements View {
@Override
public void display() {
LOGGER.info("Displaying catapults");
}
}
| 1,527
| 37.2
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/ErrorView.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.front.controller;
import lombok.extern.slf4j.Slf4j;
/**
* View for errors.
*/
@Slf4j
public class ErrorView implements View {
@Override
public void display() {
LOGGER.error("Error 500");
}
}
| 1,511
| 36.8
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.front.controller;
/**
* Default command in case the mapping is not successful.
*/
public class UnknownCommand implements Command {
@Override
public void process() {
new ErrorView().display();
}
}
| 1,515
| 39.972973
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/front-controller/src/main/java/com/iluwatar/front/controller/ArcherView.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.front.controller;
import lombok.extern.slf4j.Slf4j;
/**
* View for archers.
*/
@Slf4j
public class ArcherView implements View {
@Override
public void display() {
LOGGER.info("Displaying archers");
}
}
| 1,521
| 37.05
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/HayesTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
/**
* Hayes test class
*/
class HayesTest {
@Test
void testAcceptForDos() {
var hayes = new Hayes();
var mockVisitor = mock(ConfigureForDosVisitor.class);
hayes.accept(mockVisitor);
verify((HayesVisitor) mockVisitor).visit(eq(hayes));
}
@Test
void testAcceptForUnix() {
var hayes = new Hayes();
var mockVisitor = mock(ConfigureForUnixVisitor.class);
hayes.accept(mockVisitor);
verifyNoMoreInteractions(mockVisitor);
}
}
| 1,914
| 33.196429
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ZoomTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Zoom test class
*/
class ZoomTest {
@Test
void testAcceptForDos() {
var zoom = new Zoom();
var mockVisitor = mock(ConfigureForDosVisitor.class);
zoom.accept(mockVisitor);
verify((ZoomVisitor) mockVisitor).visit(eq(zoom));
}
@Test
void testAcceptForUnix() {
var zoom = new Zoom();
var mockVisitor = mock(ConfigureForUnixVisitor.class);
zoom.accept(mockVisitor);
verify((ZoomVisitor) mockVisitor).visit(eq(zoom));
}
}
| 1,961
| 33.421053
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/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.acyclicvisitor;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that the Acyclic Visitor example runs without errors.
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,837
| 37.291667
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
import lombok.extern.slf4j.Slf4j;
/**
* Zoom class implements its accept method.
*/
@Slf4j
public class Zoom implements Modem {
/**
* Accepts all visitors but honors only ZoomVisitor.
*/
@Override
public void accept(ModemVisitor modemVisitor) {
if (modemVisitor instanceof ZoomVisitor) {
((ZoomVisitor) modemVisitor).visit(this);
} else {
LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem");
}
}
/**
* Zoom modem's toString method.
*/
@Override
public String toString() {
return "Zoom modem";
}
}
| 1,891
| 33.4
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitor.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
import lombok.extern.slf4j.Slf4j;
/**
* ConfigureForDosVisitor class implements both zoom's and hayes' visit method for Dos
* manufacturer.
*/
@Slf4j
public class ConfigureForDosVisitor implements AllModemVisitor {
@Override
public void visit(Hayes hayes) {
LOGGER.info(hayes + " used with Dos configurator.");
}
@Override
public void visit(Zoom zoom) {
LOGGER.info(zoom + " used with Dos configurator.");
}
}
| 1,759
| 37.26087
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/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.acyclicvisitor;
/**
* The Acyclic Visitor pattern allows new functions to be added to existing class hierarchies
* without affecting those hierarchies, and without creating the dependency cycles that are inherent
* to the GoF Visitor pattern, by making the Visitor base class degenerate
*
* <p>In this example the visitor base class is {@link ModemVisitor}. The base class of the visited
* hierarchy is {@link Modem} and has two children {@link Hayes} and {@link Zoom} each one having
* its own visitor interface {@link HayesVisitor} and {@link ZoomVisitor} respectively. {@link
* ConfigureForUnixVisitor} and {@link ConfigureForDosVisitor} implement each derivative's visit
* method only if it is required
*/
public class App {
/**
* Program's entry point.
*/
public static void main(String[] args) {
var conUnix = new ConfigureForUnixVisitor();
var conDos = new ConfigureForDosVisitor();
var zoom = new Zoom();
var hayes = new Hayes();
hayes.accept(conDos); // Hayes modem with Dos configurator
zoom.accept(conDos); // Zoom modem with Dos configurator
hayes.accept(conUnix); // Hayes modem with Unix configurator
zoom.accept(conUnix); // Zoom modem with Unix configurator
}
}
| 2,544
| 44.446429
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
import lombok.extern.slf4j.Slf4j;
/**
* ConfigureForUnixVisitor class implements zoom's visit method for Unix manufacturer, unlike
* traditional visitor pattern, this class may selectively implement visit for other modems.
*/
@Slf4j
public class ConfigureForUnixVisitor implements ZoomVisitor {
@Override
public void visit(Zoom zoom) {
LOGGER.info(zoom + " used with Unix configurator.");
}
}
| 1,729
| 42.25
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
/**
* ZoomVisitor interface.
*/
public interface ZoomVisitor extends ModemVisitor {
void visit(Zoom zoom);
}
| 1,435
| 42.515152
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
import lombok.extern.slf4j.Slf4j;
/**
* Hayes class implements its accept method.
*/
@Slf4j
public class Hayes implements Modem {
/**
* Accepts all visitors but honors only HayesVisitor.
*/
@Override
public void accept(ModemVisitor modemVisitor) {
if (modemVisitor instanceof HayesVisitor) {
((HayesVisitor) modemVisitor).visit(this);
} else {
LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem");
}
}
/**
* Hayes' modem's toString method.
*/
@Override
public String toString() {
return "Hayes modem";
}
}
| 1,902
| 32.982143
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ModemVisitor.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
/**
* ModemVisitor interface does not contain any visit methods so that it does not depend on the
* visited hierarchy. Each derivative's visit method is declared in its own visitor interface
*/
public interface ModemVisitor {
// Visitor is a degenerate base class for all visitors.
}
| 1,611
| 46.411765
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Modem.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
/**
* //Modem abstract class.
* converted to an interface
*/
public interface Modem {
void accept(ModemVisitor modemVisitor);
}
| 1,455
| 41.823529
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
/**
* All ModemVisitor interface extends all visitor interfaces. This interface provides ease of use
* when a visitor needs to visit all modem types.
*/
public interface AllModemVisitor extends ZoomVisitor, HayesVisitor {
}
| 1,550
| 44.617647
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/HayesVisitor.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.acyclicvisitor;
/**
* HayesVisitor interface.
*/
public interface HayesVisitor extends ModemVisitor {
void visit(Hayes hayes);
}
| 1,439
| 42.636364
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument;
import com.iluwatar.abstractdocument.domain.Car;
import com.iluwatar.abstractdocument.domain.Part;
import com.iluwatar.abstractdocument.domain.enums.Property;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test for Part and Car
*/
class DomainTest {
private static final String TEST_PART_TYPE = "test-part-type";
private static final String TEST_PART_MODEL = "test-part-model";
private static final long TEST_PART_PRICE = 0L;
private static final String TEST_CAR_MODEL = "test-car-model";
private static final long TEST_CAR_PRICE = 1L;
@Test
void shouldConstructPart() {
var partProperties = Map.of(
Property.TYPE.toString(), TEST_PART_TYPE,
Property.MODEL.toString(), TEST_PART_MODEL,
Property.PRICE.toString(), (Object) TEST_PART_PRICE
);
var part = new Part(partProperties);
assertEquals(TEST_PART_TYPE, part.getType().orElseThrow());
assertEquals(TEST_PART_MODEL, part.getModel().orElseThrow());
assertEquals(TEST_PART_PRICE, part.getPrice().orElseThrow());
}
@Test
void shouldConstructCar() {
var carProperties = Map.of(
Property.MODEL.toString(), TEST_CAR_MODEL,
Property.PRICE.toString(), TEST_CAR_PRICE,
Property.PARTS.toString(), List.of(Map.of(), Map.of())
);
var car = new Car(carProperties);
assertEquals(TEST_CAR_MODEL, car.getModel().orElseThrow());
assertEquals(TEST_CAR_PRICE, car.getPrice().orElseThrow());
assertEquals(2, car.getParts().count());
}
}
| 2,920
| 37.946667
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
/**
* AbstractDocument test class
*/
class AbstractDocumentTest {
private static final String KEY = "key";
private static final String VALUE = "value";
private static class DocumentImplementation extends AbstractDocument {
DocumentImplementation(Map<String, Object> properties) {
super(properties);
}
}
private final DocumentImplementation document = new DocumentImplementation(new HashMap<>());
@Test
void shouldPutAndGetValue() {
document.put(KEY, VALUE);
assertEquals(VALUE, document.get(KEY));
}
@Test
void shouldRetrieveChildren() {
var children = List.of(Map.of(), Map.of());
document.put(KEY, children);
var childrenStream = document.children(KEY, DocumentImplementation::new);
assertNotNull(children);
assertEquals(2, childrenStream.count());
}
@Test
void shouldRetrieveEmptyStreamForNonExistingChildren() {
var children = document.children(KEY, DocumentImplementation::new);
assertNotNull(children);
assertEquals(0, children.count());
}
@Test
void shouldIncludePropsInToString() {
var props = Map.of(KEY, (Object) VALUE);
var document = new DocumentImplementation(props);
assertTrue(document.toString().contains(KEY));
assertTrue(document.toString().contains(VALUE));
}
}
| 2,780
| 32.107143
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/test/java/com/iluwatar/abstractdocument/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.abstractdocument;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Simple App test
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test
void shouldExecuteAppWithoutException() {
assertDoesNotThrow(() -> App.main(null));
}
}
| 1,778
| 35.306122
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/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.abstractdocument;
import com.iluwatar.abstractdocument.domain.Car;
import com.iluwatar.abstractdocument.domain.enums.Property;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
/**
* The Abstract Document pattern enables handling additional, non-static properties. This pattern
* uses concept of traits to enable type safety and separate properties of different classes into
* set of interfaces.
*
* <p>In Abstract Document pattern,({@link AbstractDocument}) fully implements {@link Document})
* interface. Traits are then defined to enable access to properties in usual, static way.
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
LOGGER.info("Constructing parts and car");
var wheelProperties = Map.of(
Property.TYPE.toString(), "wheel",
Property.MODEL.toString(), "15C",
Property.PRICE.toString(), 100L);
var doorProperties = Map.of(
Property.TYPE.toString(), "door",
Property.MODEL.toString(), "Lambo",
Property.PRICE.toString(), 300L);
var carProperties = Map.of(
Property.MODEL.toString(), "300SL",
Property.PRICE.toString(), 10000L,
Property.PARTS.toString(), List.of(wheelProperties, doorProperties));
var car = new Car(carProperties);
LOGGER.info("Here is our car:");
LOGGER.info("-> model: {}", car.getModel().orElseThrow());
LOGGER.info("-> price: {}", car.getPrice().orElseThrow());
LOGGER.info("-> parts: ");
car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}",
p.getType().orElse(null),
p.getModel().orElse(null),
p.getPrice().orElse(null))
);
}
}
| 3,056
| 37.2125
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* Document interface.
*/
public interface Document {
/**
* Puts the value related to the key.
*
* @param key element key
* @param value element value
* @return Void
*/
Void put(String key, Object value);
/**
* Gets the value for the key.
*
* @param key element key
* @return value or null
*/
Object get(String key);
/**
* Gets the stream of child documents.
*
* @param key element key
* @param constructor constructor of child class
* @return child documents
*/
<T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor);
}
| 2,043
| 31.967742
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* Abstract implementation of Document interface.
*/
public abstract class AbstractDocument implements Document {
private final Map<String, Object> properties;
protected AbstractDocument(Map<String, Object> properties) {
Objects.requireNonNull(properties, "properties map is required");
this.properties = properties;
}
@Override
public Void put(String key, Object value) {
properties.put(key, value);
return null;
}
@Override
public Object get(String key) {
return properties.get(key);
}
@Override
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) {
return Stream.ofNullable(get(key))
.filter(Objects::nonNull)
.map(el -> (List<Map<String, Object>>) el)
.findAny()
.stream()
.flatMap(Collection::stream)
.map(constructor);
}
@Override
public String toString() {
var builder = new StringBuilder();
builder.append(getClass().getName()).append("[");
properties.forEach((key, value) -> builder.append("[").append(key).append(" : ").append(value)
.append("]"));
builder.append("]");
return builder.toString();
}
}
| 2,682
| 32.962025
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument.domain;
import com.iluwatar.abstractdocument.Document;
import com.iluwatar.abstractdocument.domain.enums.Property;
import java.util.stream.Stream;
/**
* HasParts trait for static access to 'parts' property.
*/
public interface HasParts extends Document {
default Stream<Part> getParts() {
return children(Property.PARTS.toString(), Part::new);
}
}
| 1,684
| 40.097561
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument.domain;
import com.iluwatar.abstractdocument.Document;
import com.iluwatar.abstractdocument.domain.enums.Property;
import java.util.Optional;
/**
* HasModel trait for static access to 'model' property.
*/
public interface HasModel extends Document {
default Optional<String> getModel() {
return Optional.ofNullable((String) get(Property.MODEL.toString()));
}
}
| 1,697
| 40.414634
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument.domain;
import com.iluwatar.abstractdocument.AbstractDocument;
import java.util.Map;
/**
* Car entity.
*/
public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts {
public Car(Map<String, Object> properties) {
super(properties);
}
}
| 1,594
| 38.875
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument.domain;
import com.iluwatar.abstractdocument.Document;
import com.iluwatar.abstractdocument.domain.enums.Property;
import java.util.Optional;
/**
* HasPrice trait for static access to 'price' property.
*/
public interface HasPrice extends Document {
default Optional<Number> getPrice() {
return Optional.ofNullable((Number) get(Property.PRICE.toString()));
}
}
| 1,697
| 40.414634
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument.domain;
import com.iluwatar.abstractdocument.Document;
import com.iluwatar.abstractdocument.domain.enums.Property;
import java.util.Optional;
/**
* HasType trait for static access to 'type' property.
*/
public interface HasType extends Document {
default Optional<String> getType() {
return Optional.ofNullable((String) get(Property.TYPE.toString()));
}
}
| 1,692
| 40.292683
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument.domain;
import com.iluwatar.abstractdocument.AbstractDocument;
import java.util.Map;
/**
* Part entity.
*/
public class Part extends AbstractDocument implements HasType, HasModel, HasPrice {
public Part(Map<String, Object> properties) {
super(properties);
}
}
| 1,596
| 38.925
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/enums/Property.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.abstractdocument.domain.enums;
/**
* Enum To Describe Property type.
*/
public enum Property {
PARTS, TYPE, PRICE, MODEL
}
| 1,434
| 41.205882
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/promise/src/test/java/com/iluwatar/promise/PromiseTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.promise;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Tests Promise class.
*/
class PromiseTest {
private Executor executor;
private Promise<Integer> promise;
@BeforeEach
void setUp() {
executor = Executors.newSingleThreadExecutor();
promise = new Promise<>();
}
@Test
void promiseIsFulfilledWithTheResultantValueOfExecutingTheTask()
throws InterruptedException, ExecutionException {
promise.fulfillInAsync(new NumberCrunchingTask(), executor);
assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, promise.get());
assertTrue(promise.isDone());
assertFalse(promise.isCancelled());
}
@Test
void promiseIsFulfilledWithAnExceptionIfTaskThrowsAnException()
throws InterruptedException {
testWaitingForeverForPromiseToBeFulfilled();
testWaitingSomeTimeForPromiseToBeFulfilled();
}
private void testWaitingForeverForPromiseToBeFulfilled() throws InterruptedException {
var promise = new Promise<Integer>();
promise.fulfillInAsync(() -> {
throw new RuntimeException("Barf!");
}, executor);
try {
promise.get();
fail("Fetching promise should result in exception if the task threw an exception");
} catch (ExecutionException ex) {
assertTrue(promise.isDone());
assertFalse(promise.isCancelled());
}
try {
promise.get(1000, TimeUnit.SECONDS);
fail("Fetching promise should result in exception if the task threw an exception");
} catch (ExecutionException ex) {
assertTrue(promise.isDone());
assertFalse(promise.isCancelled());
}
}
private void testWaitingSomeTimeForPromiseToBeFulfilled() throws InterruptedException {
var promise = new Promise<Integer>();
promise.fulfillInAsync(() -> {
throw new RuntimeException("Barf!");
}, executor);
try {
promise.get(1000, TimeUnit.SECONDS);
fail("Fetching promise should result in exception if the task threw an exception");
} catch (ExecutionException ex) {
assertTrue(promise.isDone());
assertFalse(promise.isCancelled());
}
try {
promise.get();
fail("Fetching promise should result in exception if the task threw an exception");
} catch (ExecutionException ex) {
assertTrue(promise.isDone());
assertFalse(promise.isCancelled());
}
}
@Test
void dependentPromiseIsFulfilledAfterTheConsumerConsumesTheResultOfThisPromise()
throws InterruptedException, ExecutionException {
var dependentPromise = promise
.fulfillInAsync(new NumberCrunchingTask(), executor)
.thenAccept(value -> assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value));
dependentPromise.get();
assertTrue(dependentPromise.isDone());
assertFalse(dependentPromise.isCancelled());
}
@Test
void dependentPromiseIsFulfilledWithAnExceptionIfConsumerThrowsAnException()
throws InterruptedException {
var dependentPromise = promise
.fulfillInAsync(new NumberCrunchingTask(), executor)
.thenAccept(value -> {
throw new RuntimeException("Barf!");
});
try {
dependentPromise.get();
fail("Fetching dependent promise should result in exception "
+ "if the action threw an exception");
} catch (ExecutionException ex) {
assertTrue(promise.isDone());
assertFalse(promise.isCancelled());
}
try {
dependentPromise.get(1000, TimeUnit.SECONDS);
fail("Fetching dependent promise should result in exception "
+ "if the action threw an exception");
} catch (ExecutionException ex) {
assertTrue(promise.isDone());
assertFalse(promise.isCancelled());
}
}
@Test
void dependentPromiseIsFulfilledAfterTheFunctionTransformsTheResultOfThisPromise()
throws InterruptedException, ExecutionException {
var dependentPromise = promise
.fulfillInAsync(new NumberCrunchingTask(), executor)
.thenApply(value -> {
assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value);
return String.valueOf(value);
});
assertEquals(String.valueOf(NumberCrunchingTask.CRUNCHED_NUMBER), dependentPromise.get());
assertTrue(dependentPromise.isDone());
assertFalse(dependentPromise.isCancelled());
}
@Test
void dependentPromiseIsFulfilledWithAnExceptionIfTheFunctionThrowsException()
throws InterruptedException {
var dependentPromise = promise
.fulfillInAsync(new NumberCrunchingTask(), executor)
.thenApply(value -> {
throw new RuntimeException("Barf!");
});
try {
dependentPromise.get();
fail("Fetching dependent promise should result in exception "
+ "if the function threw an exception");
} catch (ExecutionException ex) {
assertTrue(promise.isDone());
assertFalse(promise.isCancelled());
}
try {
dependentPromise.get(1000, TimeUnit.SECONDS);
fail("Fetching dependent promise should result in exception "
+ "if the function threw an exception");
} catch (ExecutionException ex) {
assertTrue(promise.isDone());
assertFalse(promise.isCancelled());
}
}
@Test
void fetchingAnAlreadyFulfilledPromiseReturnsTheFulfilledValueImmediately()
throws ExecutionException {
var promise = new Promise<Integer>();
promise.fulfill(NumberCrunchingTask.CRUNCHED_NUMBER);
Integer result = promise.get(1000, TimeUnit.SECONDS);
assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, result);
}
@SuppressWarnings("unchecked")
@Test
void exceptionHandlerIsCalledWhenPromiseIsFulfilledExceptionally() {
var promise = new Promise<>();
var exceptionHandler = mock(Consumer.class);
promise.onError(exceptionHandler);
var exception = new Exception("barf!");
promise.fulfillExceptionally(exception);
verify(exceptionHandler).accept(eq(exception));
}
private static class NumberCrunchingTask implements Callable<Integer> {
private static final Integer CRUNCHED_NUMBER = Integer.MAX_VALUE;
@Override
public Integer call() throws Exception {
// Do number crunching
Thread.sleep(100);
return CRUNCHED_NUMBER;
}
}
}
| 8,149
| 32.817427
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/promise/src/test/java/com/iluwatar/promise/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.promise;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test.
*/
class AppTest {
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(null));
}
}
| 1,625
| 37.714286
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/promise/src/main/java/com/iluwatar/promise/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.promise;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;
/**
* The Promise object is used for asynchronous computations. A Promise represents an operation that
* hasn't completed yet, but is expected in the future.
*
* <p>A Promise represents a proxy for a value not necessarily known when the promise is created.
* It allows you to associate dependent promises to an asynchronous action's eventual success value
* or failure reason. This lets asynchronous methods return values like synchronous methods: instead
* of the final value, the asynchronous method returns a promise of having a value at some point in
* the future.
*
* <p>Promises provide a few advantages over callback objects:
* <ul>
* <li> Functional composition and error handling
* <li> Prevents callback hell and provides callback aggregation
* </ul>
*
* <p>In this application the usage of promise is demonstrated with two examples:
* <ul>
* <li>Count Lines: In this example a file is downloaded and its line count is calculated.
* The calculated line count is then consumed and printed on console.
* <li>Lowest Character Frequency: In this example a file is downloaded and its lowest frequency
* character is found and printed on console. This happens via a chain of promises, we start with
* a file download promise, then a promise of character frequency, then a promise of lowest
* frequency character which is finally consumed and result is printed on console.
* </ul>
*
* @see CompletableFuture
*/
@Slf4j
public class App {
private static final String DEFAULT_URL =
"https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md";
private final ExecutorService executor;
private final CountDownLatch stopLatch;
private App() {
executor = Executors.newFixedThreadPool(2);
stopLatch = new CountDownLatch(2);
}
/**
* Program entry point.
*
* @param args arguments
* @throws InterruptedException if main thread is interrupted.
* @throws ExecutionException if an execution error occurs.
*/
public static void main(String[] args) throws InterruptedException {
var app = new App();
try {
app.promiseUsage();
} finally {
app.stop();
}
}
private void promiseUsage() {
calculateLineCount();
calculateLowestFrequencyChar();
}
/*
* Calculate the lowest frequency character and when that promise is fulfilled,
* consume the result in a Consumer<Character>
*/
private void calculateLowestFrequencyChar() {
lowestFrequencyChar().thenAccept(
charFrequency -> {
LOGGER.info("Char with lowest frequency is: {}", charFrequency);
taskCompleted();
}
);
}
/*
* Calculate the line count and when that promise is fulfilled, consume the result
* in a Consumer<Integer>
*/
private void calculateLineCount() {
countLines().thenAccept(
count -> {
LOGGER.info("Line count is: {}", count);
taskCompleted();
}
);
}
/*
* Calculate the character frequency of a file and when that promise is fulfilled,
* then promise to apply function to calculate lowest character frequency.
*/
private Promise<Character> lowestFrequencyChar() {
return characterFrequency().thenApply(Utility::lowestFrequencyChar);
}
/*
* Download the file at DEFAULT_URL and when that promise is fulfilled,
* then promise to apply function to calculate character frequency.
*/
private Promise<Map<Character, Long>> characterFrequency() {
return download(DEFAULT_URL).thenApply(Utility::characterFrequency);
}
/*
* Download the file at DEFAULT_URL and when that promise is fulfilled,
* then promise to apply function to count lines in that file.
*/
private Promise<Integer> countLines() {
return download(DEFAULT_URL).thenApply(Utility::countLines);
}
/*
* Return a promise to provide the local absolute path of the file downloaded in background.
* This is an async method and does not wait until the file is downloaded.
*/
private Promise<String> download(String urlString) {
return new Promise<String>()
.fulfillInAsync(
() -> Utility.downloadFile(urlString), executor)
.onError(
throwable -> {
throwable.printStackTrace();
taskCompleted();
}
);
}
private void stop() throws InterruptedException {
stopLatch.await();
executor.shutdownNow();
}
private void taskCompleted() {
stopLatch.countDown();
}
}
| 6,107
| 34.306358
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/promise/src/main/java/com/iluwatar/promise/Promise.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.promise;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* A Promise represents a proxy for a value not necessarily known when the promise is created. It
* allows you to associate dependent promises to an asynchronous action's eventual success value or
* failure reason. This lets asynchronous methods return values like synchronous methods: instead of
* the final value, the asynchronous method returns a promise of having a value at some point in the
* future.
*
* @param <T> type of result.
*/
public class Promise<T> extends PromiseSupport<T> {
private Runnable fulfillmentAction;
private Consumer<? super Throwable> exceptionHandler;
/**
* Creates a promise that will be fulfilled in future.
*/
public Promise() {
// Empty constructor
}
/**
* Fulfills the promise with the provided value.
*
* @param value the fulfilled value that can be accessed using {@link #get()}.
*/
@Override
public void fulfill(T value) {
super.fulfill(value);
postFulfillment();
}
/**
* Fulfills the promise with exception due to error in execution.
*
* @param exception the exception will be wrapped in {@link ExecutionException} when accessing the
* value using {@link #get()}.
*/
@Override
public void fulfillExceptionally(Exception exception) {
super.fulfillExceptionally(exception);
handleException(exception);
postFulfillment();
}
private void handleException(Exception exception) {
if (exceptionHandler == null) {
return;
}
exceptionHandler.accept(exception);
}
private void postFulfillment() {
if (fulfillmentAction == null) {
return;
}
fulfillmentAction.run();
}
/**
* Executes the task using the executor in other thread and fulfills the promise returned once the
* task completes either successfully or with an exception.
*
* @param task the task that will provide the value to fulfill the promise.
* @param executor the executor in which the task should be run.
* @return a promise that represents the result of running the task provided.
*/
public Promise<T> fulfillInAsync(final Callable<T> task, Executor executor) {
executor.execute(() -> {
try {
fulfill(task.call());
} catch (Exception ex) {
fulfillExceptionally(ex);
}
});
return this;
}
/**
* Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result
* of this promise as argument to the action provided.
*
* @param action action to be executed.
* @return a new promise.
*/
public Promise<Void> thenAccept(Consumer<? super T> action) {
var dest = new Promise<Void>();
fulfillmentAction = new ConsumeAction(this, dest, action);
return dest;
}
/**
* Set the exception handler on this promise.
*
* @param exceptionHandler a consumer that will handle the exception occurred while fulfilling the
* promise.
* @return this
*/
public Promise<T> onError(Consumer<? super Throwable> exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
/**
* Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result
* of this promise as argument to the function provided.
*
* @param func function to be executed.
* @return a new promise.
*/
public <V> Promise<V> thenApply(Function<? super T, V> func) {
Promise<V> dest = new Promise<>();
fulfillmentAction = new TransformAction<>(this, dest, func);
return dest;
}
/**
* Accesses the value from source promise and calls the consumer, then fulfills the destination
* promise.
*/
private class ConsumeAction implements Runnable {
private final Promise<T> src;
private final Promise<Void> dest;
private final Consumer<? super T> action;
private ConsumeAction(Promise<T> src, Promise<Void> dest, Consumer<? super T> action) {
this.src = src;
this.dest = dest;
this.action = action;
}
@Override
public void run() {
try {
action.accept(src.get());
dest.fulfill(null);
} catch (Throwable throwable) {
dest.fulfillExceptionally((Exception) throwable.getCause());
}
}
}
/**
* Accesses the value from source promise, then fulfills the destination promise using the
* transformed value. The source value is transformed using the transformation function.
*/
private class TransformAction<V> implements Runnable {
private final Promise<T> src;
private final Promise<V> dest;
private final Function<? super T, V> func;
private TransformAction(Promise<T> src, Promise<V> dest, Function<? super T, V> func) {
this.src = src;
this.dest = dest;
this.func = func;
}
@Override
public void run() {
try {
dest.fulfill(func.apply(src.get()));
} catch (Throwable throwable) {
dest.fulfillExceptionally((Exception) throwable.getCause());
}
}
}
}
| 6,531
| 31.497512
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/promise/src/main/java/com/iluwatar/promise/Utility.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.promise;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
/**
* Utility to perform various operations.
*/
@Slf4j
public class Utility {
/**
* Calculates character frequency of the file provided.
*
* @param fileLocation location of the file.
* @return a map of character to its frequency, an empty map if file does not exist.
*/
public static Map<Character, Long> characterFrequency(String fileLocation) {
try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) {
return bufferedReader.lines()
.flatMapToInt(String::chars)
.mapToObj(x -> (char) x)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
} catch (IOException ex) {
ex.printStackTrace();
}
return Collections.emptyMap();
}
/**
* Return the character with the lowest frequency, if exists.
*
* @return the character, {@code Optional.empty()} otherwise.
*/
public static Character lowestFrequencyChar(Map<Character, Long> charFrequency) {
return charFrequency
.entrySet()
.stream()
.min(Comparator.comparingLong(Entry::getValue))
.map(Entry::getKey)
.orElseThrow();
}
/**
* Count the number of lines in a file.
*
* @return number of lines, 0 if file does not exist.
*/
public static Integer countLines(String fileLocation) {
try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) {
return (int) bufferedReader.lines().count();
} catch (IOException ex) {
ex.printStackTrace();
}
return 0;
}
/**
* Downloads the contents from the given urlString, and stores it in a temporary directory.
*
* @return the absolute path of the file downloaded.
*/
public static String downloadFile(String urlString) throws IOException {
LOGGER.info("Downloading contents from url: {}", urlString);
var url = new URL(urlString);
var file = File.createTempFile("promise_pattern", null);
try (var bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
var writer = new FileWriter(file)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
writer.write(line);
writer.write("\n");
}
LOGGER.info("File downloaded at: {}", file.getAbsolutePath());
return file.getAbsolutePath();
}
}
}
| 4,066
| 34.365217
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/promise/src/main/java/com/iluwatar/promise/PromiseSupport.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.promise;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A really simplified implementation of future that allows completing it successfully with a value
* or exceptionally with an exception.
*/
class PromiseSupport<T> implements Future<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(PromiseSupport.class);
private static final int RUNNING = 1;
private static final int FAILED = 2;
private static final int COMPLETED = 3;
private final Object lock;
private volatile int state = RUNNING;
private T value;
private Exception exception;
PromiseSupport() {
this.lock = new Object();
}
void fulfill(T value) {
this.value = value;
this.state = COMPLETED;
synchronized (lock) {
lock.notifyAll();
}
}
void fulfillExceptionally(Exception exception) {
this.exception = exception;
this.state = FAILED;
synchronized (lock) {
lock.notifyAll();
}
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return state > RUNNING;
}
@Override
public T get() throws InterruptedException, ExecutionException {
synchronized (lock) {
while (state == RUNNING) {
lock.wait();
}
}
if (state == COMPLETED) {
return value;
}
throw new ExecutionException(exception);
}
@Override
public T get(long timeout, TimeUnit unit) throws ExecutionException {
synchronized (lock) {
while (state == RUNNING) {
try {
lock.wait(unit.toMillis(timeout));
} catch (InterruptedException e) {
LOGGER.warn("Interrupted!", e);
Thread.currentThread().interrupt();
}
}
}
if (state == COMPLETED) {
return value;
}
throw new ExecutionException(exception);
}
}
| 3,361
| 27.491525
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.producer.consumer;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
/**
* Date: 12/27/15 - 11:01 PM
*
* @author Jeroen Meulemeester
*/
class ConsumerTest {
private static final int ITEM_COUNT = 5;
@Test
void testConsume() throws Exception {
final var queue = spy(new ItemQueue());
for (var id = 0; id < ITEM_COUNT; id++) {
queue.put(new Item("producer", id));
}
reset(queue); // Don't count the preparation above as interactions with the queue
final var consumer = new Consumer("consumer", queue);
for (var id = 0; id < ITEM_COUNT; id++) {
consumer.consume();
}
verify(queue, times(ITEM_COUNT)).take();
}
}
| 2,126
| 33.868852
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.producer.consumer;
import static java.time.Duration.ofMillis;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.junit.jupiter.api.Test;
/**
* Date: 12/28/15 - 12:12 AM
*
* @author Jeroen Meulemeester
*/
class ProducerTest {
@Test
void testProduce() {
assertTimeout(ofMillis(6000), () -> {
final var queue = mock(ItemQueue.class);
final var producer = new Producer("producer", queue);
producer.produce();
verify(queue).put(any(Item.class));
verifyNoMoreInteractions(queue);
});
}
}
| 2,053
| 35.678571
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/producer-consumer/src/test/java/com/iluwatar/producer/consumer/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.producer.consumer;
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,597
| 37.047619
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/producer-consumer/src/main/java/com/iluwatar/producer/consumer/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.producer.consumer;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
/**
* Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces
* coupling between Producer and Consumer by separating Identification of work with Execution of
* Work.
*
* <p>In producer consumer design pattern a shared queue is used to control the flow and this
* separation allows you to code producer and consumer separately. It also addresses the issue of
* different timing require to produce item or consuming item. by using producer consumer pattern
* both Producer and Consumer Thread can work with different speed.
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var queue = new ItemQueue();
var executorService = Executors.newFixedThreadPool(5);
for (var i = 0; i < 2; i++) {
final var producer = new Producer("Producer_" + i, queue);
executorService.submit(() -> {
while (true) {
producer.produce();
}
});
}
for (var i = 0; i < 3; i++) {
final var consumer = new Consumer("Consumer_" + i, queue);
executorService.submit(() -> {
while (true) {
consumer.consume();
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(10, TimeUnit.SECONDS);
executorService.shutdownNow();
} catch (InterruptedException e) {
LOGGER.error("Error waiting for ExecutorService shutdown");
}
}
}
| 2,941
| 34.878049
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.producer.consumer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Class as a channel for {@link Producer}-{@link Consumer} exchange.
*/
public class ItemQueue {
private final BlockingQueue<Item> queue;
public ItemQueue() {
queue = new LinkedBlockingQueue<>(5);
}
public void put(Item item) throws InterruptedException {
queue.put(item);
}
public Item take() throws InterruptedException {
return queue.take();
}
}
| 1,807
| 33.113208
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.producer.consumer;
import java.security.SecureRandom;
/**
* Class responsible for producing unit of work that can be expressed as {@link Item} and submitted
* to queue.
*/
public class Producer {
private static final SecureRandom RANDOM = new SecureRandom();
private final ItemQueue queue;
private final String name;
private int itemId;
public Producer(String name, ItemQueue queue) {
this.name = name;
this.queue = queue;
}
/**
* Put item in the queue.
*/
public void produce() throws InterruptedException {
var item = new Item(name, itemId++);
queue.put(item);
Thread.sleep(RANDOM.nextInt(2000));
}
}
| 1,964
| 32.87931
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.producer.consumer;
import lombok.extern.slf4j.Slf4j;
/**
* Class responsible for consume the {@link Item} produced by {@link Producer}.
*/
@Slf4j
public class Consumer {
private final ItemQueue queue;
private final String name;
public Consumer(String name, ItemQueue queue) {
this.name = name;
this.queue = queue;
}
/**
* Consume item from the queue.
*/
public void consume() throws InterruptedException {
var item = queue.take();
LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name,
item.id(), item.producer());
}
}
| 1,892
| 34.055556
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/producer-consumer/src/main/java/com/iluwatar/producer/consumer/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.producer.consumer;
/**
* Class take part of an {@link Producer}-{@link Consumer} exchange.
*/
public record Item(String producer, int id) {
}
| 1,450
| 44.34375
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/embedded-value/src/test/java/com/iluwatar/embedded/value/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.embedded.value;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
/**
* Check whether the execution of the main method in {@link App}
* throws an exception.
*/
public class AppTest {
@Test
public void doesNotThrowException() {
assertDoesNotThrow(() -> App.main(new String[] {}));
}
}
| 1,669
| 38.761905
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/embedded-value/src/main/java/com/iluwatar/embedded/value/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.embedded.value;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
/**
* <p> Many small objects make sense in an OO system that don’t make sense as
* tables in a database. Examples include currency-aware money objects (amount, currency) and date
* ranges. Although the default thinking is to save an object as a table, no sane
* person would want a table of money values. </p>
*
* <p> An Embedded Value maps the values of an object to fields in the record of
* the object’s owner. In this implementation we have an Order object with links to an
* ShippingAddress object. In the resulting table the fields in the ShippingAddress
* object map to fields in the Order table rather than make new records
* themselves. </p>
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args.
* @throws Exception if any error occurs.
*
*/
public static void main(String[] args) throws Exception {
final var dataSource = new DataSource();
// Orders to insert into database
final var order1 = new Order("JBL headphone", "Ram",
new ShippingAddress("Bangalore", "Karnataka", "560040"));
final var order2 = new Order("MacBook Pro", "Manjunath",
new ShippingAddress("Bangalore", "Karnataka", "581204"));
final var order3 = new Order("Carrie Soto is Back", "Shiva",
new ShippingAddress("Bangalore", "Karnataka", "560004"));
// Create table for orders - Orders(id, name, orderedBy, city, state, pincode).
// We can see that table is different from the Order object we have.
// We're mapping ShippingAddress into city, state, pincode colummns of the database and not creating a separate table.
if (dataSource.createSchema()) {
LOGGER.info("TABLE CREATED");
LOGGER.info("Table \"Orders\" schema:\n" + dataSource.getSchema());
} else {
//If not able to create table, there's nothing we can do further.
LOGGER.error("Error creating table");
System.exit(0);
}
// Initially, database is empty
LOGGER.info("Orders Query: {}", dataSource.queryOrders().collect(Collectors.toList()));
//Insert orders where shippingAddress is mapped to different columns of the same table
dataSource.insertOrder(order1);
dataSource.insertOrder(order2);
dataSource.insertOrder(order3);
// Query orders.
// We'll create ShippingAddress object from city, state, pincode values from the table and add it to Order object
LOGGER.info("Orders Query: {}", dataSource.queryOrders().collect(Collectors.toList()) + "\n");
//Query order by given id
LOGGER.info("Query Order with id=2: {}", dataSource.queryOrder(2));
//Remove order by given id.
//Since we'd mapped address in the same table, deleting order will also take out the shipping address details.
LOGGER.info("Remove Order with id=1");
dataSource.removeOrder(1);
LOGGER.info("\nOrders Query: {}", dataSource.queryOrders().collect(Collectors.toList()) + "\n");
//After successfull demonstration of the pattern, drop the table
if (dataSource.deleteSchema()) {
LOGGER.info("TABLE DROPPED");
} else {
//If there's a potential error while dropping table
LOGGER.error("Error deleting table");
}
}
}
| 4,659
| 42.551402
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSourceInterface.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.embedded.value;
import java.sql.SQLException;
import java.util.stream.Stream;
/*
* Abstract class which contains the required SQL queries and basic methods declaration.
*
* The main thing to consider is that the ShippingAddress object doesn't have it's own class
* but it's values are stored into the Orders table as city, state, pincode
*
*/
interface DataSourceInterface {
final String JDBC_URL = "jdbc:h2:mem:Embedded-Value";
final String CREATE_SCHEMA = "CREATE TABLE Orders (Id INT AUTO_INCREMENT, item VARCHAR(50) NOT NULL, orderedBy VARCHAR(50)"
+ ", city VARCHAR(50), state VARCHAR(50), pincode CHAR(6) NOT NULL, PRIMARY KEY(Id))";
final String GET_SCHEMA = "SHOW COLUMNS FROM Orders";
final String INSERT_ORDER = "INSERT INTO Orders (item, orderedBy, city, state, pincode) VALUES(?, ?, ?, ?, ?)";
final String QUERY_ORDERS = "SELECT * FROM Orders";
final String QUERY_ORDER = QUERY_ORDERS + " WHERE Id = ?";
final String REMOVE_ORDER = "DELETE FROM Orders WHERE Id = ?";
final String DELETE_SCHEMA = "DROP TABLE Orders";
boolean createSchema() throws SQLException;
String getSchema() throws SQLException;
boolean insertOrder(Order order) throws SQLException;
Stream<Order> queryOrders() throws SQLException;
Order queryOrder(int id) throws SQLException;
void removeOrder(int id) throws Exception;
boolean deleteSchema() throws Exception;
}
| 2,745
| 38.228571
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/embedded-value/src/main/java/com/iluwatar/embedded/value/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.embedded.value;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* A POJO which represents the Order object.
*/
@ToString
@Setter
@Getter
public class Order {
private int id;
private String item;
private String orderedBy;
private ShippingAddress shippingAddress;
/**
* Constructor for Item object.
* @param item item name
* @param orderedBy item orderer
* @param shippingAddress shipping address details
*/
public Order(String item, String orderedBy, ShippingAddress shippingAddress) {
this.item = item;
this.orderedBy = orderedBy;
this.shippingAddress = shippingAddress;
}
public Order(int id, String item, String orderedBy, ShippingAddress shippingAddress) {
this(item, orderedBy, shippingAddress);
this.id = id;
}
}
| 2,115
| 32.587302
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/embedded-value/src/main/java/com/iluwatar/embedded/value/ShippingAddress.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.embedded.value;
import lombok.Getter;
import lombok.ToString;
/**
* Another POJO which wraps the Shipping details of order into Object.
*/
@ToString
@Getter
public class ShippingAddress {
private String city;
private String state;
private String pincode;
/**
* Constructor for Shipping Address object.
* @param city City name
* @param state State name
* @param pincode Pin code of the city
*
*/
public ShippingAddress(String city, String state, String pincode) {
this.city = city;
this.state = state;
this.pincode = pincode;
}
}
| 1,891
| 33.4
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.embedded.value;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
/**
* Communicates with H2 database with the help of JDBC API.
* Inherits the SQL queries and methods from @link AbstractDataSource class.
*/
@Slf4j
public class DataSource implements DataSourceInterface {
private Connection conn;
// Statements are objects which are used to execute queries which will not be repeated.
private Statement getschema;
private Statement deleteschema;
private Statement queryOrders;
// PreparedStatements are used to execute queries which will be repeated.
private PreparedStatement insertIntoOrders;
private PreparedStatement removeorder;
private PreparedStatement queyOrderById;
/**
* {@summary Establish connection to database.
* Constructor to create DataSource object.}
*/
public DataSource() {
try {
conn = DriverManager.getConnection(JDBC_URL);
LOGGER.info("Connected to H2 in-memory database: " + conn.getCatalog());
} catch (SQLException e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
}
}
@Override
public boolean createSchema() {
try (Statement createschema = conn.createStatement()) {
createschema.execute(CREATE_SCHEMA);
insertIntoOrders = conn.prepareStatement(INSERT_ORDER, PreparedStatement.RETURN_GENERATED_KEYS);
getschema = conn.createStatement();
queryOrders = conn.createStatement();
removeorder = conn.prepareStatement(REMOVE_ORDER);
queyOrderById = conn.prepareStatement(QUERY_ORDER);
deleteschema = conn.createStatement();
} catch (SQLException e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
return false;
}
return true;
}
@Override
public String getSchema() {
try {
var resultSet = getschema.executeQuery(GET_SCHEMA);
var sb = new StringBuilder();
while (resultSet.next()) {
sb.append("Col name: " + resultSet.getString(1) + ", Col type: " + resultSet.getString(2) + "\n");
}
getschema.close();
return sb.toString();
} catch (Exception e) {
LOGGER.error("Error in retrieving schema: {}", e.getLocalizedMessage(), e.getCause());
}
return "Schema unavailable";
}
@Override
public boolean insertOrder(Order order) {
try {
conn.setAutoCommit(false);
insertIntoOrders.setString(1, order.getItem());
insertIntoOrders.setString(2, order.getOrderedBy());
var address = order.getShippingAddress();
insertIntoOrders.setString(3, address.getCity());
insertIntoOrders.setString(4, address.getState());
insertIntoOrders.setString(5, address.getPincode());
var affectedRows = insertIntoOrders.executeUpdate();
if (affectedRows == 1) {
var rs = insertIntoOrders.getGeneratedKeys();
rs.last();
var insertedAddress = new ShippingAddress(address.getCity(), address.getState(), address.getPincode());
var insertedOrder = new Order(rs.getInt(1), order.getItem(), order.getOrderedBy(),
insertedAddress);
conn.commit();
LOGGER.info("Inserted: {}", insertedOrder);
} else {
conn.rollback();
}
} catch (Exception e) {
LOGGER.error(e.getLocalizedMessage());
} finally {
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
LOGGER.error(e.getLocalizedMessage());
}
}
return true;
}
@Override
public Stream<Order> queryOrders() {
var ordersList = new ArrayList<Order>();
try (var rSet = queryOrders.executeQuery(QUERY_ORDERS)) {
while (rSet.next()) {
var order = new Order(rSet.getInt(1), rSet.getString(2), rSet.getString(3),
new ShippingAddress(rSet.getString(4), rSet.getString(5),
rSet.getString(6)));
ordersList.add(order);
}
rSet.close();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e.getCause());
}
return ordersList.stream();
}
/**
* Query order by given id.
* @param id as the parameter
* @return Order objct
* @throws SQLException in case of unexpected events
*/
@Override
public Order queryOrder(int id) throws SQLException {
Order order = null;
queyOrderById.setInt(1, id);
try (var rSet = queyOrderById.executeQuery()) {
queyOrderById.setInt(1, id);
if (rSet.next()) {
var address = new ShippingAddress(rSet.getString(4),
rSet.getString(5), rSet.getString(6));
order = new Order(rSet.getInt(1), rSet.getString(2), rSet.getString(3), address);
}
rSet.close();
} catch (Exception e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
}
return order;
}
@Override
public void removeOrder(int id) throws Exception {
try {
conn.setAutoCommit(false);
removeorder.setInt(1, id);
if (removeorder.executeUpdate() == 1) {
LOGGER.info("Order with id " + id + " successfully removed");
} else {
LOGGER.info("Order with id " + id + " unavailable.");
}
} catch (Exception e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
conn.rollback();
} finally {
conn.setAutoCommit(true);
}
}
@Override
public boolean deleteSchema() throws Exception {
try {
deleteschema.execute(DELETE_SCHEMA);
queryOrders.close();
queyOrderById.close();
deleteschema.close();
insertIntoOrders.close();
conn.close();
return true;
} catch (Exception e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
}
return false;
}
}
| 7,127
| 32.942857
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.facade;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
/**
* Date: 12/9/15 - 9:40 PM
*
* @author Jeroen Meulemeester
*/
class DwarvenGoldmineFacadeTest {
private InMemoryAppender appender;
@BeforeEach
void setUp() {
appender = new InMemoryAppender();
}
@AfterEach
void tearDown() {
appender.stop();
}
/**
* Test a complete day cycle in the gold mine by executing all three different steps: {@link
* DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link
* DwarvenGoldmineFacade#endDay()}.
* <p>
* See if the workers are doing what's expected from them on each step.
*/
@Test
void testFullWorkDay() {
final var goldMine = new DwarvenGoldmineFacade();
goldMine.startNewDay();
// On the start of a day, all workers should wake up ...
assertTrue(appender.logContains("Dwarf gold digger wakes up."));
assertTrue(appender.logContains("Dwarf cart operator wakes up."));
assertTrue(appender.logContains("Dwarven tunnel digger wakes up."));
// ... and go to the mine
assertTrue(appender.logContains("Dwarf gold digger goes to the mine."));
assertTrue(appender.logContains("Dwarf cart operator goes to the mine."));
assertTrue(appender.logContains("Dwarven tunnel digger goes to the mine."));
// No other actions were invoked, so the workers shouldn't have done (printed) anything else
assertEquals(6, appender.getLogSize());
// Now do some actual work, start digging gold!
goldMine.digOutGold();
// Since we gave the dig command, every worker should be doing it's job ...
assertTrue(appender.logContains("Dwarf gold digger digs for gold."));
assertTrue(appender.logContains("Dwarf cart operator moves gold chunks out of the mine."));
assertTrue(appender.logContains("Dwarven tunnel digger creates another promising tunnel."));
// Again, they shouldn't be doing anything else.
assertEquals(9, appender.getLogSize());
// Enough gold, lets end the day.
goldMine.endDay();
// Check if the workers go home ...
assertTrue(appender.logContains("Dwarf gold digger goes home."));
assertTrue(appender.logContains("Dwarf cart operator goes home."));
assertTrue(appender.logContains("Dwarven tunnel digger goes home."));
// ... and go to sleep. We need well rested workers the next day :)
assertTrue(appender.logContains("Dwarf gold digger goes to sleep."));
assertTrue(appender.logContains("Dwarf cart operator goes to sleep."));
assertTrue(appender.logContains("Dwarven tunnel digger goes to sleep."));
// Every worker should be sleeping now, no other actions allowed
assertEquals(15, appender.getLogSize());
}
private static class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
public boolean logContains(String message) {
return log.stream()
.map(ILoggingEvent::getFormattedMessage)
.anyMatch(message::equals);
}
}
}
| 5,043
| 35.28777
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/facade/src/test/java/com/iluwatar/facade/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.facade;
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,585
| 37.682927
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.facade;
import lombok.extern.slf4j.Slf4j;
/**
* DwarvenGoldDigger is one of the goldmine subsystems.
*/
@Slf4j
public class DwarvenGoldDigger extends DwarvenMineWorker {
@Override
public void work() {
LOGGER.info("{} digs for gold.", name());
}
@Override
public String name() {
return "Dwarf gold digger";
}
}
| 1,641
| 35.488889
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.facade;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
/**
* DwarvenMineWorker is one of the goldmine subsystems.
*/
@Slf4j
public abstract class DwarvenMineWorker {
public void goToSleep() {
LOGGER.info("{} goes to sleep.", name());
}
public void wakeUp() {
LOGGER.info("{} wakes up.", name());
}
public void goHome() {
LOGGER.info("{} goes home.", name());
}
public void goToMine() {
LOGGER.info("{} goes to the mine.", name());
}
private void action(Action action) {
switch (action) {
case GO_TO_SLEEP -> goToSleep();
case WAKE_UP -> wakeUp();
case GO_HOME -> goHome();
case GO_TO_MINE -> goToMine();
case WORK -> work();
default -> LOGGER.info("Undefined action");
}
}
/**
* Perform actions.
*/
public void action(Action... actions) {
Arrays.stream(actions).forEach(this::action);
}
public abstract void work();
public abstract String name();
enum Action {
GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK
}
}
| 2,351
| 29.153846
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/facade/src/main/java/com/iluwatar/facade/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.facade;
/**
* The Facade design pattern is often used when a system is very complex or difficult to understand
* because the system has a large number of interdependent classes or its source code is
* unavailable. This pattern hides the complexities of the larger system and provides a simpler
* interface to the client. It typically involves a single wrapper class which contains a set of
* members required by client. These members access the system on behalf of the facade client and
* hide the implementation details.
*
* <p>In this example the Facade is ({@link DwarvenGoldmineFacade}) and it provides a simpler
* interface to the goldmine subsystem.
*/
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var facade = new DwarvenGoldmineFacade();
facade.startNewDay();
facade.digOutGold();
facade.endDay();
}
}
| 2,240
| 42.096154
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.facade;
import lombok.extern.slf4j.Slf4j;
/**
* DwarvenCartOperator is one of the goldmine subsystems.
*/
@Slf4j
public class DwarvenCartOperator extends DwarvenMineWorker {
@Override
public void work() {
LOGGER.info("{} moves gold chunks out of the mine.", name());
}
@Override
public String name() {
return "Dwarf cart operator";
}
}
| 1,667
| 36.066667
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.facade;
import java.util.Collection;
import java.util.List;
/**
* DwarvenGoldmineFacade provides a single interface through which users can operate the
* subsystems.
*
* <p>This makes the goldmine easier to operate and cuts the dependencies from the goldmine user to
* the subsystems.
*/
public class DwarvenGoldmineFacade {
private final List<DwarvenMineWorker> workers;
/**
* Constructor.
*/
public DwarvenGoldmineFacade() {
workers = List.of(
new DwarvenGoldDigger(),
new DwarvenCartOperator(),
new DwarvenTunnelDigger());
}
public void startNewDay() {
makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE);
}
public void digOutGold() {
makeActions(workers, DwarvenMineWorker.Action.WORK);
}
public void endDay() {
makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP);
}
private static void makeActions(
Collection<DwarvenMineWorker> workers,
DwarvenMineWorker.Action... actions
) {
workers.forEach(worker -> worker.action(actions));
}
}
| 2,426
| 33.671429
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.facade;
import lombok.extern.slf4j.Slf4j;
/**
* DwarvenTunnelDigger is one of the goldmine subsystems.
*/
@Slf4j
public class DwarvenTunnelDigger extends DwarvenMineWorker {
@Override
public void work() {
LOGGER.info("{} creates another promising tunnel.", name());
}
@Override
public String name() {
return "Dwarven tunnel digger";
}
}
| 1,668
| 36.088889
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/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.hexagonal;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Unit test for simple App.
*/
class AppTest {
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,598
| 37.071429
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.database;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.hexagonal.domain.LotteryNumbers;
import com.iluwatar.hexagonal.domain.LotteryTicket;
import com.iluwatar.hexagonal.domain.LotteryTicketId;
import com.iluwatar.hexagonal.domain.PlayerDetails;
import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader;
import com.mongodb.MongoClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Tests for Mongo based ticket repository
*/
@Disabled
class MongoTicketRepositoryTest {
private static final String TEST_DB = "lotteryTestDB";
private static final String TEST_TICKETS_COLLECTION = "lotteryTestTickets";
private static final String TEST_COUNTERS_COLLECTION = "testCounters";
private MongoTicketRepository repository;
@BeforeEach
void init() {
MongoConnectionPropertiesLoader.load();
var mongoClient = new MongoClient(System.getProperty("mongo-host"),
Integer.parseInt(System.getProperty("mongo-port")));
mongoClient.dropDatabase(TEST_DB);
mongoClient.close();
repository = new MongoTicketRepository(TEST_DB, TEST_TICKETS_COLLECTION,
TEST_COUNTERS_COLLECTION);
}
@Test
void testSetup() {
assertEquals(1, repository.getCountersCollection().countDocuments());
assertEquals(0, repository.getTicketsCollection().countDocuments());
}
@Test
void testNextId() {
assertEquals(1, repository.getNextId());
assertEquals(2, repository.getNextId());
assertEquals(3, repository.getNextId());
}
@Test
void testCrudOperations() {
// create new lottery ticket and save it
var details = new PlayerDetails("foo@bar.com", "123-123", "07001234");
var random = LotteryNumbers.createRandom();
var original = new LotteryTicket(new LotteryTicketId(), details, random);
var saved = repository.save(original);
assertEquals(1, repository.getTicketsCollection().countDocuments());
assertTrue(saved.isPresent());
// fetch the saved lottery ticket from database and check its contents
var found = repository.findById(saved.get());
assertTrue(found.isPresent());
var ticket = found.get();
assertEquals("foo@bar.com", ticket.getPlayerDetails().getEmail());
assertEquals("123-123", ticket.getPlayerDetails().getBankAccount());
assertEquals("07001234", ticket.getPlayerDetails().getPhoneNumber());
assertEquals(original.getLotteryNumbers(), ticket.getLotteryNumbers());
// clear the collection
repository.deleteAll();
assertEquals(0, repository.getTicketsCollection().countDocuments());
}
}
| 4,018
| 40.010204
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.database;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.hexagonal.test.LotteryTestUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link LotteryTicketRepository}
*/
class InMemoryTicketRepositoryTest {
private final LotteryTicketRepository repository = new InMemoryTicketRepository();
@BeforeEach
void clear() {
repository.deleteAll();
}
@Test
void testCrudOperations() {
var repository = new InMemoryTicketRepository();
assertTrue(repository.findAll().isEmpty());
var ticket = LotteryTestUtils.createLotteryTicket();
var id = repository.save(ticket);
assertTrue(id.isPresent());
assertEquals(1, repository.findAll().size());
var optionalTicket = repository.findById(id.get());
assertTrue(optionalTicket.isPresent());
}
}
| 2,240
| 37.637931
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.test;
import com.iluwatar.hexagonal.domain.LotteryNumbers;
import com.iluwatar.hexagonal.domain.LotteryTicket;
import com.iluwatar.hexagonal.domain.LotteryTicketId;
import com.iluwatar.hexagonal.domain.PlayerDetails;
import java.util.Set;
/**
* Utilities for lottery tests
*/
public class LotteryTestUtils {
/**
* @return lottery ticket
*/
public static LotteryTicket createLotteryTicket() {
return createLotteryTicket("foo@bar.com", "12231-213132", "+99324554", Set.of(1, 2, 3, 4));
}
/**
* @return lottery ticket
*/
public static LotteryTicket createLotteryTicket(String email, String account, String phone,
Set<Integer> givenNumbers) {
var details = new PlayerDetails(email, account, phone);
var numbers = LotteryNumbers.create(givenNumbers);
return new LotteryTicket(new LotteryTicketId(), details, numbers);
}
}
| 2,228
| 39.527273
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.eventlog;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.hexagonal.domain.PlayerDetails;
import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader;
import com.mongodb.MongoClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Tests for Mongo event log
*/
@Disabled
class MongoEventLogTest {
private static final String TEST_DB = "lotteryDBTest";
private static final String TEST_EVENTS_COLLECTION = "testEvents";
private MongoEventLog mongoEventLog;
@BeforeEach
void init() {
MongoConnectionPropertiesLoader.load();
var mongoClient = new MongoClient(System.getProperty("mongo-host"),
Integer.parseInt(System.getProperty("mongo-port")));
mongoClient.dropDatabase(TEST_DB);
mongoClient.close();
mongoEventLog = new MongoEventLog(TEST_DB, TEST_EVENTS_COLLECTION);
}
@Test
void testSetup() {
assertEquals(0, mongoEventLog.getEventsCollection().countDocuments());
}
@Test
void testFundTransfers() {
var playerDetails = new PlayerDetails("john@wayne.com", "000-000", "03432534543");
mongoEventLog.prizeError(playerDetails, 1000);
assertEquals(1, mongoEventLog.getEventsCollection().countDocuments());
mongoEventLog.prizeError(playerDetails, 1000);
assertEquals(2, mongoEventLog.getEventsCollection().countDocuments());
mongoEventLog.ticketDidNotWin(playerDetails);
assertEquals(3, mongoEventLog.getEventsCollection().countDocuments());
mongoEventLog.ticketDidNotWin(playerDetails);
assertEquals(4, mongoEventLog.getEventsCollection().countDocuments());
mongoEventLog.ticketSubmitError(playerDetails);
assertEquals(5, mongoEventLog.getEventsCollection().countDocuments());
mongoEventLog.ticketSubmitError(playerDetails);
assertEquals(6, mongoEventLog.getEventsCollection().countDocuments());
mongoEventLog.ticketSubmitted(playerDetails);
assertEquals(7, mongoEventLog.getEventsCollection().countDocuments());
mongoEventLog.ticketSubmitted(playerDetails);
assertEquals(8, mongoEventLog.getEventsCollection().countDocuments());
mongoEventLog.ticketWon(playerDetails, 1000);
assertEquals(9, mongoEventLog.getEventsCollection().countDocuments());
mongoEventLog.ticketWon(playerDetails, 1000);
assertEquals(10, mongoEventLog.getEventsCollection().countDocuments());
}
}
| 3,742
| 42.022989
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link LotteryTicketCheckResult}
*/
class LotteryTicketCheckResultTest {
@Test
void testEquals() {
var result1 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE);
var result2 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE);
assertEquals(result1, result2);
var result3 = new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 300000);
assertNotEquals(result1, result3);
}
}
| 1,988
| 41.319149
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Set;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link LotteryNumbers}
*/
class LotteryNumbersTest {
@Test
void testGivenNumbers() {
var numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4));
assertEquals(numbers.getNumbers().size(), 4);
assertTrue(numbers.getNumbers().contains(1));
assertTrue(numbers.getNumbers().contains(2));
assertTrue(numbers.getNumbers().contains(3));
assertTrue(numbers.getNumbers().contains(4));
}
@Test
void testNumbersCantBeModified() {
var numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4));
assertThrows(UnsupportedOperationException.class, () -> numbers.getNumbers().add(5));
}
@Test
void testRandomNumbers() {
var numbers = LotteryNumbers.createRandom();
assertEquals(numbers.getNumbers().size(), LotteryNumbers.NUM_NUMBERS);
}
@Test
void testEquals() {
var numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4));
var numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4));
assertEquals(numbers1, numbers2);
var numbers3 = LotteryNumbers.create(Set.of(11, 12, 13, 14));
assertNotEquals(numbers1, numbers3);
}
}
| 2,729
| 37.450704
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.util.Set;
import org.junit.jupiter.api.Test;
/**
* Test Lottery Tickets for equality
*/
class LotteryTicketTest {
@Test
void testEquals() {
var details1 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322");
var numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4));
var ticket1 = new LotteryTicket(new LotteryTicketId(), details1, numbers1);
var details2 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322");
var numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4));
var ticket2 = new LotteryTicket(new LotteryTicketId(), details2, numbers2);
assertEquals(ticket1, ticket2);
var details3 = new PlayerDetails("elsa@foo.bar", "1223-121212", "+49332322");
var numbers3 = LotteryNumbers.create(Set.of(1, 2, 3, 8));
var ticket3 = new LotteryTicket(new LotteryTicketId(), details3, numbers3);
assertNotEquals(ticket1, ticket3);
}
}
| 2,361
| 43.566038
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link PlayerDetails}
*/
class PlayerDetailsTest {
@Test
void testEquals() {
var details1 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425");
var details2 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425");
assertEquals(details1, details2);
var details3 = new PlayerDetails("john@foo.bar", "16412-123439", "+34323432");
assertNotEquals(details1, details3);
}
}
| 1,923
| 40.826087
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;
/**
* Tests for lottery ticket id
*/
class LotteryTicketIdTest {
@Test
void testEquals() {
var ticketId1 = new LotteryTicketId();
var ticketId2 = new LotteryTicketId();
var ticketId3 = new LotteryTicketId();
assertNotEquals(ticketId1, ticketId2);
assertNotEquals(ticketId2, ticketId3);
var ticketId4 = new LotteryTicketId(ticketId1.getId());
assertEquals(ticketId1, ticketId4);
}
}
| 1,905
| 38.708333
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult;
import com.iluwatar.hexagonal.module.LotteryTestingModule;
import com.iluwatar.hexagonal.test.LotteryTestUtils;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test the lottery system
*/
class LotteryTest {
private final Injector injector;
@Inject
private LotteryAdministration administration;
@Inject
private LotteryService service;
@Inject
private WireTransfers wireTransfers;
LotteryTest() {
this.injector = Guice.createInjector(new LotteryTestingModule());
}
@BeforeEach
void setup() {
injector.injectMembers(this);
// add funds to the test player's bank account
wireTransfers.setFunds("123-12312", 100);
}
@Test
void testLottery() {
// admin resets the lottery
administration.resetLottery();
assertEquals(0, administration.getAllSubmittedTickets().size());
// players submit the lottery tickets
var ticket1 = service.submitTicket(LotteryTestUtils.createLotteryTicket("cvt@bbb.com",
"123-12312", "+32425255", Set.of(1, 2, 3, 4)));
assertTrue(ticket1.isPresent());
var ticket2 = service.submitTicket(LotteryTestUtils.createLotteryTicket("ant@bac.com",
"123-12312", "+32423455", Set.of(11, 12, 13, 14)));
assertTrue(ticket2.isPresent());
var ticket3 = service.submitTicket(LotteryTestUtils.createLotteryTicket("arg@boo.com",
"123-12312", "+32421255", Set.of(6, 8, 13, 19)));
assertTrue(ticket3.isPresent());
assertEquals(3, administration.getAllSubmittedTickets().size());
// perform lottery
var winningNumbers = administration.performLottery();
// cheat a bit for testing sake, use winning numbers to submit another ticket
var ticket4 = service.submitTicket(LotteryTestUtils.createLotteryTicket("lucky@orb.com",
"123-12312", "+12421255", winningNumbers.getNumbers()));
assertTrue(ticket4.isPresent());
assertEquals(4, administration.getAllSubmittedTickets().size());
// check winners
var tickets = administration.getAllSubmittedTickets();
for (var id : tickets.keySet()) {
var checkResult = service.checkTicketForPrize(id, winningNumbers);
assertNotEquals(CheckResult.TICKET_NOT_SUBMITTED, checkResult.getResult());
if (checkResult.getResult().equals(CheckResult.WIN_PRIZE)) {
assertTrue(checkResult.getPrizeAmount() > 0);
} else {
assertEquals(0, checkResult.getPrizeAmount());
}
}
// check another ticket that has not been submitted
var checkResult = service.checkTicketForPrize(new LotteryTicketId(), winningNumbers);
assertEquals(CheckResult.TICKET_NOT_SUBMITTED, checkResult.getResult());
assertEquals(0, checkResult.getPrizeAmount());
}
}
| 4,477
| 39.342342
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java
|
package com.iluwatar.hexagonal.banking;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfig;
import de.flapdoodle.embed.mongo.distribution.Version;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
/**
* Tests for Mongo banking adapter
*/
class MongoBankTest {
private static final String TEST_DB = "lotteryDBTest";
private static final String TEST_ACCOUNTS_COLLECTION = "testAccounts";
private static final String TEST_HOST = "localhost";
private static final int TEST_PORT = 27017;
private static MongodExecutable mongodExe;
private static MongodProcess mongodProcess;
private static MongoClient mongoClient;
private static MongoDatabase mongoDatabase;
private MongoBank mongoBank;
@BeforeAll
static void setUp() throws Exception {
MongodStarter starter = MongodStarter.getDefaultInstance();
MongodConfig mongodConfig = buildMongoConfig();
mongoClient = buildMongoClient();
mongodExe = starter.prepare(mongodConfig);
mongodProcess = mongodExe.start();
mongoDatabase = mongoClient.getDatabase(TEST_DB);
}
@BeforeEach
void init() {
System.setProperty("mongo-host", TEST_HOST);
System.setProperty("mongo-port", String.valueOf(TEST_PORT));
mongoDatabase.drop();
mongoBank = new MongoBank(mongoDatabase.getName(), TEST_ACCOUNTS_COLLECTION);
}
@AfterAll
static void tearDown() {
mongoClient.close();
mongodProcess.stop();
mongodExe.stop();
}
@Test
void testSetup() {
assertEquals(0, mongoBank.getAccountsCollection().countDocuments());
}
@Test
void testFundTransfers() {
assertEquals(0, mongoBank.getFunds("000-000"));
mongoBank.setFunds("000-000", 10);
assertEquals(10, mongoBank.getFunds("000-000"));
assertEquals(0, mongoBank.getFunds("111-111"));
mongoBank.transferFunds(9, "000-000", "111-111");
assertEquals(1, mongoBank.getFunds("000-000"));
assertEquals(9, mongoBank.getFunds("111-111"));
}
private static MongodConfig buildMongoConfig() {
return MongodConfig.builder()
.version(Version.Main.PRODUCTION)
.net(new de.flapdoodle.embed.mongo.config.Net(TEST_HOST, TEST_PORT, true))
.build();
}
private static MongoClient buildMongoClient() {
return MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder -> builder.hosts(List.of(new ServerAddress(TEST_HOST, TEST_PORT))))
.build()
);
}
}
| 2,997
| 30.229167
| 115
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.banking;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Tests for banking
*/
class InMemoryBankTest {
private final WireTransfers bank = new InMemoryBank();
@Test
void testInit() {
assertEquals(0, bank.getFunds("foo"));
bank.setFunds("foo", 100);
assertEquals(100, bank.getFunds("foo"));
bank.setFunds("bar", 150);
assertEquals(150, bank.getFunds("bar"));
assertTrue(bank.transferFunds(50, "bar", "foo"));
assertEquals(150, bank.getFunds("foo"));
assertEquals(100, bank.getFunds("bar"));
}
}
| 1,968
| 37.607843
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/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.hexagonal;
import com.google.inject.Guice;
import com.iluwatar.hexagonal.domain.LotteryAdministration;
import com.iluwatar.hexagonal.domain.LotteryService;
import com.iluwatar.hexagonal.module.LotteryTestingModule;
import com.iluwatar.hexagonal.sampledata.SampleData;
/**
* Hexagonal Architecture pattern decouples the application core from the services it uses. This
* allows the services to be plugged in and the application will run with or without the services.
*
* <p>The core logic, or business logic, of an application consists of the algorithms that are
* essential to its purpose. They implement the use cases that are the heart of the application.
* When you change them, you change the essence of the application.
*
* <p>The services are not essential. They can be replaced without changing the purpose of the
* application. Examples: database access and other types of storage, user interface components,
* e-mail and other communication components, hardware devices.
*
* <p>This example demonstrates Hexagonal Architecture with a lottery system. The application core
* is separate from the services that drive it and from the services it uses.
*
* <p>The primary ports for the application are console interfaces {@link
* com.iluwatar.hexagonal.administration.ConsoleAdministration} through which the lottery round is
* initiated and run and {@link com.iluwatar.hexagonal.service.ConsoleLottery} that allows players
* to submit lottery tickets for the draw.
*
* <p>The secondary ports that application core uses are{@link
* com.iluwatar.hexagonal.banking.WireTransfers} which is a banking service, {@link
* com.iluwatar.hexagonal.eventlog.LotteryEventLog} that delivers eventlog as lottery events occur
* and {@link com.iluwatar.hexagonal.database.LotteryTicketRepository} that is the storage for the
* lottery tickets.
*/
public class App {
/**
* Program entry point.
*/
public static void main(String[] args) {
var injector = Guice.createInjector(new LotteryTestingModule());
// start new lottery round
var administration = injector.getInstance(LotteryAdministration.class);
administration.resetLottery();
// submit some lottery tickets
var service = injector.getInstance(LotteryService.class);
SampleData.submitTickets(service, 20);
// perform lottery
administration.performLottery();
}
}
| 3,689
| 45.125
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.mongo;
import java.io.FileInputStream;
import java.util.Properties;
/**
* Mongo connection properties loader.
*/
public class MongoConnectionPropertiesLoader {
private static final String DEFAULT_HOST = "localhost";
private static final int DEFAULT_PORT = 27017;
/**
* Try to load connection properties from file. Fall back to default connection properties.
*/
public static void load() {
var host = DEFAULT_HOST;
var port = DEFAULT_PORT;
var path = System.getProperty("hexagonal.properties.path");
var properties = new Properties();
if (path != null) {
try (var fin = new FileInputStream(path)) {
properties.load(fin);
host = properties.getProperty("mongo-host");
port = Integer.parseInt(properties.getProperty("mongo-port"));
} catch (Exception e) {
// error occurred, use default properties
e.printStackTrace();
}
}
System.setProperty("mongo-host", host);
System.setProperty("mongo-port", String.format("%d", port));
}
}
| 2,351
| 38.2
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.database;
import com.iluwatar.hexagonal.domain.LotteryTicket;
import com.iluwatar.hexagonal.domain.LotteryTicketId;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Mock database for lottery tickets.
*/
public class InMemoryTicketRepository implements LotteryTicketRepository {
private static final Map<LotteryTicketId, LotteryTicket> tickets = new HashMap<>();
@Override
public Optional<LotteryTicket> findById(LotteryTicketId id) {
return Optional.ofNullable(tickets.get(id));
}
@Override
public Optional<LotteryTicketId> save(LotteryTicket ticket) {
var id = new LotteryTicketId();
tickets.put(id, ticket);
return Optional.of(id);
}
@Override
public Map<LotteryTicketId, LotteryTicket> findAll() {
return tickets;
}
@Override
public void deleteAll() {
tickets.clear();
}
}
| 2,182
| 34.209677
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.database;
import com.iluwatar.hexagonal.domain.LotteryTicket;
import com.iluwatar.hexagonal.domain.LotteryTicketId;
import java.util.Map;
import java.util.Optional;
/**
* Interface for accessing lottery tickets in database.
*/
public interface LotteryTicketRepository {
/**
* Find lottery ticket by id.
*/
Optional<LotteryTicket> findById(LotteryTicketId id);
/**
* Save lottery ticket.
*/
Optional<LotteryTicketId> save(LotteryTicket ticket);
/**
* Get all lottery tickets.
*/
Map<LotteryTicketId, LotteryTicket> findAll();
/**
* Delete all lottery tickets.
*/
void deleteAll();
}
| 1,946
| 32.568966
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.database;
import com.iluwatar.hexagonal.domain.LotteryNumbers;
import com.iluwatar.hexagonal.domain.LotteryTicket;
import com.iluwatar.hexagonal.domain.LotteryTicketId;
import com.iluwatar.hexagonal.domain.PlayerDetails;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.bson.Document;
/**
* Mongo lottery ticket database.
*/
public class MongoTicketRepository implements LotteryTicketRepository {
private static final String DEFAULT_DB = "lotteryDB";
private static final String DEFAULT_TICKETS_COLLECTION = "lotteryTickets";
private static final String DEFAULT_COUNTERS_COLLECTION = "counters";
private static final String TICKET_ID = "ticketId";
private MongoClient mongoClient;
private MongoDatabase database;
private MongoCollection<Document> ticketsCollection;
private MongoCollection<Document> countersCollection;
/**
* Constructor.
*/
public MongoTicketRepository() {
connect();
}
/**
* Constructor accepting parameters.
*/
public MongoTicketRepository(String dbName, String ticketsCollectionName,
String countersCollectionName) {
connect(dbName, ticketsCollectionName, countersCollectionName);
}
/**
* Connect to database with default parameters.
*/
public void connect() {
connect(DEFAULT_DB, DEFAULT_TICKETS_COLLECTION, DEFAULT_COUNTERS_COLLECTION);
}
/**
* Connect to database with given parameters.
*/
public void connect(String dbName, String ticketsCollectionName,
String countersCollectionName) {
if (mongoClient != null) {
mongoClient.close();
}
mongoClient = new MongoClient(System.getProperty("mongo-host"),
Integer.parseInt(System.getProperty("mongo-port")));
database = mongoClient.getDatabase(dbName);
ticketsCollection = database.getCollection(ticketsCollectionName);
countersCollection = database.getCollection(countersCollectionName);
if (countersCollection.countDocuments() <= 0) {
initCounters();
}
}
private void initCounters() {
var doc = new Document("_id", TICKET_ID).append("seq", 1);
countersCollection.insertOne(doc);
}
/**
* Get next ticket id.
*
* @return next ticket id
*/
public int getNextId() {
var find = new Document("_id", TICKET_ID);
var increase = new Document("seq", 1);
var update = new Document("$inc", increase);
var result = countersCollection.findOneAndUpdate(find, update);
return result.getInteger("seq");
}
/**
* Get tickets collection.
*
* @return tickets collection
*/
public MongoCollection<Document> getTicketsCollection() {
return ticketsCollection;
}
/**
* Get counters collection.
*
* @return counters collection
*/
public MongoCollection<Document> getCountersCollection() {
return countersCollection;
}
@Override
public Optional<LotteryTicket> findById(LotteryTicketId id) {
return ticketsCollection
.find(new Document(TICKET_ID, id.getId()))
.limit(1)
.into(new ArrayList<>())
.stream()
.findFirst()
.map(this::docToTicket);
}
@Override
public Optional<LotteryTicketId> save(LotteryTicket ticket) {
var ticketId = getNextId();
var doc = new Document(TICKET_ID, ticketId);
doc.put("email", ticket.getPlayerDetails().getEmail());
doc.put("bank", ticket.getPlayerDetails().getBankAccount());
doc.put("phone", ticket.getPlayerDetails().getPhoneNumber());
doc.put("numbers", ticket.getLotteryNumbers().getNumbersAsString());
ticketsCollection.insertOne(doc);
return Optional.of(new LotteryTicketId(ticketId));
}
@Override
public Map<LotteryTicketId, LotteryTicket> findAll() {
return ticketsCollection
.find(new Document())
.into(new ArrayList<>())
.stream()
.map(this::docToTicket)
.collect(Collectors.toMap(LotteryTicket::getId, Function.identity()));
}
@Override
public void deleteAll() {
ticketsCollection.deleteMany(new Document());
}
private LotteryTicket docToTicket(Document doc) {
var playerDetails = new PlayerDetails(doc.getString("email"), doc.getString("bank"),
doc.getString("phone"));
var numbers = Arrays.stream(doc.getString("numbers").split(","))
.map(Integer::parseInt)
.collect(Collectors.toSet());
var lotteryNumbers = LotteryNumbers.create(numbers);
var ticketId = new LotteryTicketId(doc.getInteger(TICKET_ID));
return new LotteryTicket(ticketId, playerDetails, lotteryNumbers);
}
}
| 6,128
| 32.675824
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.service;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.domain.LotteryNumbers;
import com.iluwatar.hexagonal.domain.LotteryService;
import com.iluwatar.hexagonal.domain.LotteryTicket;
import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult;
import com.iluwatar.hexagonal.domain.LotteryTicketId;
import com.iluwatar.hexagonal.domain.PlayerDetails;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
import org.slf4j.Logger;
/**
* Console implementation for lottery console service.
*/
public class LotteryConsoleServiceImpl implements LotteryConsoleService {
private final Logger logger;
/**
* Constructor.
*/
public LotteryConsoleServiceImpl(Logger logger) {
this.logger = logger;
}
@Override
public void checkTicket(LotteryService service, Scanner scanner) {
logger.info("What is the ID of the lottery ticket?");
var id = readString(scanner);
logger.info("Give the 4 comma separated winning numbers?");
var numbers = readString(scanner);
try {
var winningNumbers = Arrays.stream(numbers.split(","))
.map(Integer::parseInt)
.limit(4)
.collect(Collectors.toSet());
final var lotteryTicketId = new LotteryTicketId(Integer.parseInt(id));
final var lotteryNumbers = LotteryNumbers.create(winningNumbers);
var result = service.checkTicketForPrize(lotteryTicketId, lotteryNumbers);
if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) {
logger.info("Congratulations! The lottery ticket has won!");
} else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) {
logger.info("Unfortunately the lottery ticket did not win.");
} else {
logger.info("Such lottery ticket has not been submitted.");
}
} catch (Exception e) {
logger.info("Failed checking the lottery ticket - please try again.");
}
}
@Override
public void submitTicket(LotteryService service, Scanner scanner) {
logger.info("What is your email address?");
var email = readString(scanner);
logger.info("What is your bank account number?");
var account = readString(scanner);
logger.info("What is your phone number?");
var phone = readString(scanner);
var details = new PlayerDetails(email, account, phone);
logger.info("Give 4 comma separated lottery numbers?");
var numbers = readString(scanner);
try {
var chosen = Arrays.stream(numbers.split(","))
.map(Integer::parseInt)
.collect(Collectors.toSet());
var lotteryNumbers = LotteryNumbers.create(chosen);
var lotteryTicket = new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers);
service.submitTicket(lotteryTicket).ifPresentOrElse(
(id) -> logger.info("Submitted lottery ticket with id: {}", id),
() -> logger.info("Failed submitting lottery ticket - please try again.")
);
} catch (Exception e) {
logger.info("Failed submitting lottery ticket - please try again.");
}
}
@Override
public void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) {
logger.info("What is the account number?");
var account = readString(scanner);
logger.info("How many credits do you want to deposit?");
var amount = readString(scanner);
bank.setFunds(account, Integer.parseInt(amount));
logger.info("The account {} now has {} credits.", account, bank.getFunds(account));
}
@Override
public void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner) {
logger.info("What is the account number?");
var account = readString(scanner);
logger.info("The account {} has {} credits.", account, bank.getFunds(account));
}
private String readString(Scanner scanner) {
logger.info("> ");
return scanner.next();
}
}
| 5,224
| 39.503876
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.service;
import com.google.inject.Guice;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.domain.LotteryService;
import com.iluwatar.hexagonal.module.LotteryModule;
import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader;
import java.util.Scanner;
import lombok.extern.slf4j.Slf4j;
/**
* Console interface for lottery players.
*/
@Slf4j
public class ConsoleLottery {
/**
* Program entry point.
*/
public static void main(String[] args) {
MongoConnectionPropertiesLoader.load();
var injector = Guice.createInjector(new LotteryModule());
var service = injector.getInstance(LotteryService.class);
var bank = injector.getInstance(WireTransfers.class);
try (Scanner scanner = new Scanner(System.in)) {
var exit = false;
while (!exit) {
printMainMenu();
var cmd = readString(scanner);
var lotteryConsoleService = new LotteryConsoleServiceImpl(LOGGER);
if ("1".equals(cmd)) {
lotteryConsoleService.queryLotteryAccountFunds(bank, scanner);
} else if ("2".equals(cmd)) {
lotteryConsoleService.addFundsToLotteryAccount(bank, scanner);
} else if ("3".equals(cmd)) {
lotteryConsoleService.submitTicket(service, scanner);
} else if ("4".equals(cmd)) {
lotteryConsoleService.checkTicket(service, scanner);
} else if ("5".equals(cmd)) {
exit = true;
} else {
LOGGER.info("Unknown command");
}
}
}
}
private static void printMainMenu() {
LOGGER.info("");
LOGGER.info("### Lottery Service Console ###");
LOGGER.info("(1) Query lottery account funds");
LOGGER.info("(2) Add funds to lottery account");
LOGGER.info("(3) Submit ticket");
LOGGER.info("(4) Check ticket");
LOGGER.info("(5) Exit");
}
private static String readString(Scanner scanner) {
LOGGER.info("> ");
return scanner.next();
}
}
| 3,282
| 36.735632
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.service;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.domain.LotteryService;
import java.util.Scanner;
/**
* Console interface for lottery service.
*/
public interface LotteryConsoleService {
void checkTicket(LotteryService service, Scanner scanner);
/**
* Submit lottery ticket to participate in the lottery.
*/
void submitTicket(LotteryService service, Scanner scanner);
/**
* Add funds to lottery account.
*/
void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner);
/**
* Recovery funds from lottery account.
*/
void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner);
}
| 1,992
| 34.589286
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.administration;
import com.google.inject.Guice;
import com.iluwatar.hexagonal.domain.LotteryAdministration;
import com.iluwatar.hexagonal.domain.LotteryService;
import com.iluwatar.hexagonal.module.LotteryModule;
import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader;
import com.iluwatar.hexagonal.sampledata.SampleData;
import java.util.Scanner;
import lombok.extern.slf4j.Slf4j;
/**
* Console interface for lottery administration.
*/
@Slf4j
public class ConsoleAdministration {
/**
* Program entry point.
*/
public static void main(String[] args) {
MongoConnectionPropertiesLoader.load();
var injector = Guice.createInjector(new LotteryModule());
var administration = injector.getInstance(LotteryAdministration.class);
var service = injector.getInstance(LotteryService.class);
SampleData.submitTickets(service, 20);
var consoleAdministration = new ConsoleAdministrationSrvImpl(administration, LOGGER);
try (var scanner = new Scanner(System.in)) {
var exit = false;
while (!exit) {
printMainMenu();
var cmd = readString(scanner);
if ("1".equals(cmd)) {
consoleAdministration.getAllSubmittedTickets();
} else if ("2".equals(cmd)) {
consoleAdministration.performLottery();
} else if ("3".equals(cmd)) {
consoleAdministration.resetLottery();
} else if ("4".equals(cmd)) {
exit = true;
} else {
LOGGER.info("Unknown command: {}", cmd);
}
}
}
}
private static void printMainMenu() {
LOGGER.info("");
LOGGER.info("### Lottery Administration Console ###");
LOGGER.info("(1) Show all submitted tickets");
LOGGER.info("(2) Perform lottery draw");
LOGGER.info("(3) Reset lottery ticket database");
LOGGER.info("(4) Exit");
}
private static String readString(Scanner scanner) {
LOGGER.info("> ");
return scanner.next();
}
}
| 3,266
| 36.988372
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.administration;
/**
* Console interface for lottery administration.
*/
public interface ConsoleAdministrationSrv {
/**
* Get all submitted tickets.
*/
void getAllSubmittedTickets();
/**
* Draw lottery numbers.
*/
void performLottery();
/**
* Begin new lottery round.
*/
void resetLottery();
}
| 1,644
| 34
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.administration;
import com.iluwatar.hexagonal.domain.LotteryAdministration;
import com.iluwatar.hexagonal.domain.LotteryNumbers;
import org.slf4j.Logger;
/**
* Console implementation for lottery administration.
*/
public class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv {
private final LotteryAdministration administration;
private final Logger logger;
/**
* Constructor.
*/
public ConsoleAdministrationSrvImpl(LotteryAdministration administration, Logger logger) {
this.administration = administration;
this.logger = logger;
}
@Override
public void getAllSubmittedTickets() {
administration.getAllSubmittedTickets()
.forEach((k, v) -> logger.info("Key: {}, Value: {}", k, v));
}
@Override
public void performLottery() {
var numbers = administration.performLottery();
logger.info("The winning numbers: {}", numbers.getNumbersAsString());
logger.info("Time to reset the database for next round, eh?");
}
@Override
public void resetLottery() {
administration.resetLottery();
logger.info("The lottery ticket database was cleared.");
}
}
| 2,453
| 36.753846
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.module;
import com.google.inject.AbstractModule;
import com.iluwatar.hexagonal.banking.InMemoryBank;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.database.InMemoryTicketRepository;
import com.iluwatar.hexagonal.database.LotteryTicketRepository;
import com.iluwatar.hexagonal.eventlog.LotteryEventLog;
import com.iluwatar.hexagonal.eventlog.StdOutEventLog;
/**
* Guice module for testing dependencies.
*/
public class LotteryTestingModule extends AbstractModule {
@Override
protected void configure() {
bind(LotteryTicketRepository.class).to(InMemoryTicketRepository.class);
bind(LotteryEventLog.class).to(StdOutEventLog.class);
bind(WireTransfers.class).to(InMemoryBank.class);
}
}
| 2,057
| 43.73913
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.module;
import com.google.inject.AbstractModule;
import com.iluwatar.hexagonal.banking.MongoBank;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.database.LotteryTicketRepository;
import com.iluwatar.hexagonal.database.MongoTicketRepository;
import com.iluwatar.hexagonal.eventlog.LotteryEventLog;
import com.iluwatar.hexagonal.eventlog.MongoEventLog;
/**
* Guice module for binding production dependencies.
*/
public class LotteryModule extends AbstractModule {
@Override
protected void configure() {
bind(LotteryTicketRepository.class).to(MongoTicketRepository.class);
bind(LotteryEventLog.class).to(MongoEventLog.class);
bind(WireTransfers.class).to(MongoBank.class);
}
}
| 2,047
| 43.521739
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.eventlog;
import com.iluwatar.hexagonal.domain.PlayerDetails;
/**
* Event log for lottery events.
*/
public interface LotteryEventLog {
/**
* lottery ticket submitted.
*/
void ticketSubmitted(PlayerDetails details);
/**
* error submitting lottery ticket.
*/
void ticketSubmitError(PlayerDetails details);
/**
* lottery ticket did not win.
*/
void ticketDidNotWin(PlayerDetails details);
/**
* lottery ticket won.
*/
void ticketWon(PlayerDetails details, int prizeAmount);
/**
* error paying the prize.
*/
void prizeError(PlayerDetails details, int prizeAmount);
}
| 1,939
| 31.333333
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.eventlog;
import com.iluwatar.hexagonal.domain.PlayerDetails;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
/**
* Mongo based event log.
*/
public class MongoEventLog implements LotteryEventLog {
private static final String DEFAULT_DB = "lotteryDB";
private static final String DEFAULT_EVENTS_COLLECTION = "events";
private static final String EMAIL = "email";
private static final String PHONE = "phone";
public static final String MESSAGE = "message";
private MongoClient mongoClient;
private MongoDatabase database;
private MongoCollection<Document> eventsCollection;
private final StdOutEventLog stdOutEventLog = new StdOutEventLog();
/**
* Constructor.
*/
public MongoEventLog() {
connect();
}
/**
* Constructor accepting parameters.
*/
public MongoEventLog(String dbName, String eventsCollectionName) {
connect(dbName, eventsCollectionName);
}
/**
* Connect to database with default parameters.
*/
public void connect() {
connect(DEFAULT_DB, DEFAULT_EVENTS_COLLECTION);
}
/**
* Connect to database with given parameters.
*/
public void connect(String dbName, String eventsCollectionName) {
if (mongoClient != null) {
mongoClient.close();
}
mongoClient = new MongoClient(System.getProperty("mongo-host"),
Integer.parseInt(System.getProperty("mongo-port")));
database = mongoClient.getDatabase(dbName);
eventsCollection = database.getCollection(eventsCollectionName);
}
/**
* Get mongo client.
*
* @return mongo client
*/
public MongoClient getMongoClient() {
return mongoClient;
}
/**
* Get mongo database.
*
* @return mongo database
*/
public MongoDatabase getMongoDatabase() {
return database;
}
/**
* Get events collection.
*
* @return events collection
*/
public MongoCollection<Document> getEventsCollection() {
return eventsCollection;
}
@Override
public void ticketSubmitted(PlayerDetails details) {
var document = new Document(EMAIL, details.getEmail());
document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
document
.put(MESSAGE, "Lottery ticket was submitted and bank account was charged for 3 credits.");
eventsCollection.insertOne(document);
stdOutEventLog.ticketSubmitted(details);
}
@Override
public void ticketSubmitError(PlayerDetails details) {
var document = new Document(EMAIL, details.getEmail());
document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
document.put(MESSAGE, "Lottery ticket could not be submitted because lack of funds.");
eventsCollection.insertOne(document);
stdOutEventLog.ticketSubmitError(details);
}
@Override
public void ticketDidNotWin(PlayerDetails details) {
var document = new Document(EMAIL, details.getEmail());
document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
document.put(MESSAGE, "Lottery ticket was checked and unfortunately did not win this time.");
eventsCollection.insertOne(document);
stdOutEventLog.ticketDidNotWin(details);
}
@Override
public void ticketWon(PlayerDetails details, int prizeAmount) {
var document = new Document(EMAIL, details.getEmail());
document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
document.put(MESSAGE, String
.format("Lottery ticket won! The bank account was deposited with %d credits.",
prizeAmount));
eventsCollection.insertOne(document);
stdOutEventLog.ticketWon(details, prizeAmount);
}
@Override
public void prizeError(PlayerDetails details, int prizeAmount) {
var document = new Document(EMAIL, details.getEmail());
document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
document.put(MESSAGE, String
.format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.",
prizeAmount));
eventsCollection.insertOne(document);
stdOutEventLog.prizeError(details, prizeAmount);
}
}
| 5,607
| 32.580838
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.eventlog;
import com.iluwatar.hexagonal.domain.PlayerDetails;
import lombok.extern.slf4j.Slf4j;
/**
* Standard output event log.
*/
@Slf4j
public class StdOutEventLog implements LotteryEventLog {
@Override
public void ticketSubmitted(PlayerDetails details) {
LOGGER.info("Lottery ticket for {} was submitted. Bank account {} was charged for 3 credits.",
details.getEmail(), details.getBankAccount());
}
@Override
public void ticketDidNotWin(PlayerDetails details) {
LOGGER.info("Lottery ticket for {} was checked and unfortunately did not win this time.",
details.getEmail());
}
@Override
public void ticketWon(PlayerDetails details, int prizeAmount) {
LOGGER.info("Lottery ticket for {} has won! The bank account {} was deposited with {} credits.",
details.getEmail(), details.getBankAccount(), prizeAmount);
}
@Override
public void prizeError(PlayerDetails details, int prizeAmount) {
LOGGER.error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of"
+ " {} failed.", details.getEmail(), prizeAmount);
}
@Override
public void ticketSubmitError(PlayerDetails details) {
LOGGER.error("Lottery ticket for {} could not be submitted because the credit transfer"
+ " of 3 credits failed.", details.getEmail());
}
}
| 2,647
| 39.121212
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.sampledata;
import com.iluwatar.hexagonal.banking.InMemoryBank;
import com.iluwatar.hexagonal.domain.LotteryConstants;
import com.iluwatar.hexagonal.domain.LotteryNumbers;
import com.iluwatar.hexagonal.domain.LotteryService;
import com.iluwatar.hexagonal.domain.LotteryTicket;
import com.iluwatar.hexagonal.domain.LotteryTicketId;
import com.iluwatar.hexagonal.domain.PlayerDetails;
import java.security.SecureRandom;
import java.util.AbstractMap.SimpleEntry;
import java.util.List;
import java.util.stream.Collectors;
/**
* Utilities for creating sample lottery tickets.
*/
public class SampleData {
private static final List<PlayerDetails> PLAYERS;
private static final SecureRandom RANDOM = new SecureRandom();
static {
PLAYERS = List.of(
new PlayerDetails("john@google.com", "312-342", "+3242434242"),
new PlayerDetails("mary@google.com", "234-987", "+23452346"),
new PlayerDetails("steve@google.com", "833-836", "+63457543"),
new PlayerDetails("wayne@google.com", "319-826", "+24626"),
new PlayerDetails("johnie@google.com", "983-322", "+3635635"),
new PlayerDetails("andy@google.com", "934-734", "+0898245"),
new PlayerDetails("richard@google.com", "536-738", "+09845325"),
new PlayerDetails("kevin@google.com", "453-936", "+2423532"),
new PlayerDetails("arnold@google.com", "114-988", "+5646346524"),
new PlayerDetails("ian@google.com", "663-765", "+928394235"),
new PlayerDetails("robin@google.com", "334-763", "+35448"),
new PlayerDetails("ted@google.com", "735-964", "+98752345"),
new PlayerDetails("larry@google.com", "734-853", "+043842423"),
new PlayerDetails("calvin@google.com", "334-746", "+73294135"),
new PlayerDetails("jacob@google.com", "444-766", "+358042354"),
new PlayerDetails("edwin@google.com", "895-345", "+9752435"),
new PlayerDetails("mary@google.com", "760-009", "+34203542"),
new PlayerDetails("lolita@google.com", "425-907", "+9872342"),
new PlayerDetails("bruno@google.com", "023-638", "+673824122"),
new PlayerDetails("peter@google.com", "335-886", "+5432503945"),
new PlayerDetails("warren@google.com", "225-946", "+9872341324"),
new PlayerDetails("monica@google.com", "265-748", "+134124"),
new PlayerDetails("ollie@google.com", "190-045", "+34453452"),
new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"),
new PlayerDetails("lars@google.com", "746-936", "+42345298345"),
new PlayerDetails("bobbie@google.com", "946-384", "+79831742"),
new PlayerDetails("tyron@google.com", "310-992", "+0498837412"),
new PlayerDetails("tyrell@google.com", "032-045", "+67834134"),
new PlayerDetails("nadja@google.com", "000-346", "+498723"),
new PlayerDetails("wendy@google.com", "994-989", "+987324454"),
new PlayerDetails("luke@google.com", "546-634", "+987642435"),
new PlayerDetails("bjorn@google.com", "342-874", "+7834325"),
new PlayerDetails("lisa@google.com", "024-653", "+980742154"),
new PlayerDetails("anton@google.com", "834-935", "+876423145"),
new PlayerDetails("bruce@google.com", "284-936", "+09843212345"),
new PlayerDetails("ray@google.com", "843-073", "+678324123"),
new PlayerDetails("ron@google.com", "637-738", "+09842354"),
new PlayerDetails("xavier@google.com", "143-947", "+375245"),
new PlayerDetails("harriet@google.com", "842-404", "+131243252")
);
var wireTransfers = new InMemoryBank();
PLAYERS.stream()
.map(PlayerDetails::getBankAccount)
.map(e -> new SimpleEntry<>(e, RANDOM.nextInt(LotteryConstants.PLAYER_MAX_BALANCE)))
.collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue))
.forEach(wireTransfers::setFunds);
}
/**
* Inserts lottery tickets into the database based on the sample data.
*/
public static void submitTickets(LotteryService lotteryService, int numTickets) {
for (var i = 0; i < numTickets; i++) {
var randomPlayerDetails = getRandomPlayerDetails();
var lotteryNumbers = LotteryNumbers.createRandom();
var lotteryTicketId = new LotteryTicketId();
var ticket = new LotteryTicket(lotteryTicketId, randomPlayerDetails, lotteryNumbers);
lotteryService.submitTicket(ticket);
}
}
private static PlayerDetails getRandomPlayerDetails() {
return PLAYERS.get(RANDOM.nextInt(PLAYERS.size()));
}
}
| 5,831
| 50.157895
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import com.google.common.base.Joiner;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.HashSet;
import java.util.PrimitiveIterator;
import java.util.Set;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Value object representing lottery numbers. This lottery uses sets of 4 numbers. The numbers must
* be unique and between 1 and 20.
*/
@EqualsAndHashCode
@ToString
public class LotteryNumbers {
private final Set<Integer> numbers;
public static final int MIN_NUMBER = 1;
public static final int MAX_NUMBER = 20;
public static final int NUM_NUMBERS = 4;
/**
* Constructor. Creates random lottery numbers.
*/
private LotteryNumbers() {
numbers = new HashSet<>();
generateRandomNumbers();
}
/**
* Constructor. Uses given numbers.
*/
private LotteryNumbers(Set<Integer> givenNumbers) {
numbers = new HashSet<>();
numbers.addAll(givenNumbers);
}
/**
* Creates a random lottery number.
*
* @return random LotteryNumbers
*/
public static LotteryNumbers createRandom() {
return new LotteryNumbers();
}
/**
* Creates lottery number from given set of numbers.
*
* @return given LotteryNumbers
*/
public static LotteryNumbers create(Set<Integer> givenNumbers) {
return new LotteryNumbers(givenNumbers);
}
/**
* Get numbers.
*
* @return lottery numbers
*/
public Set<Integer> getNumbers() {
return Collections.unmodifiableSet(numbers);
}
/**
* Get numbers as string.
*
* @return numbers as comma separated string
*/
public String getNumbersAsString() {
return Joiner.on(',').join(numbers);
}
/**
* Generates 4 unique random numbers between 1-20 into numbers set.
*/
private void generateRandomNumbers() {
numbers.clear();
var generator = new RandomNumberGenerator(MIN_NUMBER, MAX_NUMBER);
while (numbers.size() < NUM_NUMBERS) {
var num = generator.nextInt();
numbers.add(num);
}
}
/**
* Helper class for generating random numbers.
*/
private static class RandomNumberGenerator {
private final PrimitiveIterator.OfInt randomIterator;
/**
* Initialize a new random number generator that generates random numbers in the range [min,
* max].
*
* @param min the min value (inclusive)
* @param max the max value (inclusive)
*/
public RandomNumberGenerator(int min, int max) {
randomIterator = new SecureRandom().ints(min, max + 1).iterator();
}
/**
* Gets next random integer in [min, max] range.
*
* @return a random number in the range (min, max)
*/
public int nextInt() {
return randomIterator.nextInt();
}
}
}
| 4,063
| 27.41958
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import static com.iluwatar.hexagonal.domain.LotteryConstants.PRIZE_AMOUNT;
import static com.iluwatar.hexagonal.domain.LotteryConstants.SERVICE_BANK_ACCOUNT;
import com.google.inject.Inject;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.database.LotteryTicketRepository;
import com.iluwatar.hexagonal.eventlog.LotteryEventLog;
import java.util.Map;
/**
* Lottery administration implementation.
*/
public class LotteryAdministration {
private final LotteryTicketRepository repository;
private final LotteryEventLog notifications;
private final WireTransfers wireTransfers;
/**
* Constructor.
*/
@Inject
public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications,
WireTransfers wireTransfers) {
this.repository = repository;
this.notifications = notifications;
this.wireTransfers = wireTransfers;
}
/**
* Get all the lottery tickets submitted for lottery.
*/
public Map<LotteryTicketId, LotteryTicket> getAllSubmittedTickets() {
return repository.findAll();
}
/**
* Draw lottery numbers.
*/
public LotteryNumbers performLottery() {
var numbers = LotteryNumbers.createRandom();
var tickets = getAllSubmittedTickets();
for (var id : tickets.keySet()) {
var lotteryTicket = tickets.get(id);
var playerDetails = lotteryTicket.getPlayerDetails();
var playerAccount = playerDetails.getBankAccount();
var result = LotteryUtils.checkTicketForPrize(repository, id, numbers).getResult();
if (result == LotteryTicketCheckResult.CheckResult.WIN_PRIZE) {
if (wireTransfers.transferFunds(PRIZE_AMOUNT, SERVICE_BANK_ACCOUNT, playerAccount)) {
notifications.ticketWon(playerDetails, PRIZE_AMOUNT);
} else {
notifications.prizeError(playerDetails, PRIZE_AMOUNT);
}
} else if (result == LotteryTicketCheckResult.CheckResult.NO_PRIZE) {
notifications.ticketDidNotWin(playerDetails);
}
}
return numbers;
}
/**
* Begin new lottery round.
*/
public void resetLottery() {
repository.deleteAll();
}
}
| 3,502
| 36.265957
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
/**
* Immutable value object representing lottery ticket.
*/
@Getter
@ToString
@RequiredArgsConstructor
public class LotteryTicket {
private final LotteryTicketId id;
private final PlayerDetails playerDetails;
private final LotteryNumbers lotteryNumbers;
@Override
public int hashCode() {
final var prime = 31;
var result = 1;
result = prime * result + ((lotteryNumbers == null) ? 0 : lotteryNumbers.hashCode());
result = prime * result + ((playerDetails == null) ? 0 : playerDetails.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
var other = (LotteryTicket) obj;
if (lotteryNumbers == null) {
if (other.lotteryNumbers != null) {
return false;
}
} else if (!lotteryNumbers.equals(other.lotteryNumbers)) {
return false;
}
if (playerDetails == null) {
return other.playerDetails == null;
} else {
return playerDetails.equals(other.playerDetails);
}
}
}
| 2,563
| 31.455696
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* Lottery ticked id.
*/
@Getter
@EqualsAndHashCode
@RequiredArgsConstructor
public class LotteryTicketId {
private static final AtomicInteger numAllocated = new AtomicInteger(0);
private final int id;
public LotteryTicketId() {
this.id = numAllocated.incrementAndGet();
}
@Override
public String toString() {
return String.format("%d", id);
}
}
| 1,846
| 33.849057
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import static com.iluwatar.hexagonal.domain.LotteryConstants.SERVICE_BANK_ACCOUNT;
import static com.iluwatar.hexagonal.domain.LotteryConstants.TICKET_PRIZE;
import com.google.inject.Inject;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.database.LotteryTicketRepository;
import com.iluwatar.hexagonal.eventlog.LotteryEventLog;
import java.util.Optional;
/**
* Implementation for lottery service.
*/
public class LotteryService {
private final LotteryTicketRepository repository;
private final LotteryEventLog notifications;
private final WireTransfers wireTransfers;
/**
* Constructor.
*/
@Inject
public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications,
WireTransfers wireTransfers) {
this.repository = repository;
this.notifications = notifications;
this.wireTransfers = wireTransfers;
}
/**
* Submit lottery ticket to participate in the lottery.
*/
public Optional<LotteryTicketId> submitTicket(LotteryTicket ticket) {
var playerDetails = ticket.getPlayerDetails();
var playerAccount = playerDetails.getBankAccount();
var result = wireTransfers.transferFunds(TICKET_PRIZE, playerAccount, SERVICE_BANK_ACCOUNT);
if (!result) {
notifications.ticketSubmitError(playerDetails);
return Optional.empty();
}
var optional = repository.save(ticket);
if (optional.isPresent()) {
notifications.ticketSubmitted(playerDetails);
}
return optional;
}
/**
* Check if lottery ticket has won.
*/
public LotteryTicketCheckResult checkTicketForPrize(
LotteryTicketId id,
LotteryNumbers winningNumbers
) {
return LotteryUtils.checkTicketForPrize(repository, id, winningNumbers);
}
}
| 3,117
| 36.119048
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
/**
* Immutable value object containing lottery player details.
*/
@EqualsAndHashCode
@ToString
@Getter
@RequiredArgsConstructor
public class PlayerDetails {
private final String email;
private final String bankAccount;
private final String phoneNumber;
}
| 1,709
| 36.173913
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import com.iluwatar.hexagonal.database.LotteryTicketRepository;
import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult;
/**
* Lottery utilities.
*/
public class LotteryUtils {
private LotteryUtils() {
}
/**
* Checks if lottery ticket has won.
*/
public static LotteryTicketCheckResult checkTicketForPrize(
LotteryTicketRepository repository,
LotteryTicketId id,
LotteryNumbers winningNumbers
) {
var optional = repository.findById(id);
if (optional.isPresent()) {
if (optional.get().getLotteryNumbers().equals(winningNumbers)) {
return new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 1000);
} else {
return new LotteryTicketCheckResult(CheckResult.NO_PRIZE);
}
} else {
return new LotteryTicketCheckResult(CheckResult.TICKET_NOT_SUBMITTED);
}
}
}
| 2,191
| 36.793103
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
/**
* Lottery domain constants.
*/
public class LotteryConstants {
private LotteryConstants() {
}
public static final int PRIZE_AMOUNT = 100000;
public static final String SERVICE_BANK_ACCOUNT = "123-123";
public static final int TICKET_PRIZE = 3;
public static final int SERVICE_BANK_ACCOUNT_BALANCE = 150000;
public static final int PLAYER_MAX_BALANCE = 100;
}
| 1,706
| 39.642857
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.domain;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* Represents lottery ticket check result.
*/
@Getter
@EqualsAndHashCode
@RequiredArgsConstructor
public class LotteryTicketCheckResult {
/**
* Enumeration of Type of Outcomes of a Lottery.
*/
public enum CheckResult {
WIN_PRIZE,
NO_PRIZE,
TICKET_NOT_SUBMITTED
}
private final CheckResult result;
private final int prizeAmount;
/**
* Constructor.
*/
public LotteryTicketCheckResult(CheckResult result) {
this.result = result;
prizeAmount = 0;
}
}
| 1,923
| 31.066667
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java
|
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.hexagonal.banking;
/**
* Interface to bank accounts.
*/
public interface WireTransfers {
/**
* Set amount of funds for bank account.
*/
void setFunds(String bankAccount, int amount);
/**
* Get amount of funds for bank account.
*/
int getFunds(String bankAccount);
/**
* Transfer funds from one bank account to another.
*/
boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount);
}
| 1,758
| 35.645833
| 140
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.