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/interpreter/src/test/java/com/iluwatar/interpreter/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.interpreter;
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,590 | 37.804878 | 140 | java |
java-design-patterns | java-design-patterns-master/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.interpreter;
/**
* Expression.
*/
public abstract class Expression {
public abstract int interpret();
@Override
public abstract String toString();
}
| 1,465 | 38.621622 | 140 | java |
java-design-patterns | java-design-patterns-master/interpreter/src/main/java/com/iluwatar/interpreter/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.interpreter;
import java.util.Stack;
import lombok.extern.slf4j.Slf4j;
/**
* The Interpreter pattern is a design pattern that specifies how to evaluate sentences in a
* language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a
* specialized computer language. The syntax tree of a sentence in the language is an instance of
* the composite pattern and is used to evaluate (interpret) the sentence for a client.
*
* <p>In this example we use the Interpreter pattern to break sentences into expressions ({@link
* Expression}) that can be evaluated and as a whole form the result.
*
* <p>Expressions can be evaluated using prefix, infix or postfix notations This sample uses
* postfix, where operator comes after the operands.
*
*/
@Slf4j
public class App {
/**
* Program entry point.
* @param args program arguments
*/
public static void main(String[] args) {
// the halfling kids are learning some basic math at school
// define the math string we want to parse
final var tokenString = "4 3 2 - 1 + *";
// the stack holds the parsed expressions
var stack = new Stack<Expression>();
// tokenize the string and go through them one by one
var tokenList = tokenString.split(" ");
for (var s : tokenList) {
if (isOperator(s)) {
// when an operator is encountered we expect that the numbers can be popped from the top of
// the stack
var rightExpression = stack.pop();
var leftExpression = stack.pop();
LOGGER.info("popped from stack left: {} right: {}",
leftExpression.interpret(), rightExpression.interpret());
var operator = getOperatorInstance(s, leftExpression, rightExpression);
LOGGER.info("operator: {}", operator);
var result = operator.interpret();
// the operation result is pushed on top of the stack
var resultExpression = new NumberExpression(result);
stack.push(resultExpression);
LOGGER.info("push result to stack: {}", resultExpression.interpret());
} else {
// numbers are pushed on top of the stack
var i = new NumberExpression(s);
stack.push(i);
LOGGER.info("push to stack: {}", i.interpret());
}
}
// in the end, the final result lies on top of the stack
LOGGER.info("result: {}", stack.pop().interpret());
}
/**
* Checks whether the input parameter is an operator.
* @param s input string
* @return true if the input parameter is an operator
*/
public static boolean isOperator(String s) {
return s.equals("+") || s.equals("-") || s.equals("*");
}
/**
* Returns correct expression based on the parameters.
* @param s input string
* @param left expression
* @param right expression
* @return expression
*/
public static Expression getOperatorInstance(String s, Expression left, Expression right) {
return switch (s) {
case "+" -> new PlusExpression(left, right);
case "-" -> new MinusExpression(left, right);
default -> new MultiplyExpression(left, right);
};
}
}
| 4,425 | 38.873874 | 140 | java |
java-design-patterns | java-design-patterns-master/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.interpreter;
/**
* PlusExpression.
*/
public class PlusExpression extends Expression {
private final Expression leftExpression;
private final Expression rightExpression;
public PlusExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret() {
return leftExpression.interpret() + rightExpression.interpret();
}
@Override
public String toString() {
return "+";
}
}
| 1,832 | 35.66 | 140 | java |
java-design-patterns | java-design-patterns-master/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.interpreter;
/**
* MultiplyExpression.
*/
public class MultiplyExpression extends Expression {
private final Expression leftExpression;
private final Expression rightExpression;
public MultiplyExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret() {
return leftExpression.interpret() * rightExpression.interpret();
}
@Override
public String toString() {
return "*";
}
}
| 1,845 | 35.196078 | 140 | java |
java-design-patterns | java-design-patterns-master/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.interpreter;
/**
* NumberExpression.
*/
public class NumberExpression extends Expression {
private final int number;
public NumberExpression(int number) {
this.number = number;
}
public NumberExpression(String s) {
this.number = Integer.parseInt(s);
}
@Override
public int interpret() {
return number;
}
@Override
public String toString() {
return "number";
}
}
| 1,713 | 31.961538 | 140 | java |
java-design-patterns | java-design-patterns-master/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.interpreter;
/**
* MinusExpression.
*/
public class MinusExpression extends Expression {
private final Expression leftExpression;
private final Expression rightExpression;
public MinusExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret() {
return leftExpression.interpret() - rightExpression.interpret();
}
@Override
public String toString() {
return "-";
}
}
| 1,836 | 35.019608 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/sample-application/src/main/java/com/iluwatar/pageobject/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.pageobject;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
/**
* Page Object pattern wraps an UI component with an application specific API allowing you to
* manipulate the UI elements without having to dig around with the underlying UI technology used.
* This is especially useful for testing as it means your tests will be less brittle. Your tests can
* concentrate on the actual test cases where as the manipulation of the UI can be left to the
* internals of the page object itself.
*
* <p>Due to this reason, it has become very popular within the test automation community. In
* particular, it is very common in that the page object is used to represent the html pages of a
* web application that is under test. This web application is referred to as AUT (Application Under
* Test). A web browser automation tool/framework like Selenium for instance, is then used to drive
* the automating of the browser navigation and user actions journeys through this web application.
* Your test class would therefore only be responsible for particular test cases and page object
* would be used by the test class for UI manipulation required for the tests.
*
* <p>In this implementation rather than using Selenium, the HtmlUnit library is used as a
* replacement to represent the specific html elements and to drive the browser. The purpose of this
* example is just to provide a simple version that showcase the intentions of this pattern and how
* this pattern is used in order to understand it.
*/
@Slf4j
public final class App {
private App() {
}
/**
* Application entry point
*
* <p>The application under development is a web application. Normally you would probably have a
* backend that is probably implemented in an object-oriented language (e.g. Java) that serves the
* frontend which comprises of a series of HTML, CSS, JS etc...
*
* <p>For illustrations purposes only, a very simple static html app is used here. This main
* method just fires up this simple web app in a default browser.
*
* @param args arguments
*/
public static void main(String[] args) {
try {
var classLoader = App.class.getClassLoader();
var applicationFile = new File(classLoader.getResource("sample-ui/login.html").getPath());
// should work for unix like OS (mac, unix etc...)
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(applicationFile);
} else {
// java Desktop not supported - above unlikely to work for Windows so try instead...
Runtime.getRuntime().exec("cmd.exe start " + applicationFile);
}
} catch (IOException ex) {
LOGGER.error("An error occured.", ex);
}
}
}
| 4,083 | 43.879121 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.gargoylesoftware.htmlunit.WebClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test Album Page Operations
*/
class AlbumPageTest {
private final AlbumPage albumPage = new AlbumPage(new WebClient());
@BeforeEach
void setUp() {
albumPage.navigateToPage();
}
@Test
void testSaveAlbum() {
var albumPageAfterChanges = albumPage
.changeAlbumTitle("25")
.changeArtist("Adele Laurie Blue Adkins")
.changeAlbumYear(2015)
.changeAlbumRating("B")
.changeNumberOfSongs(20)
.saveChanges();
assertTrue(albumPageAfterChanges.isAt());
}
@Test
void testCancelChanges() {
var albumListPage = albumPage.cancelChanges();
albumListPage.navigateToPage();
assertTrue(albumListPage.isAt());
}
}
| 2,203 | 31.411765 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.gargoylesoftware.htmlunit.WebClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test Album Selection and Album Listing
*/
class AlbumListPageTest {
private final AlbumListPage albumListPage = new AlbumListPage(new WebClient());
@BeforeEach
void setUp() {
albumListPage.navigateToPage();
}
@Test
void testSelectAlbum() {
var albumPage = albumListPage.selectAlbum("21");
albumPage.navigateToPage();
assertTrue(albumPage.isAt());
}
}
| 1,896 | 34.792453 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.gargoylesoftware.htmlunit.WebClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test Login Page Object
*/
class LoginPageTest {
private final LoginPage loginPage = new LoginPage(new WebClient());
@BeforeEach
void setUp() {
loginPage.navigateToPage();
}
@Test
void testLogin() {
var albumListPage = loginPage
.enterUsername("admin")
.enterPassword("password")
.login();
albumListPage.navigateToPage();
assertTrue(albumListPage.isAt());
}
}
| 1,928 | 33.446429 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
/**
* Page Object encapsulating the Login Page (login.html)
*/
@Slf4j
public class LoginPage extends Page {
private static final String LOGIN_PAGE_HTML_FILE = "login.html";
private static final String PAGE_URL = "file:" + AUT_PATH + LOGIN_PAGE_HTML_FILE;
private HtmlPage page;
/**
* Constructor.
*
* @param webClient {@link WebClient}
*/
public LoginPage(WebClient webClient) {
super(webClient);
}
/**
* Navigates to the Login page.
*
* @return {@link LoginPage}
*/
public LoginPage navigateToPage() {
try {
page = this.webClient.getPage(PAGE_URL);
} catch (IOException e) {
LOGGER.error("An error occured on navigateToPage.", e);
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAt() {
return "Login".equals(page.getTitleText());
}
/**
* Enters the username into the username input text field.
*
* @param username the username to enter
* @return {@link LoginPage}
*/
public LoginPage enterUsername(String username) {
var usernameInputTextField = (HtmlTextInput) page.getElementById("username");
usernameInputTextField.setText(username);
return this;
}
/**
* Enters the password into the password input password field.
*
* @param password the password to enter
* @return {@link LoginPage}
*/
public LoginPage enterPassword(String password) {
var passwordInputPasswordField = (HtmlPasswordInput) page.getElementById("password");
passwordInputPasswordField.setText(password);
return this;
}
/**
* Clicking on the login button to 'login'.
*
* @return {@link AlbumListPage} - this is the page that user gets navigated to once successfully
* logged in
*/
public AlbumListPage login() {
var loginButton = (HtmlSubmitInput) page.getElementById("loginButton");
try {
loginButton.click();
} catch (IOException e) {
LOGGER.error("An error occured on login.", e);
}
return new AlbumListPage(webClient);
}
}
| 3,701 | 29.85 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import com.gargoylesoftware.htmlunit.WebClient;
/**
* Encapsulation for a generic 'Page'.
*/
public abstract class Page {
/**
* Application Under Test path This directory location is where html web pages are located.
*/
public static final String AUT_PATH = "../sample-application/src/main/resources/sample-ui/";
protected final WebClient webClient;
/**
* Constructor.
*
* @param webClient {@link WebClient}
*/
public Page(WebClient webClient) {
this.webClient = webClient;
}
/**
* Checks that the current page is actually the page this page object represents.
*
* @return true if so, otherwise false
*/
public abstract boolean isAt();
}
| 2,015 | 33.169492 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlNumberInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
/**
* Page Object encapsulating the Album Page (album-page.html)
*/
@Slf4j
public class AlbumPage extends Page {
private static final String ALBUM_PAGE_HTML_FILE = "album-page.html";
private static final String PAGE_URL = "file:" + AUT_PATH + ALBUM_PAGE_HTML_FILE;
private HtmlPage page;
/**
* Constructor.
*/
public AlbumPage(WebClient webClient) {
super(webClient);
}
/**
* Navigates to the album page.
*
* @return {@link AlbumPage}
*/
public AlbumPage navigateToPage() {
try {
page = this.webClient.getPage(PAGE_URL);
} catch (IOException e) {
LOGGER.error("An error occured on navigateToPage.", e);
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAt() {
return "Album Page".equals(page.getTitleText());
}
/**
* Sets the album title input text field.
*
* @param albumTitle the new album title value to set
* @return {@link AlbumPage}
*/
public AlbumPage changeAlbumTitle(String albumTitle) {
var albumTitleInputTextField = (HtmlTextInput) page.getElementById("albumTitle");
albumTitleInputTextField.setText(albumTitle);
return this;
}
/**
* Sets the artist input text field.
*
* @param artist the new artist value to set
* @return {@link AlbumPage}
*/
public AlbumPage changeArtist(String artist) {
var artistInputTextField = (HtmlTextInput) page.getElementById("albumArtist");
artistInputTextField.setText(artist);
return this;
}
/**
* Selects the select's option value based on the year value given.
*
* @param year the new year value to set
* @return {@link AlbumPage}
*/
public AlbumPage changeAlbumYear(int year) {
var albumYearSelectOption = (HtmlSelect) page.getElementById("albumYear");
var yearOption = albumYearSelectOption.getOptionByValue(Integer.toString(year));
albumYearSelectOption.setSelectedAttribute(yearOption, true);
return this;
}
/**
* Sets the album rating input text field.
*
* @param albumRating the new album rating value to set
* @return {@link AlbumPage}
*/
public AlbumPage changeAlbumRating(String albumRating) {
var albumRatingInputTextField = (HtmlTextInput) page.getElementById("albumRating");
albumRatingInputTextField.setText(albumRating);
return this;
}
/**
* Sets the number of songs number input field.
*
* @param numberOfSongs the new number of songs value to be set
* @return {@link AlbumPage}
*/
public AlbumPage changeNumberOfSongs(int numberOfSongs) {
var numberOfSongsNumberField = (HtmlNumberInput) page.getElementById("numberOfSongs");
numberOfSongsNumberField.setText(Integer.toString(numberOfSongs));
return this;
}
/**
* Cancel changes made by clicking the cancel button.
*
* @return {@link AlbumListPage}
*/
public AlbumListPage cancelChanges() {
var cancelButton = (HtmlSubmitInput) page.getElementById("cancelButton");
try {
cancelButton.click();
} catch (IOException e) {
LOGGER.error("An error occured on cancelChanges.", e);
}
return new AlbumListPage(webClient);
}
/**
* Saves changes made by clicking the save button.
*
* @return {@link AlbumPage}
*/
public AlbumPage saveChanges() {
var saveButton = (HtmlSubmitInput) page.getElementById("saveButton");
try {
saveButton.click();
} catch (IOException e) {
LOGGER.error("An error occured on saveChanges.", e);
}
return this;
}
}
| 5,246 | 28.8125 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.io.IOException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
/**
* Page Object encapsulating the Album List page (album-list.html)
*/
@Slf4j
public class AlbumListPage extends Page {
private static final String ALBUM_LIST_HTML_FILE = "album-list.html";
private static final String PAGE_URL = "file:" + AUT_PATH + ALBUM_LIST_HTML_FILE;
private HtmlPage page;
/**
* Constructor.
*/
public AlbumListPage(WebClient webClient) {
super(webClient);
}
/**
* Navigates to the Album List Page.
*
* @return {@link AlbumListPage}
*/
public AlbumListPage navigateToPage() {
try {
page = this.webClient.getPage(PAGE_URL);
} catch (IOException e) {
LOGGER.error("An error occured on navigateToPage.", e);
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAt() {
return "Album List".equals(page.getTitleText());
}
/**
* Selects an album by the given album title.
*
* @param albumTitle the title of the album to click
* @return the album page
*/
public AlbumPage selectAlbum(String albumTitle) {
// uses XPath to find list of html anchor tags with the class album in it
var albumLinks = (List<Object>) page.getByXPath("//tr[@class='album']//a");
for (var anchor : albumLinks) {
if (((HtmlAnchor) anchor).getTextContent().equals(albumTitle)) {
try {
((HtmlAnchor) anchor).click();
return new AlbumPage(webClient);
} catch (IOException e) {
LOGGER.error("An error occured on selectAlbum", e);
}
}
}
throw new IllegalArgumentException("No links with the album title: " + albumTitle);
}
}
| 3,186 | 31.191919 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.gargoylesoftware.htmlunit.WebClient;
import com.iluwatar.pageobject.pages.AlbumPage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test Album Page Operations
*/
class AlbumPageTest {
private final AlbumPage albumPage = new AlbumPage(new WebClient());
@BeforeEach
void setUp() {
albumPage.navigateToPage();
}
@Test
void testSaveAlbum() {
var albumPageAfterChanges = albumPage
.changeAlbumTitle("25")
.changeArtist("Adele Laurie Blue Adkins")
.changeAlbumYear(2015)
.changeAlbumRating("B")
.changeNumberOfSongs(20)
.saveChanges();
assertTrue(albumPageAfterChanges.isAt());
}
@Test
void testCancelChanges() {
var albumListPage = albumPage.cancelChanges();
albumListPage.navigateToPage();
assertTrue(albumListPage.isAt());
}
}
| 2,251 | 31.637681 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.gargoylesoftware.htmlunit.WebClient;
import com.iluwatar.pageobject.pages.AlbumListPage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test Album Selection and Album Listing
*/
class AlbumListPageTest {
private final AlbumListPage albumListPage = new AlbumListPage(new WebClient());
@BeforeEach
void setUp() {
albumListPage.navigateToPage();
}
@Test
void testSelectAlbum() {
var albumPage = albumListPage.selectAlbum("21");
albumPage.navigateToPage();
assertTrue(albumPage.isAt());
}
}
| 1,948 | 35.092593 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.gargoylesoftware.htmlunit.WebClient;
import com.iluwatar.pageobject.pages.LoginPage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test Login Page Object
*/
class LoginPageTest {
private final LoginPage loginPage = new LoginPage(new WebClient());
@BeforeEach
void setUp() {
loginPage.navigateToPage();
}
@Test
void testLogin() {
var albumListPage = loginPage
.enterUsername("admin")
.enterPassword("password")
.login();
albumListPage.navigateToPage();
assertTrue(albumListPage.isAt());
}
}
| 1,976 | 33.684211 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/src/test/java/com/iluwatar/pageobject/pages/LoginPage.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject.pages;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import java.io.IOException;
/**
* Page Object encapsulating the Login Page (login.html)
*/
public class LoginPage extends Page {
private static final String LOGIN_PAGE_HTML_FILE = "login.html";
private static final String PAGE_URL = "file:" + AUT_PATH + LOGIN_PAGE_HTML_FILE;
private HtmlPage page;
/**
* Constructor
*
* @param webClient {@link WebClient}
*/
public LoginPage(WebClient webClient) {
super(webClient);
}
/**
* Navigates to the Login page
*
* @return {@link LoginPage}
*/
public LoginPage navigateToPage() {
try {
page = this.webClient.getPage(PAGE_URL);
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAt() {
return "Login".equals(page.getTitleText());
}
/**
* Enters the username into the username input text field
*
* @param username the username to enter
* @return {@link LoginPage}
*/
public LoginPage enterUsername(String username) {
var usernameInputTextField = (HtmlTextInput) page.getElementById("username");
usernameInputTextField.setText(username);
return this;
}
/**
* Enters the password into the password input password field
*
* @param password the password to enter
* @return {@link LoginPage}
*/
public LoginPage enterPassword(String password) {
var passwordInputPasswordField = (HtmlPasswordInput) page.getElementById("password");
passwordInputPasswordField.setText(password);
return this;
}
/**
* Clicking on the login button to 'login'
*
* @return {@link AlbumListPage} - this is the page that user gets navigated to once successfully
* logged in
*/
public AlbumListPage login() {
var loginButton = (HtmlSubmitInput) page.getElementById("loginButton");
try {
loginButton.click();
} catch (IOException e) {
e.printStackTrace();
}
return new AlbumListPage(webClient);
}
}
| 3,601 | 29.268908 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/src/test/java/com/iluwatar/pageobject/pages/Page.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject.pages;
import com.gargoylesoftware.htmlunit.WebClient;
/**
* Encapsulation for a generic 'Page'
*/
public abstract class Page {
/**
* Application Under Test path This directory location is where html web pages are located
*/
public static final String AUT_PATH = "src/main/resources/sample-ui/";
protected final WebClient webClient;
/**
* Constructor
*
* @param webClient {@link WebClient}
*/
public Page(WebClient webClient) {
this.webClient = webClient;
}
/**
* Checks that the current page is actually the page this page object represents
*
* @return true if so, otherwise false
*/
public abstract boolean isAt();
}
| 1,995 | 32.830508 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumPage.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject.pages;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlNumberInput;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import java.io.IOException;
/**
* Page Object encapsulating the Album Page (album-page.html)
*/
public class AlbumPage extends Page {
private static final String ALBUM_PAGE_HTML_FILE = "album-page.html";
private static final String PAGE_URL = "file:" + AUT_PATH + ALBUM_PAGE_HTML_FILE;
private HtmlPage page;
/**
* Constructor
*/
public AlbumPage(WebClient webClient) {
super(webClient);
}
/**
* Navigates to the album page
*
* @return {@link AlbumPage}
*/
public AlbumPage navigateToPage() {
try {
page = this.webClient.getPage(PAGE_URL);
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAt() {
return "Album Page".equals(page.getTitleText());
}
/**
* Sets the album title input text field
*
* @param albumTitle the new album title value to set
* @return {@link AlbumPage}
*/
public AlbumPage changeAlbumTitle(String albumTitle) {
var albumTitleInputTextField = (HtmlTextInput) page.getElementById("albumTitle");
albumTitleInputTextField.setText(albumTitle);
return this;
}
/**
* Sets the artist input text field
*
* @param artist the new artist value to set
* @return {@link AlbumPage}
*/
public AlbumPage changeArtist(String artist) {
var artistInputTextField = (HtmlTextInput) page.getElementById("albumArtist");
artistInputTextField.setText(artist);
return this;
}
/**
* Selects the select's option value based on the year value given
*
* @param year the new year value to set
* @return {@link AlbumPage}
*/
public AlbumPage changeAlbumYear(int year) {
var albumYearSelectOption = (HtmlSelect) page.getElementById("albumYear");
var yearOption = albumYearSelectOption.getOptionByValue(Integer.toString(year));
albumYearSelectOption.setSelectedAttribute(yearOption, true);
return this;
}
/**
* Sets the album rating input text field
*
* @param albumRating the new album rating value to set
* @return {@link AlbumPage}
*/
public AlbumPage changeAlbumRating(String albumRating) {
var albumRatingInputTextField = (HtmlTextInput) page.getElementById("albumRating");
albumRatingInputTextField.setText(albumRating);
return this;
}
/**
* Sets the number of songs number input field
*
* @param numberOfSongs the new number of songs value to be set
* @return {@link AlbumPage}
*/
public AlbumPage changeNumberOfSongs(int numberOfSongs) {
var numberOfSongsNumberField = (HtmlNumberInput) page.getElementById("numberOfSongs");
numberOfSongsNumberField.setText(Integer.toString(numberOfSongs));
return this;
}
/**
* Cancel changes made by clicking the cancel button
*
* @return {@link AlbumListPage}
*/
public AlbumListPage cancelChanges() {
var cancelButton = (HtmlSubmitInput) page.getElementById("cancelButton");
try {
cancelButton.click();
} catch (IOException e) {
e.printStackTrace();
}
return new AlbumListPage(webClient);
}
/**
* Saves changes made by clicking the save button
*
* @return {@link AlbumPage}
*/
public AlbumPage saveChanges() {
var saveButton = (HtmlSubmitInput) page.getElementById("saveButton");
try {
saveButton.click();
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
}
| 5,156 | 28.301136 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumListPage.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.pageobject.pages;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.io.IOException;
import java.util.List;
/**
* Page Object encapsulating the Album List page (album-list.html)
*/
public class AlbumListPage extends Page {
private static final String ALBUM_LIST_HTML_FILE = "album-list.html";
private static final String PAGE_URL = "file:" + AUT_PATH + ALBUM_LIST_HTML_FILE;
private HtmlPage page;
/**
* Constructor
*/
public AlbumListPage(WebClient webClient) {
super(webClient);
}
/**
* Navigates to the Album List Page
*
* @return {@link AlbumListPage}
*/
public AlbumListPage navigateToPage() {
try {
page = this.webClient.getPage(PAGE_URL);
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAt() {
return "Album List".equals(page.getTitleText());
}
/**
* Selects an album by the given album title
*
* @param albumTitle the title of the album to click
* @return the album page
*/
public AlbumPage selectAlbum(String albumTitle) {
// uses XPath to find list of html anchor tags with the class album in it
var albumLinks = (List<HtmlAnchor>) page.getByXPath("//tr[@class='album']//a");
for (var anchor : albumLinks) {
if (anchor.getTextContent().equals(albumTitle)) {
try {
anchor.click();
return new AlbumPage(webClient);
} catch (IOException e) {
e.printStackTrace();
}
}
}
throw new IllegalArgumentException("No links with the album title: " + albumTitle);
}
}
| 3,057 | 30.204082 | 140 | java |
java-design-patterns | java-design-patterns-master/page-object/src/main/java/com/iluwatar/pageobject/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.pageobject;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
/**
* Page Object pattern wraps an UI component with an application specific API allowing you to
* manipulate the UI elements without having to dig around with the underlying UI technology used.
* This is especially useful for testing as it means your tests will be less brittle. Your tests can
* concentrate on the actual test cases where as the manipulation of the UI can be left to the
* internals of the page object itself.
*
* <p>Due to this reason, it has become very popular within the test automation community. In
* particular, it is very common in that the page object is used to represent the html pages of a
* web application that is under test. This web application is referred to as AUT (Application Under
* Test). A web browser automation tool/framework like Selenium for instance, is then used to drive
* the automating of the browser navigation and user actions journeys through this web application.
* Your test class would therefore only be responsible for particular test cases and page object
* would be used by the test class for UI manipulation required for the tests.
*
* <p>In this implementation rather than using Selenium, the HtmlUnit library is used as a
* replacement to represent the specific html elements and to drive the browser. The purpose of this
* example is just to provide a simple version that showcase the intentions of this pattern and how
* this pattern is used in order to understand it.
*/
public final class App {
private App() {
}
/**
* Application entry point
*
* <p>The application under development is a web application. Normally you would probably have a
* backend that is probably implemented in an object-oriented language (e.g. Java) that serves the
* frontend which comprises of a series of HTML, CSS, JS etc...
*
* <p>For illustrations purposes only, a very simple static html app is used here. This main
* method just fires up this simple web app in a default browser.
*
* @param args arguments
*/
public static void main(String[] args) {
try {
var classLoader = App.class.getClassLoader();
var applicationFile = new File(classLoader.getResource("sample-ui/login.html").getPath());
// Should work for unix like OS (mac, unix etc...)
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(applicationFile);
} else {
// Java Desktop not supported - above unlikely to work for Windows so try the
// following instead...
Runtime.getRuntime().exec("cmd.exe start " + applicationFile);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| 4,050 | 44.011111 | 140 | java |
java-design-patterns | java-design-patterns-master/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.adapter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* Tests for the adapter pattern.
*/
class AdapterPatternTest {
private Map<String, Object> beans;
private static final String FISHING_BEAN = "fisher";
private static final String ROWING_BEAN = "captain";
/**
* This method runs before the test execution and sets the bean objects in the beans Map.
*/
@BeforeEach
void setup() {
beans = new HashMap<>();
var fishingBoatAdapter = spy(new FishingBoatAdapter());
beans.put(FISHING_BEAN, fishingBoatAdapter);
var captain = new Captain();
captain.setRowingBoat((FishingBoatAdapter) beans.get(FISHING_BEAN));
beans.put(ROWING_BEAN, captain);
}
/**
* This test asserts that when we use the row() method on a captain bean(client), it is internally
* calling sail method on the fishing boat object. The Adapter ({@link FishingBoatAdapter} )
* converts the interface of the target class ( {@link FishingBoat}) into a suitable one expected
* by the client ({@link Captain} ).
*/
@Test
void testAdapter() {
var captain = (Captain) beans.get(ROWING_BEAN);
// when captain moves
captain.row();
// the captain internally calls the battleship object to move
var adapter = (RowingBoat) beans.get(FISHING_BEAN);
verify(adapter).row();
}
}
| 2,797 | 34.417722 | 140 | java |
java-design-patterns | java-design-patterns-master/adapter/src/test/java/com/iluwatar/adapter/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.adapter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Adapter example runs without errors.
*/
class AppTest {
/**
* Check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,724 | 35.702128 | 140 | java |
java-design-patterns | java-design-patterns-master/adapter/src/main/java/com/iluwatar/adapter/package-info.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.adapter;
| 1,314 | 49.576923 | 140 | java |
java-design-patterns | java-design-patterns-master/adapter/src/main/java/com/iluwatar/adapter/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.adapter;
/**
* An adapter helps two incompatible interfaces to work together. This is the real world definition
* for an adapter. Interfaces may be incompatible but the inner functionality should suit the need.
* The Adapter design pattern allows otherwise incompatible classes to work together by converting
* the interface of one class into an interface expected by the clients.
*
* <p>There are two variations of the Adapter pattern: The class adapter implements the adaptee's
* interface whereas the object adapter uses composition to contain the adaptee in the adapter
* object. This example uses the object adapter approach.
*
* <p>The Adapter ({@link FishingBoatAdapter}) converts the interface of the adaptee class ({@link
* FishingBoat}) into a suitable one expected by the client ({@link RowingBoat}).
*
* <p>The story of this implementation is this. <br> Pirates are coming! we need a {@link
* RowingBoat} to flee! We have a {@link FishingBoat} and our captain. We have no time to make up a
* new ship! we need to reuse this {@link FishingBoat}. The captain needs a rowing boat which he can
* operate. The spec is in {@link RowingBoat}. We will use the Adapter pattern to reuse {@link
* FishingBoat}.
*/
public final class App {
private App() {
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(final String[] args) {
// The captain can only operate rowing boats but with adapter he is able to
// use fishing boats as well
var captain = new Captain(new FishingBoatAdapter());
captain.row();
}
}
| 2,910 | 45.206349 | 140 | java |
java-design-patterns | java-design-patterns-master/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.adapter;
/**
* Adapter class. Adapts the interface of the device ({@link FishingBoat}) into {@link RowingBoat}
* interface expected by the client ({@link Captain}).
*/
public class FishingBoatAdapter implements RowingBoat {
private final FishingBoat boat = new FishingBoat();
public final void row() {
boat.sail();
}
}
| 1,640 | 41.076923 | 140 | java |
java-design-patterns | java-design-patterns-master/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.adapter;
/**
* The interface expected by the client.<br> A rowing boat is rowed to move.
*/
public interface RowingBoat {
void row();
}
| 1,448 | 40.4 | 140 | java |
java-design-patterns | java-design-patterns-master/adapter/src/main/java/com/iluwatar/adapter/Captain.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.adapter;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* The Captain uses {@link RowingBoat} to sail. <br> This is the client in the pattern.
*/
@Setter
@NoArgsConstructor
@AllArgsConstructor
public final class Captain {
private RowingBoat rowingBoat;
void row() {
rowingBoat.row();
}
}
| 1,656 | 35.021739 | 140 | java |
java-design-patterns | java-design-patterns-master/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.adapter;
import lombok.extern.slf4j.Slf4j;
/**
* Device class (adaptee in the pattern). We want to reuse this class. Fishing boat moves by
* sailing.
*/
@Slf4j
final class FishingBoat {
void sail() {
LOGGER.info("The fishing boat is sailing");
}
}
| 1,568 | 37.268293 | 140 | java |
java-design-patterns | java-design-patterns-master/serialized-entity/src/test/java/com/iluwatar/serializedentity/CountryTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.serializedentity;
import org.junit.jupiter.api.Test;
import java.io.*;
import static org.junit.jupiter.api.Assertions.*;
public class CountryTest {
@Test
void testGetMethod() {
Country China = new Country(
86,
"China",
"Asia",
"Chinese"
);
assertEquals(86, China.getCode());
assertEquals("China", China.getName());
assertEquals("Asia", China.getContinents());
assertEquals("Chinese", China.getLanguage());
}
@Test
void testSetMethod() {
Country country = new Country(
86,
"China",
"Asia",
"Chinese"
);
country.setCode(971);
country.setName("UAE");
country.setContinents("West-Asia");
country.setLanguage("Arabic");
assertEquals(971, country.getCode());
assertEquals("UAE", country.getName());
assertEquals("West-Asia", country.getContinents());
assertEquals("Arabic", country.getLanguage());
}
@Test
void testSerializable(){
// Serializing Country
try {
Country country = new Country(
86,
"China",
"Asia",
"Chinese");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("output.txt"));
objectOutputStream.writeObject(country);
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// De-serialize Country
try {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("output.txt"));
Country country = (Country) objectInputStream.readObject();
objectInputStream.close();
System.out.println(country);
Country China = new Country(
86,
"China",
"Asia",
"Chinese");
assertEquals(China, country);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 3,376 | 31.471154 | 140 | java |
java-design-patterns | java-design-patterns-master/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java | package com.iluwatar.serializedentity;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Serialized Entity example runs without errors.
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test
void shouldExecuteSerializedEntityWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 595 | 23.833333 | 115 | java |
java-design-patterns | java-design-patterns-master/serialized-entity/src/main/java/com/iluwatar/serializedentity/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.serializedentity;
import java.io.IOException;
import java.sql.SQLException;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.h2.jdbcx.JdbcDataSource;
/**
* Serialized Entity Pattern.
*
* <p> Serialized Entity Pattern allow us to easily persist Java objects to the database. It uses Serializable interface
* and DAO pattern. Serialized Entity Pattern will first use Serializable to convert a Java object into a set of bytes,
* then it will using DAO pattern to store this set of bytes as BLOB to database.</p>
*
* <p> In this example, we first initialize two Java objects (Country) "China" and "UnitedArabEmirates", then we
* initialize "serializedChina" with "China" object and "serializedUnitedArabEmirates" with "UnitedArabEmirates",
* then we use method "serializedChina.insertCountry()" and "serializedUnitedArabEmirates.insertCountry()" to serialize
* "China" and "UnitedArabEmirates" and persist them to database.
* Last, with "serializedChina.selectCountry()" and "serializedUnitedArabEmirates.selectCountry()" we could read "China"
* and "UnitedArabEmirates" from database as sets of bytes, then deserialize them back to Java object (Country). </p>
*
*/
@Slf4j
public class App {
private static final String DB_URL = "jdbc:h2:~/test";
private App() {
}
/**
* Program entry point.
* @param args command line args.
* @throws IOException if any
* @throws ClassNotFoundException if any
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
final var dataSource = createDataSource();
deleteSchema(dataSource);
createSchema(dataSource);
// Initializing Country Object China
final var China = new Country(
86,
"China",
"Asia",
"Chinese"
);
// Initializing Country Object UnitedArabEmirates
final var UnitedArabEmirates = new Country(
971,
"United Arab Emirates",
"Asia",
"Arabic"
);
// Initializing CountrySchemaSql Object with parameter "China" and "dataSource"
final var serializedChina = new CountrySchemaSql(China, dataSource);
// Initializing CountrySchemaSql Object with parameter "UnitedArabEmirates" and "dataSource"
final var serializedUnitedArabEmirates = new CountrySchemaSql(UnitedArabEmirates, dataSource);
/*
By using CountrySchemaSql.insertCountry() method, the private (Country) type variable within Object
CountrySchemaSql will be serialized to a set of bytes and persist to database.
For more details of CountrySchemaSql.insertCountry() method please refer to CountrySchemaSql.java file
*/
serializedChina.insertCountry();
serializedUnitedArabEmirates.insertCountry();
/*
By using CountrySchemaSql.selectCountry() method, CountrySchemaSql object will read the sets of bytes from database
and deserialize it to Country object.
For more details of CountrySchemaSql.selectCountry() method please refer to CountrySchemaSql.java file
*/
serializedChina.selectCountry();
serializedUnitedArabEmirates.selectCountry();
}
private static void deleteSchema(DataSource dataSource) {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(CountrySchemaSql.DELETE_SCHEMA_SQL);
} catch (SQLException e) {
LOGGER.info("Exception thrown " + e.getMessage());
}
}
private static void createSchema(DataSource dataSource) {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(CountrySchemaSql.CREATE_SCHEMA_SQL);
} catch (SQLException e) {
LOGGER.info("Exception thrown " + e.getMessage());
}
}
private static DataSource createDataSource() {
var dataSource = new JdbcDataSource();
dataSource.setURL(DB_URL);
return dataSource;
}
} | 5,267 | 39.523077 | 140 | java |
java-design-patterns | java-design-patterns-master/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountryDao.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* In an application the Data Access Object (DAO) is a part of Data access layer. It is an object
* that provides an interface to some type of persistence mechanism. By mapping application calls to
* the persistence layer, DAO provides some specific data operations without exposing details of the
* database. This isolation supports the Single responsibility principle. It separates what data
* accesses the application needs, in terms of domain-specific objects and data types (the public
* interface of the DAO), from how these needs can be satisfied with a specific DBMS, database
* schema, etc.
*
* <p>Any change in the way data is stored and retrieved will not change the client code as the
* client will be using interface and need not worry about exact source.
*
* @see InMemoryCustomerDao
* @see DbCustomerDao
*/
package com.iluwatar.serializedentity;
import java.io.IOException;
/**
* DAO interface for Country transactions.
*/
public interface CountryDao {
int insertCountry() throws IOException;
int selectCountry() throws IOException, ClassNotFoundException;
}
| 2,383 | 45.745098 | 140 | java |
java-design-patterns | java-design-patterns-master/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.serializedentity;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
/**
* Country Schema SQL Class.
*/
@Slf4j
public class CountrySchemaSql implements CountryDao {
public static final String CREATE_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS WORLD (ID INT PRIMARY KEY, COUNTRY BLOB)";
public static final String DELETE_SCHEMA_SQL = "DROP TABLE WORLD IF EXISTS";
private Country country;
private DataSource dataSource;
/**
* Public constructor.
*
* @param dataSource datasource
* @param country country
*/
public CountrySchemaSql(Country country, DataSource dataSource) {
this.country = new Country(
country.getCode(),
country.getName(),
country.getContinents(),
country.getLanguage()
);
this.dataSource = dataSource;
}
/**
* This method will serialize a Country object and store it to database.
* @return int type, if successfully insert a serialized object to database then return country code, else return -1.
* @throws IOException if any.
*/
@Override
public int insertCountry() throws IOException {
var sql = "INSERT INTO WORLD (ID, COUNTRY) VALUES (?, ?)";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oss = new ObjectOutputStream(baos)) {
oss.writeObject(country);
oss.flush();
preparedStatement.setInt(1, country.getCode());
preparedStatement.setBlob(2, new ByteArrayInputStream(baos.toByteArray()));
preparedStatement.execute();
return country.getCode();
} catch (SQLException e) {
LOGGER.info("Exception thrown " + e.getMessage());
}
return -1;
}
/**
* This method will select a data item from database and deserialize it.
* @return int type, if successfully select and deserialized object from database then return country code,
* else return -1.
* @throws IOException if any.
* @throws ClassNotFoundException if any.
*/
@Override
public int selectCountry() throws IOException, ClassNotFoundException {
var sql = "SELECT ID, COUNTRY FROM WORLD WHERE ID = ?";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setInt(1, country.getCode());
try (ResultSet rs = preparedStatement.executeQuery()) {
if (rs.next()) {
Blob countryBlob = rs.getBlob("country");
ByteArrayInputStream baos = new ByteArrayInputStream(countryBlob.getBytes(1, (int) countryBlob.length()));
ObjectInputStream ois = new ObjectInputStream(baos);
country = (Country) ois.readObject();
LOGGER.info("Country: " + country);
}
return rs.getInt("id");
}
} catch (SQLException e) {
LOGGER.info("Exception thrown " + e.getMessage());
}
return -1;
}
}
| 4,574 | 35.895161 | 140 | java |
java-design-patterns | java-design-patterns-master/serialized-entity/src/main/java/com/iluwatar/serializedentity/Country.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.serializedentity;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* A Country POJO taht represents the data that will serialize and store in database.
*/
@Getter
@Setter
@EqualsAndHashCode
@ToString
@AllArgsConstructor
public class Country implements Serializable {
private int code;
private String name;
private String continents;
private String language;
public static final long serialVersionUID = 7149851;
}
| 1,852 | 36.06 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/test/java/com/iluwatar/chain/OrcKingTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.chain;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Date: 12/6/15 - 9:29 PM
*
* @author Jeroen Meulemeester
*/
class OrcKingTest {
/**
* All possible requests
*/
private static final List<Request> REQUESTS = List.of(
new Request(RequestType.DEFEND_CASTLE, "Don't let the barbarians enter my castle!!"),
new Request(RequestType.TORTURE_PRISONER, "Don't just stand there, tickle him!"),
new Request(RequestType.COLLECT_TAX, "Don't steal, the King hates competition ...")
);
@Test
void testMakeRequest() {
final var king = new OrcKing();
REQUESTS.forEach(request -> {
king.makeRequest(request);
assertTrue(
request.isHandled(),
"Expected all requests from King to be handled, but [" + request + "] was not!"
);
});
}
} | 2,195 | 35 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/test/java/com/iluwatar/chain/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.chain;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,786 | 35.469388 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcSoldier.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.chain;
import lombok.extern.slf4j.Slf4j;
/**
* OrcSoldier.
*/
@Slf4j
public class OrcSoldier implements RequestHandler {
@Override
public boolean canHandleRequest(Request req) {
return req.getRequestType() == RequestType.COLLECT_TAX;
}
@Override
public int getPriority() {
return 1;
}
@Override
public void handle(Request req) {
req.markHandled();
LOGGER.info("{} handling request \"{}\"", name(), req);
}
@Override
public String name() {
return "Orc soldier";
}
}
| 1,821 | 32.127273 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcOfficer.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.chain;
import lombok.extern.slf4j.Slf4j;
/**
* OrcOfficer.
*/
@Slf4j
public class OrcOfficer implements RequestHandler {
@Override
public boolean canHandleRequest(Request req) {
return req.getRequestType() == RequestType.TORTURE_PRISONER;
}
@Override
public int getPriority() {
return 3;
}
@Override
public void handle(Request req) {
req.markHandled();
LOGGER.info("{} handling request \"{}\"", name(), req);
}
@Override
public String name() {
return "Orc officer";
}
}
| 1,827 | 31.642857 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestHandler.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.chain;
/**
* RequestHandler.
*/
public interface RequestHandler {
boolean canHandleRequest(Request req);
int getPriority();
void handle(Request req);
String name();
}
| 1,487 | 36.2 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/main/java/com/iluwatar/chain/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.chain;
/**
* The Chain of Responsibility pattern is a design pattern consisting of command objects and a
* series of processing objects. Each processing object contains logic that defines the types of
* command objects that it can handle; the rest are passed to the next processing object in the
* chain. A mechanism also exists for adding new processing objects to the end of this chain.
*
* <p>In this example we organize the request handlers ({@link RequestHandler}) into a chain where
* each handler has a chance to act on the request on its turn. Here the king ({@link OrcKing})
* makes requests and the military orcs ({@link OrcCommander}, {@link OrcOfficer}, {@link
* OrcSoldier}) form the handler chain.
*/
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var king = new OrcKing();
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner"));
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
}
}
| 2,448 | 45.207547 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcCommander.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.chain;
import lombok.extern.slf4j.Slf4j;
/**
* OrcCommander.
*/
@Slf4j
public class OrcCommander implements RequestHandler {
@Override
public boolean canHandleRequest(Request req) {
return req.getRequestType() == RequestType.DEFEND_CASTLE;
}
@Override
public int getPriority() {
return 2;
}
@Override
public void handle(Request req) {
req.markHandled();
LOGGER.info("{} handling request \"{}\"", name(), req);
}
@Override
public String name() {
return "Orc commander";
}
}
| 1,829 | 32.272727 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/main/java/com/iluwatar/chain/Request.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.chain;
import java.util.Objects;
/**
* Request.
*/
public class Request {
/**
* The type of this request, used by each item in the chain to see if they should or can handle
* this particular request.
*/
private final RequestType requestType;
/**
* A description of the request.
*/
private final String requestDescription;
/**
* Indicates if the request is handled or not. A request can only switch state from unhandled to
* handled, there's no way to 'unhandle' a request.
*/
private boolean handled;
/**
* Create a new request of the given type and accompanied description.
*
* @param requestType The type of request
* @param requestDescription The description of the request
*/
public Request(final RequestType requestType, final String requestDescription) {
this.requestType = Objects.requireNonNull(requestType);
this.requestDescription = Objects.requireNonNull(requestDescription);
}
/**
* Get a description of the request.
*
* @return A human readable description of the request
*/
public String getRequestDescription() {
return requestDescription;
}
/**
* Get the type of this request, used by each person in the chain of command to see if they should
* or can handle this particular request.
*
* @return The request type
*/
public RequestType getRequestType() {
return requestType;
}
/**
* Mark the request as handled.
*/
public void markHandled() {
this.handled = true;
}
/**
* Indicates if this request is handled or not.
*
* @return <tt>true</tt> when the request is handled, <tt>false</tt> if not
*/
public boolean isHandled() {
return this.handled;
}
@Override
public String toString() {
return getRequestDescription();
}
}
| 3,123 | 29.330097 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcKing.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.chain;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* OrcKing makes requests that are handled by the chain.
*/
public class OrcKing {
private List<RequestHandler> handlers;
public OrcKing() {
buildChain();
}
private void buildChain() {
handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier());
}
/**
* Handle request by the chain.
*/
public void makeRequest(Request req) {
handlers
.stream()
.sorted(Comparator.comparing(RequestHandler::getPriority))
.filter(handler -> handler.canHandleRequest(req))
.findFirst()
.ifPresent(handler -> handler.handle(req));
}
}
| 2,009 | 33.655172 | 140 | java |
java-design-patterns | java-design-patterns-master/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestType.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.chain;
/**
* RequestType enumeration.
*/
public enum RequestType {
DEFEND_CASTLE,
TORTURE_PRISONER,
COLLECT_TAX
}
| 1,430 | 37.675676 | 140 | java |
java-design-patterns | java-design-patterns-master/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.object.pool;
import static java.time.Duration.ofMillis;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Date: 12/27/15 - 1:05 AM
*
* @author Jeroen Meulemeester
*/
class OliphauntPoolTest {
/**
* Use the same object 100 times subsequently. This should not take much time since the heavy
* object instantiation is done only once. Verify if we get the same object each time.
*/
@Test
void testSubsequentCheckinCheckout() {
assertTimeout(ofMillis(5000), () -> {
final var pool = new OliphauntPool();
assertEquals("Pool available=0 inUse=0", pool.toString());
final var expectedOliphaunt = pool.checkOut();
assertEquals("Pool available=0 inUse=1", pool.toString());
pool.checkIn(expectedOliphaunt);
assertEquals("Pool available=1 inUse=0", pool.toString());
for (int i = 0; i < 100; i++) {
final var oliphaunt = pool.checkOut();
assertEquals("Pool available=0 inUse=1", pool.toString());
assertSame(expectedOliphaunt, oliphaunt);
assertEquals(expectedOliphaunt.getId(), oliphaunt.getId());
assertEquals(expectedOliphaunt.toString(), oliphaunt.toString());
pool.checkIn(oliphaunt);
assertEquals("Pool available=1 inUse=0", pool.toString());
}
});
}
/**
* Use the same object 100 times subsequently. This should not take much time since the heavy
* object instantiation is done only once. Verify if we get the same object each time.
*/
@Test
void testConcurrentCheckinCheckout() {
assertTimeout(ofMillis(5000), () -> {
final var pool = new OliphauntPool();
assertEquals(pool.toString(), "Pool available=0 inUse=0");
final var firstOliphaunt = pool.checkOut();
assertEquals(pool.toString(), "Pool available=0 inUse=1");
final var secondOliphaunt = pool.checkOut();
assertEquals(pool.toString(), "Pool available=0 inUse=2");
assertNotSame(firstOliphaunt, secondOliphaunt);
assertEquals(firstOliphaunt.getId() + 1, secondOliphaunt.getId());
// After checking in the second, we should get the same when checking out a new oliphaunt ...
pool.checkIn(secondOliphaunt);
assertEquals(pool.toString(), "Pool available=1 inUse=1");
final var oliphaunt3 = pool.checkOut();
assertEquals(pool.toString(), "Pool available=0 inUse=2");
assertSame(secondOliphaunt, oliphaunt3);
// ... and the same applies for the first one
pool.checkIn(firstOliphaunt);
assertEquals(pool.toString(), "Pool available=1 inUse=1");
final var oliphaunt4 = pool.checkOut();
assertEquals(pool.toString(), "Pool available=0 inUse=2");
assertSame(firstOliphaunt, oliphaunt4);
// When both oliphaunt return to the pool, we should still get the same instances
pool.checkIn(firstOliphaunt);
assertEquals(pool.toString(), "Pool available=1 inUse=1");
pool.checkIn(secondOliphaunt);
assertEquals(pool.toString(), "Pool available=2 inUse=0");
// The order of the returned instances is not determined, so just put them in a list
// and verify if both expected instances are in there.
final var oliphaunts = List.of(pool.checkOut(), pool.checkOut());
assertEquals(pool.toString(), "Pool available=0 inUse=2");
assertTrue(oliphaunts.contains(firstOliphaunt));
assertTrue(oliphaunts.contains(secondOliphaunt));
});
}
} | 5,051 | 39.416 | 140 | java |
java-design-patterns | java-design-patterns-master/object-pool/src/test/java/com/iluwatar/object/pool/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.object.pool;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
/**
*
* Application test
*
*/
class AppTest {
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,596 | 36.139535 | 140 | java |
java-design-patterns | java-design-patterns-master/object-pool/src/main/java/com/iluwatar/object/pool/OliphauntPool.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.object.pool;
/**
* Oliphaunt object pool.
*/
public class OliphauntPool extends ObjectPool<Oliphaunt> {
@Override
protected Oliphaunt create() {
return new Oliphaunt();
}
}
| 1,492 | 39.351351 | 140 | java |
java-design-patterns | java-design-patterns-master/object-pool/src/main/java/com/iluwatar/object/pool/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.object.pool;
import lombok.extern.slf4j.Slf4j;
/**
* When it is necessary to work with a large number of objects that are particularly expensive to
* instantiate and each object is only needed for a short period of time, the performance of an
* entire application may be adversely affected. An object pool design pattern may be deemed
* desirable in cases such as these.
*
* <p>The object pool design pattern creates a set of objects that may be reused. When a new object
* is needed, it is requested from the pool. If a previously prepared object is available it is
* returned immediately, avoiding the instantiation cost. If no objects are present in the pool, a
* new item is created and returned. When the object has been used and is no longer needed, it is
* returned to the pool, allowing it to be used again in the future without repeating the
* computationally expensive instantiation process. It is important to note that once an object has
* been used and returned, existing references will become invalid.
*
* <p>In this example we have created {@link OliphauntPool} inheriting from generic {@link
* ObjectPool}. {@link Oliphaunt}s can be checked out from the pool and later returned to it. The
* pool tracks created instances and their status (available, inUse).
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var pool = new OliphauntPool();
LOGGER.info(pool.toString());
var oliphaunt1 = pool.checkOut();
String checkedOut = "Checked out {}";
LOGGER.info(checkedOut, oliphaunt1);
LOGGER.info(pool.toString());
var oliphaunt2 = pool.checkOut();
LOGGER.info(checkedOut, oliphaunt2);
var oliphaunt3 = pool.checkOut();
LOGGER.info(checkedOut, oliphaunt3);
LOGGER.info(pool.toString());
LOGGER.info("Checking in {}", oliphaunt1);
pool.checkIn(oliphaunt1);
LOGGER.info("Checking in {}", oliphaunt2);
pool.checkIn(oliphaunt2);
LOGGER.info(pool.toString());
var oliphaunt4 = pool.checkOut();
LOGGER.info(checkedOut, oliphaunt4);
var oliphaunt5 = pool.checkOut();
LOGGER.info(checkedOut, oliphaunt5);
LOGGER.info(pool.toString());
}
}
| 3,554 | 43.4375 | 140 | java |
java-design-patterns | java-design-patterns-master/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.object.pool;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Oliphaunts are expensive to create.
*/
public class Oliphaunt {
private static final AtomicInteger counter = new AtomicInteger(0);
private final int id;
/**
* Constructor.
*/
public Oliphaunt() {
id = counter.incrementAndGet();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public int getId() {
return id;
}
@Override
public String toString() {
return String.format("Oliphaunt id=%d", id);
}
}
| 1,879 | 30.864407 | 140 | java |
java-design-patterns | java-design-patterns-master/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.object.pool;
import java.util.HashSet;
import java.util.Set;
/**
* Generic object pool.
*
* @param <T> Type T of Object in the Pool
*/
public abstract class ObjectPool<T> {
private final Set<T> available = new HashSet<>();
private final Set<T> inUse = new HashSet<>();
protected abstract T create();
/**
* Checkout object from pool.
*/
public synchronized T checkOut() {
if (available.isEmpty()) {
available.add(create());
}
var instance = available.iterator().next();
available.remove(instance);
inUse.add(instance);
return instance;
}
public synchronized void checkIn(T instance) {
inUse.remove(instance);
available.add(instance);
}
@Override
public synchronized String toString() {
return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
}
}
| 2,159 | 32.230769 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.cqrs.commandes.CommandServiceImpl;
import com.iluwatar.cqrs.dto.Author;
import com.iluwatar.cqrs.dto.Book;
import com.iluwatar.cqrs.queries.QueryService;
import com.iluwatar.cqrs.queries.QueryServiceImpl;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* Integration test of IQueryService and ICommandService with h2 data
*/
class IntegrationTest {
private static QueryService queryService;
@BeforeAll
static void initializeAndPopulateDatabase() {
var commandService = new CommandServiceImpl();
queryService = new QueryServiceImpl();
// create first author1
commandService.authorCreated("username1", "name1", "email1");
// create author1 and update all its data
commandService.authorCreated("username2", "name2", "email2");
commandService.authorEmailUpdated("username2", "new_email2");
commandService.authorNameUpdated("username2", "new_name2");
commandService.authorUsernameUpdated("username2", "new_username2");
// add book1 to author1
commandService.bookAddedToAuthor("title1", 10, "username1");
// add book2 to author1 and update all its data
commandService.bookAddedToAuthor("title2", 20, "username1");
commandService.bookPriceUpdated("title2", 30);
commandService.bookTitleUpdated("title2", "new_title2");
}
@Test
void testGetAuthorByUsername() {
var author = queryService.getAuthorByUsername("username1");
assertEquals("username1", author.getUsername());
assertEquals("name1", author.getName());
assertEquals("email1", author.getEmail());
}
@Test
void testGetUpdatedAuthorByUsername() {
var author = queryService.getAuthorByUsername("new_username2");
var expectedAuthor = new Author("new_name2", "new_email2", "new_username2");
assertEquals(expectedAuthor, author);
}
@Test
void testGetBook() {
var book = queryService.getBook("title1");
assertEquals("title1", book.getTitle());
assertEquals(10, book.getPrice(), 0.01);
}
@Test
void testGetAuthorBooks() {
var books = queryService.getAuthorBooks("username1");
assertEquals(2, books.size());
assertTrue(books.contains(new Book("title1", 10)));
assertTrue(books.contains(new Book("new_title2", 30)));
}
@Test
void testGetAuthorBooksCount() {
var bookCount = queryService.getAuthorBooksCount("username1");
assertEquals(new BigInteger("2"), bookCount);
}
@Test
void testGetAuthorsCount() {
var authorCount = queryService.getAuthorsCount();
assertEquals(new BigInteger("2"), authorCount);
}
}
| 4,052 | 34.552632 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandService.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.commandes;
/**
* This interface represents the commands of the CQRS pattern.
*/
public interface CommandService {
void authorCreated(String username, String name, String email);
void bookAddedToAuthor(String title, double price, String username);
void authorNameUpdated(String username, String name);
void authorUsernameUpdated(String oldUsername, String newUsername);
void authorEmailUpdated(String username, String email);
void bookTitleUpdated(String oldTitle, String newTitle);
void bookPriceUpdated(String title, double price);
}
| 1,870 | 38.808511 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.commandes;
import com.iluwatar.cqrs.domain.model.Author;
import com.iluwatar.cqrs.domain.model.Book;
import com.iluwatar.cqrs.util.HibernateUtil;
import org.hibernate.SessionFactory;
/**
* This class is an implementation of {@link CommandService} interface. It uses Hibernate as an api
* for persistence.
*/
public class CommandServiceImpl implements CommandService {
private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
private Author getAuthorByUsername(String username) {
Author author;
try (var session = sessionFactory.openSession()) {
var query = session.createQuery("from Author where username=:username");
query.setParameter("username", username);
author = (Author) query.uniqueResult();
}
if (author == null) {
HibernateUtil.getSessionFactory().close();
throw new NullPointerException("Author " + username + " doesn't exist!");
}
return author;
}
private Book getBookByTitle(String title) {
Book book;
try (var session = sessionFactory.openSession()) {
var query = session.createQuery("from Book where title=:title");
query.setParameter("title", title);
book = (Book) query.uniqueResult();
}
if (book == null) {
HibernateUtil.getSessionFactory().close();
throw new NullPointerException("Book " + title + " doesn't exist!");
}
return book;
}
@Override
public void authorCreated(String username, String name, String email) {
var author = new Author(username, name, email);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.save(author);
session.getTransaction().commit();
}
}
@Override
public void bookAddedToAuthor(String title, double price, String username) {
var author = getAuthorByUsername(username);
var book = new Book(title, price, author);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.save(book);
session.getTransaction().commit();
}
}
@Override
public void authorNameUpdated(String username, String name) {
var author = getAuthorByUsername(username);
author.setName(name);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(author);
session.getTransaction().commit();
}
}
@Override
public void authorUsernameUpdated(String oldUsername, String newUsername) {
var author = getAuthorByUsername(oldUsername);
author.setUsername(newUsername);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(author);
session.getTransaction().commit();
}
}
@Override
public void authorEmailUpdated(String username, String email) {
var author = getAuthorByUsername(username);
author.setEmail(email);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(author);
session.getTransaction().commit();
}
}
@Override
public void bookTitleUpdated(String oldTitle, String newTitle) {
var book = getBookByTitle(oldTitle);
book.setTitle(newTitle);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(book);
session.getTransaction().commit();
}
}
@Override
public void bookPriceUpdated(String title, double price) {
var book = getBookByTitle(title);
book.setPrice(price);
try (var session = sessionFactory.openSession()) {
session.beginTransaction();
session.update(book);
session.getTransaction().commit();
}
}
}
| 4,996 | 33.462069 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.util;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
/**
* This class simply returns one instance of {@link SessionFactory} initialized when the application
* is started.
*/
@Slf4j
public class HibernateUtil {
private static final SessionFactory SESSIONFACTORY = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
// configures settings from hibernate.cfg.xml
final var registry = new StandardServiceRegistryBuilder().configure().build();
try {
return new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception ex) {
StandardServiceRegistryBuilder.destroy(registry);
LOGGER.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return SESSIONFACTORY;
}
}
| 2,320 | 38.338983 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.app;
import com.iluwatar.cqrs.commandes.CommandServiceImpl;
import com.iluwatar.cqrs.constants.AppConstants;
import com.iluwatar.cqrs.queries.QueryServiceImpl;
import com.iluwatar.cqrs.util.HibernateUtil;
import lombok.extern.slf4j.Slf4j;
/**
* CQRS : Command Query Responsibility Segregation. A pattern used to separate query services from
* commands or writes services. The pattern is very simple but it has many consequences. For
* example, it can be used to tackle down a complex domain, or to use other architectures that were
* hard to implement with the classical way.
*
* <p>This implementation is an example of managing books and authors in a library. The persistence
* of books and authors is done according to the CQRS architecture. A command side that deals with a
* data model to persist(insert,update,delete) objects to a database. And a query side that uses
* native queries to get data from the database and return objects as DTOs (Data transfer Objects).
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var commands = new CommandServiceImpl();
// Create Authors and Books using CommandService
commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "evans@email.com");
commands.authorCreated(AppConstants.J_BLOCH, "Joshua Bloch", "jBloch@email.com");
commands.authorCreated(AppConstants.M_FOWLER, "Martin Fowler", "mFowler@email.com");
commands.bookAddedToAuthor("Domain-Driven Design", 60.08, AppConstants.E_EVANS);
commands.bookAddedToAuthor("Effective Java", 40.54, AppConstants.J_BLOCH);
commands.bookAddedToAuthor("Java Puzzlers", 39.99, AppConstants.J_BLOCH);
commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, AppConstants.J_BLOCH);
commands.bookAddedToAuthor("Patterns of Enterprise"
+ " Application Architecture", 54.01, AppConstants.M_FOWLER);
commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER);
commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans");
var queries = new QueryServiceImpl();
// Query the database using QueryService
var nullAuthor = queries.getAuthorByUsername("username");
var evans = queries.getAuthorByUsername(AppConstants.E_EVANS);
var blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH);
var authorsCount = queries.getAuthorsCount();
var dddBook = queries.getBook("Domain-Driven Design");
var blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH);
LOGGER.info("Author username : {}", nullAuthor);
LOGGER.info("Author evans : {}", evans);
LOGGER.info("jBloch number of books : {}", blochBooksCount);
LOGGER.info("Number of authors : {}", authorsCount);
LOGGER.info("DDD book : {}", dddBook);
LOGGER.info("jBloch books : {}", blochBooks);
HibernateUtil.getSessionFactory().close();
}
}
| 4,266 | 46.411111 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.queries;
import com.iluwatar.cqrs.constants.AppConstants;
import com.iluwatar.cqrs.dto.Author;
import com.iluwatar.cqrs.dto.Book;
import com.iluwatar.cqrs.util.HibernateUtil;
import java.math.BigInteger;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
/**
* This class is an implementation of {@link QueryService}. It uses Hibernate native queries to
* return DTOs from the database.
*/
public class QueryServiceImpl implements QueryService {
private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
@Override
public Author getAuthorByUsername(String username) {
Author authorDto;
try (var session = sessionFactory.openSession()) {
Query<Author> sqlQuery = session.createQuery(
"select new com.iluwatar.cqrs.dto.Author(a.name, a.email, a.username)"
+ " from com.iluwatar.cqrs.domain.model.Author a where a.username=:username");
sqlQuery.setParameter(AppConstants.USER_NAME, username);
authorDto = sqlQuery.uniqueResult();
}
return authorDto;
}
@Override
public Book getBook(String title) {
Book bookDto;
try (var session = sessionFactory.openSession()) {
Query<Book> sqlQuery = session.createQuery(
"select new com.iluwatar.cqrs.dto.Book(b.title, b.price)"
+ " from com.iluwatar.cqrs.domain.model.Book b where b.title=:title");
sqlQuery.setParameter("title", title);
bookDto = sqlQuery.uniqueResult();
}
return bookDto;
}
@Override
public List<Book> getAuthorBooks(String username) {
List<Book> bookDtos;
try (var session = sessionFactory.openSession()) {
Query<Book> sqlQuery = session.createQuery(
"select new com.iluwatar.cqrs.dto.Book(b.title, b.price)"
+ " from com.iluwatar.cqrs.domain.model.Author a, com.iluwatar.cqrs.domain.model.Book b "
+ "where b.author.id = a.id and a.username=:username");
sqlQuery.setParameter(AppConstants.USER_NAME, username);
bookDtos = sqlQuery.list();
}
return bookDtos;
}
@Override
public BigInteger getAuthorBooksCount(String username) {
BigInteger bookcount;
try (var session = sessionFactory.openSession()) {
var sqlQuery = session.createNativeQuery(
"SELECT count(b.title)" + " FROM Book b, Author a"
+ " where b.author_id = a.id and a.username=:username");
sqlQuery.setParameter(AppConstants.USER_NAME, username);
bookcount = (BigInteger) sqlQuery.uniqueResult();
}
return bookcount;
}
@Override
public BigInteger getAuthorsCount() {
BigInteger authorcount;
try (var session = sessionFactory.openSession()) {
var sqlQuery = session.createNativeQuery("SELECT count(id) from Author");
authorcount = (BigInteger) sqlQuery.uniqueResult();
}
return authorcount;
}
}
| 4,259 | 38.444444 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryService.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.queries;
import com.iluwatar.cqrs.dto.Author;
import com.iluwatar.cqrs.dto.Book;
import java.math.BigInteger;
import java.util.List;
/**
* This interface represents the query methods of the CQRS pattern.
*/
public interface QueryService {
Author getAuthorByUsername(String username);
Book getBook(String title);
List<Book> getAuthorBooks(String username);
BigInteger getAuthorBooksCount(String username);
BigInteger getAuthorsCount();
}
| 1,767 | 35.833333 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.dto;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* This is a DTO (Data Transfer Object) author, contains only useful information to be returned.
*/
@ToString
@EqualsAndHashCode
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Author {
private String name;
private String email;
private String username;
}
| 1,744 | 35.354167 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.dto;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* This is a DTO (Data Transfer Object) book, contains only useful information to be returned.
*/
@ToString
@EqualsAndHashCode
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Book {
private String title;
private double price;
}
| 1,714 | 35.489362 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.constants;
/**
* Class to define the constants.
*/
public class AppConstants {
public static final String E_EVANS = "eEvans";
public static final String J_BLOCH = "jBloch";
public static final String M_FOWLER = "mFowler";
public static final String USER_NAME = "username";
}
| 1,598 | 41.078947 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.domain.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* This is an Author entity. It is used by Hibernate for persistence.
*/
@ToString
@Getter
@Setter
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String username;
private String name;
private String email;
/**
* Constructor.
*
* @param username username of the author
* @param name name of the author
* @param email email of the author
*/
public Author(String username, String name, String email) {
this.username = username;
this.name = name;
this.email = email;
}
protected Author() {
}
}
| 2,159 | 31.238806 | 140 | java |
java-design-patterns | java-design-patterns-master/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.domain.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* This is a Book entity. It is used by Hibernate for persistence. Many books can be written by one
* {@link Author}
*/
@ToString
@Setter
@Getter
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String title;
private double price;
@ManyToOne
private Author author;
/**
* Constructor.
*
* @param title title of the book
* @param price price of the book
* @param author author of the book
*/
public Book(String title, double price, Author author) {
this.title = title;
this.price = price;
this.author = author;
}
protected Book() {
}
}
| 2,233 | 30.914286 | 140 | java |
java-design-patterns | java-design-patterns-master/.mvn/wrapper/MavenWrapperDownloader.java | /*
* The MIT License
* Copyright © 2014-2021 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| 5,458 | 42.325397 | 118 | java |
java-design-patterns | java-design-patterns-master/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/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.halfsynchalfasync;
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,586 | 37.707317 | 140 | java |
java-design-patterns | java-design-patterns-master/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.halfsynchalfasync;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Date: 12/12/15 - 11:15 PM
*
* @author Jeroen Meulemeester
*/
class AsynchronousServiceTest {
private AsynchronousService service;
private AsyncTask<Object> task;
@BeforeEach
void setUp() {
service = new AsynchronousService(new LinkedBlockingQueue<>());
task = mock(AsyncTask.class);
}
@Test
void testPerfectExecution() throws Exception {
final var result = new Object();
when(task.call()).thenReturn(result);
service.execute(task);
verify(task, timeout(2000)).onPostCall(eq(result));
final var inOrder = inOrder(task);
inOrder.verify(task, times(1)).onPreCall();
inOrder.verify(task, times(1)).call();
inOrder.verify(task, times(1)).onPostCall(eq(result));
verifyNoMoreInteractions(task);
}
@Test
void testCallException() throws Exception {
final var exception = new IOException();
when(task.call()).thenThrow(exception);
service.execute(task);
verify(task, timeout(2000)).onError(eq(exception));
final var inOrder = inOrder(task);
inOrder.verify(task, times(1)).onPreCall();
inOrder.verify(task, times(1)).call();
inOrder.verify(task, times(1)).onError(exception);
verifyNoMoreInteractions(task);
}
@Test
void testPreCallException() {
final var exception = new IllegalStateException();
doThrow(exception).when(task).onPreCall();
service.execute(task);
verify(task, timeout(2000)).onError(eq(exception));
final var inOrder = inOrder(task);
inOrder.verify(task, times(1)).onPreCall();
inOrder.verify(task, times(1)).onError(exception);
verifyNoMoreInteractions(task);
}
} | 3,513 | 32.788462 | 140 | java |
java-design-patterns | java-design-patterns-master/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.halfsynchalfasync;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
/**
* This is the asynchronous layer which does not block when a new request arrives. It just passes
* the request to the synchronous layer which consists of a queue i.e. a {@link BlockingQueue} and a
* pool of threads i.e. {@link ThreadPoolExecutor}. Out of this pool of worker threads one of the
* thread picks up the task and executes it synchronously in background and the result is posted
* back to the caller via callback.
*/
@Slf4j
public class AsynchronousService {
/*
* This represents the queuing layer as well as synchronous layer of the pattern. The thread pool
* contains worker threads which execute the tasks in blocking/synchronous manner. Long running
* tasks should be performed in the background which does not affect the performance of main
* thread.
*/
private final ExecutorService service;
/**
* Creates an asynchronous service using {@code workQueue} as communication channel between
* asynchronous layer and synchronous layer. Different types of queues such as Priority queue, can
* be used to control the pattern of communication between the layers.
*/
public AsynchronousService(BlockingQueue<Runnable> workQueue) {
service = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, workQueue);
}
/**
* A non-blocking method which performs the task provided in background and returns immediately.
*
* <p>On successful completion of task the result is posted back using callback method {@link
* AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally due to some
* exception then the reason for error is posted back using callback method {@link
* AsyncTask#onError(Throwable)}.
*
* <p>NOTE: The results are posted back in the context of background thread in this
* implementation.
*/
public <T> void execute(final AsyncTask<T> task) {
try {
// some small tasks such as validation can be performed here.
task.onPreCall();
} catch (Exception e) {
task.onError(e);
return;
}
service.submit(new FutureTask<T>(task) {
@Override
protected void done() {
super.done();
try {
/*
* called in context of background thread. There is other variant possible where result is
* posted back and sits in the queue of caller thread which then picks it up for
* processing. An example of such a system is Android OS, where the UI elements can only
* be updated using UI thread. So result must be posted back in UI thread.
*/
task.onPostCall(get());
} catch (InterruptedException e) {
// should not occur
} catch (ExecutionException e) {
task.onError(e.getCause());
}
}
});
}
/**
* Stops the pool of workers. This is a blocking call to wait for all tasks to be completed.
*/
public void close() {
service.shutdown();
try {
service.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
LOGGER.error("Error waiting for executor service shutdown!");
}
}
}
| 4,747 | 40.286957 | 140 | java |
java-design-patterns | java-design-patterns-master/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/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.halfsynchalfasync;
import java.util.concurrent.LinkedBlockingQueue;
import lombok.extern.slf4j.Slf4j;
/**
* This application demonstrates Half-Sync/Half-Async pattern. Key parts of the pattern are {@link
* AsyncTask} and {@link AsynchronousService}.
*
* <p><i>PROBLEM</i> <br>
* A concurrent system have a mixture of short duration, mid duration and long duration tasks. Mid
* or long duration tasks should be performed asynchronously to meet quality of service
* requirements.
*
* <p><i>INTENT</i> <br>
* The intent of this pattern is to separate the the synchronous and asynchronous processing in the
* concurrent application by introducing two intercommunicating layers - one for sync and one for
* async. This simplifies the programming without unduly affecting the performance.
*
* <p><i>APPLICABILITY</i> <br>
* UNIX network subsystems - In operating systems network operations are carried out asynchronously
* with help of hardware level interrupts.<br> CORBA - At the asynchronous layer one thread is
* associated with each socket that is connected to the client. Thread blocks waiting for CORBA
* requests from the client. On receiving request it is inserted in the queuing layer which is then
* picked up by synchronous layer which processes the request and sends response back to the
* client.<br> Android AsyncTask framework - Framework provides a way to execute long running
* blocking calls, such as downloading a file, in background threads so that the UI thread remains
* free to respond to user inputs.<br>
*
* <p><i>IMPLEMENTATION</i> <br>
* The main method creates an asynchronous service which does not block the main thread while the
* task is being performed. The main thread continues its work which is similar to Async Method
* Invocation pattern. The difference between them is that there is a queuing layer between
* Asynchronous layer and synchronous layer, which allows for different communication patterns
* between both layers. Such as Priority Queue can be used as queuing layer to prioritize the way
* tasks are executed. Our implementation is just one simple way of implementing this pattern, there
* are many variants possible as described in its applications.
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var service = new AsynchronousService(new LinkedBlockingQueue<>());
/*
* A new task to calculate sum is received but as this is main thread, it should not block. So
* it passes it to the asynchronous task layer to compute and proceeds with handling other
* incoming requests. This is particularly useful when main thread is waiting on Socket to
* receive new incoming requests and does not wait for particular request to be completed before
* responding to new request.
*/
service.execute(new ArithmeticSumTask(1000));
/*
* New task received, lets pass that to async layer for computation. So both requests will be
* executed in parallel.
*/
service.execute(new ArithmeticSumTask(500));
service.execute(new ArithmeticSumTask(2000));
service.execute(new ArithmeticSumTask(1));
service.close();
}
/**
* ArithmeticSumTask.
*/
static class ArithmeticSumTask implements AsyncTask<Long> {
private final long numberOfElements;
public ArithmeticSumTask(long numberOfElements) {
this.numberOfElements = numberOfElements;
}
/*
* This is the long running task that is performed in background. In our example the long
* running task is calculating arithmetic sum with artificial delay.
*/
@Override
public Long call() throws Exception {
return ap(numberOfElements);
}
/*
* This will be called in context of the main thread where some validations can be done
* regarding the inputs. Such as it must be greater than 0. It's a small computation which can
* be performed in main thread. If we did validated the input in background thread then we pay
* the cost of context switching which is much more than validating it in main thread.
*/
@Override
public void onPreCall() {
if (numberOfElements < 0) {
throw new IllegalArgumentException("n is less than 0");
}
}
@Override
public void onPostCall(Long result) {
// Handle the result of computation
LOGGER.info(result.toString());
}
@Override
public void onError(Throwable throwable) {
throw new IllegalStateException("Should not occur");
}
}
private static long ap(long i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
LOGGER.error("Exception caught.", e);
}
return i * (i + 1) / 2;
}
}
| 6,109 | 40.849315 | 140 | java |
java-design-patterns | java-design-patterns-master/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.halfsynchalfasync;
import java.util.concurrent.Callable;
/**
* Represents some computation that is performed asynchronously and its result. The computation is
* typically done is background threads and the result is posted back in form of callback. The
* callback does not implement {@code isComplete}, {@code cancel} as it is out of scope of this
* pattern.
*
* @param <O> type of result
*/
public interface AsyncTask<O> extends Callable<O> {
/**
* Is called in context of caller thread before call to {@link #call()}. Large tasks should not be
* performed in this method as it will block the caller thread. Small tasks such as validations
* can be performed here so that the performance penalty of context switching is not incurred in
* case of invalid requests.
*/
void onPreCall();
/**
* A callback called after the result is successfully computed by {@link #call()}. In our
* implementation this method is called in context of background thread but in some variants, such
* as Android where only UI thread can change the state of UI widgets, this method is called in
* context of UI thread.
*/
void onPostCall(O result);
/**
* A callback called if computing the task resulted in some exception. This method is called when
* either of {@link #call()} or {@link #onPreCall()} throw any exception.
*
* @param throwable error cause
*/
void onError(Throwable throwable);
/**
* This is where the computation of task should reside. This method is called in context of
* background thread.
*/
@Override
O call() throws Exception;
}
| 2,918 | 41.304348 | 140 | java |
java-design-patterns | java-design-patterns-master/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.balking;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link WashingMachine}
*/
class WashingMachineTest {
private final FakeDelayProvider fakeDelayProvider = new FakeDelayProvider();
@Test
void wash() {
var washingMachine = new WashingMachine(fakeDelayProvider);
washingMachine.wash();
washingMachine.wash();
var machineStateGlobal = washingMachine.getWashingMachineState();
fakeDelayProvider.task.run();
// washing machine remains in washing state
assertEquals(WashingMachineState.WASHING, machineStateGlobal);
// washing machine goes back to enabled state
assertEquals(WashingMachineState.ENABLED, washingMachine.getWashingMachineState());
}
@Test
void endOfWashing() {
var washingMachine = new WashingMachine();
washingMachine.wash();
assertEquals(WashingMachineState.ENABLED, washingMachine.getWashingMachineState());
}
private static class FakeDelayProvider implements DelayProvider {
private Runnable task;
@Override
public void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task) {
this.task = task;
}
}
} | 2,541 | 34.305556 | 140 | java |
java-design-patterns | java-design-patterns-master/balking/src/test/java/com/iluwatar/balking/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.balking;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow((Executable) App::main);
}
} | 1,830 | 35.62 | 140 | java |
java-design-patterns | java-design-patterns-master/balking/src/main/java/com/iluwatar/balking/WashingMachine.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.balking;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
/**
* Washing machine class.
*/
@Slf4j
public class WashingMachine {
private final DelayProvider delayProvider;
private WashingMachineState washingMachineState;
/**
* Creates a new instance of WashingMachine.
*/
public WashingMachine() {
this((interval, timeUnit, task) -> {
try {
Thread.sleep(timeUnit.toMillis(interval));
} catch (InterruptedException ie) {
LOGGER.error("", ie);
Thread.currentThread().interrupt();
}
task.run();
});
}
/**
* Creates a new instance of WashingMachine using provided delayProvider. This constructor is used
* only for unit testing purposes.
*/
public WashingMachine(DelayProvider delayProvider) {
this.delayProvider = delayProvider;
this.washingMachineState = WashingMachineState.ENABLED;
}
public WashingMachineState getWashingMachineState() {
return washingMachineState;
}
/**
* Method responsible for washing if the object is in appropriate state.
*/
public void wash() {
synchronized (this) {
var machineState = getWashingMachineState();
LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState);
if (this.washingMachineState == WashingMachineState.WASHING) {
LOGGER.error("Cannot wash if the machine has been already washing!");
return;
}
this.washingMachineState = WashingMachineState.WASHING;
}
LOGGER.info("{}: Doing the washing", Thread.currentThread().getName());
this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing);
}
/**
* Method responsible of ending the washing by changing machine state.
*/
public synchronized void endOfWashing() {
washingMachineState = WashingMachineState.ENABLED;
LOGGER.info("{}: Washing completed.", Thread.currentThread().getId());
}
}
| 3,268 | 33.776596 | 140 | java |
java-design-patterns | java-design-patterns-master/balking/src/main/java/com/iluwatar/balking/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.balking;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
/**
* In Balking Design Pattern if an object’s method is invoked when it is in an inappropriate state,
* then the method will return without doing anything. Objects that use this pattern are generally
* only in a state that is prone to balking temporarily but for an unknown amount of time
*
* <p>In this example implementation, {@link WashingMachine} is an object that has two states in
* which it can be: ENABLED and WASHING. If the machine is ENABLED, the state changes to WASHING
* using a thread-safe method. On the other hand, if it already has been washing and any other
* thread executes {@link WashingMachine#wash()} it won't do that and returns without doing
* anything.
*/
@Slf4j
public class App {
/**
* Entry Point.
*
* @param args the command line arguments - not used
*/
public static void main(String... args) {
final var washingMachine = new WashingMachine();
var executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
executorService.execute(washingMachine::wash);
}
executorService.shutdown();
try {
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException ie) {
LOGGER.error("ERROR: Waiting on executor service shutdown!");
Thread.currentThread().interrupt();
}
}
}
| 2,807 | 40.910448 | 140 | java |
java-design-patterns | java-design-patterns-master/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.balking;
/**
* WashingMachineState enum describes in which state machine is, it can be enabled and ready to work
* as well as during washing.
*/
public enum WashingMachineState {
ENABLED,
WASHING
}
| 1,511 | 42.2 | 140 | java |
java-design-patterns | java-design-patterns-master/balking/src/main/java/com/iluwatar/balking/DelayProvider.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.balking;
import java.util.concurrent.TimeUnit;
/**
* An interface to simulate delay while executing some work.
*/
public interface DelayProvider {
void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task);
}
| 1,533 | 42.828571 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link FindCustomer}.
*
* @author George Aristy (george.aristy@gmail.com)
*/
class FindCustomerTest {
/**
* Returns the given result with no exceptions.
*/
@Test
void noExceptions() throws Exception {
assertThat(new FindCustomer("123").perform(), is("123"));
}
/**
* Throws the given exception.
*/
@Test
void oneException() {
var findCustomer = new FindCustomer("123", new BusinessException("test"));
assertThrows(BusinessException.class, findCustomer::perform);
}
/**
* Should first throw the given exceptions, then return the given result.
*
* @throws Exception not an expected exception
*/
@Test
void resultAfterExceptions() throws Exception {
final var op = new FindCustomer(
"123",
new CustomerNotFoundException("not found"),
new DatabaseNotAvailableException("not available")
);
try {
op.perform();
} catch (CustomerNotFoundException e) {
//ignore
}
try {
op.perform();
} catch (DatabaseNotAvailableException e) {
//ignore
}
assertThat(op.perform(), is("123"));
}
}
| 2,652 | 31.353659 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link Retry}.
*
* @author George Aristy (george.aristy@gmail.com)
*/
class RetryExponentialBackoffTest {
/**
* Should contain all errors thrown.
*/
@Test
void errors() {
final var e = new BusinessException("unhandled");
final var retry = new RetryExponentialBackoff<String>(
() -> {
throw e;
},
2,
0
);
try {
retry.perform();
} catch (BusinessException ex) {
//ignore
}
assertThat(retry.errors(), hasItem(e));
}
/**
* No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking
* it to attempt twice.
*/
@Test
void attempts() {
final var e = new BusinessException("unhandled");
final var retry = new RetryExponentialBackoff<String>(
() -> {
throw e;
},
2,
0
);
try {
retry.perform();
} catch (BusinessException ex) {
//ignore
}
assertThat(retry.attempts(), is(1));
}
/**
* Final number of attempts should be equal to the number of attempts asked because we are asking
* it to ignore the exception that will be thrown.
*/
@Test
void ignore() {
final var e = new CustomerNotFoundException("customer not found");
final var retry = new RetryExponentialBackoff<String>(
() -> {
throw e;
},
2,
0,
ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass())
);
try {
retry.perform();
} catch (BusinessException ex) {
//ignore
}
assertThat(retry.attempts(), is(2));
}
}
| 3,136 | 28.046296 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/test/java/com/iluwatar/retry/RetryTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link Retry}.
*
* @author George Aristy (george.aristy@gmail.com)
*/
class RetryTest {
/**
* Should contain all errors thrown.
*/
@Test
void errors() {
final var e = new BusinessException("unhandled");
final var retry = new Retry<String>(
() -> {
throw e;
},
2,
0
);
try {
retry.perform();
} catch (BusinessException ex) {
//ignore
}
assertThat(retry.errors(), hasItem(e));
}
/**
* No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking
* it to attempt twice.
*/
@Test
void attempts() {
final var e = new BusinessException("unhandled");
final var retry = new Retry<String>(
() -> {
throw e;
},
2,
0
);
try {
retry.perform();
} catch (BusinessException ex) {
//ignore
}
assertThat(retry.attempts(), is(1));
}
/**
* Final number of attempts should be equal to the number of attempts asked because we are asking
* it to ignore the exception that will be thrown.
*/
@Test
void ignore() {
final var e = new CustomerNotFoundException("customer not found");
final var retry = new Retry<String>(
() -> {
throw e;
},
2,
0,
ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass())
);
try {
retry.perform();
} catch (BusinessException ex) {
//ignore
}
assertThat(retry.attempts(), is(2));
}
} | 3,065 | 27.12844 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/main/java/com/iluwatar/retry/FindCustomer.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
/**
* Finds a customer, returning its ID from our records.
*
* <p>This is an imaginary operation that, for some imagined input, returns the ID for a customer.
* However, this is a "flaky" operation that is supposed to fail intermittently, but for the
* purposes of this example it fails in a programmed way depending on the constructor parameters.
*
* @author George Aristy (george.aristy@gmail.com)
*/
public record FindCustomer(String customerId, Deque<BusinessException> errors) implements BusinessOperation<String> {
public FindCustomer(String customerId, BusinessException... errors) {
this(customerId, new ArrayDeque<>(List.of(errors)));
}
@Override
public String perform() throws BusinessException {
if (!this.errors.isEmpty()) {
throw this.errors.pop();
}
return this.customerId;
}
}
| 2,224 | 40.203704 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/main/java/com/iluwatar/retry/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.retry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <em>Retry</em> pattern enables applications to handle potentially recoverable failures from
* the environment if the business requirements and nature of the failures allow it. By retrying
* failed operations on external dependencies, the application may maintain stability and minimize
* negative impact on the user experience.
*
* <p>In our example, we have the {@link BusinessOperation} interface as an abstraction over all
* operations that our application performs involving remote systems. The calling code should remain
* decoupled from implementations.
*
* <p>{@link FindCustomer} is a business operation that looks up a customer's record and returns
* its ID. Imagine its job is performed by looking up the customer in our local database and
* returning its ID. We can pass {@link CustomerNotFoundException} as one of its {@link
* FindCustomer#FindCustomer(java.lang.String, com.iluwatar.retry.BusinessException...) constructor
* parameters} in order to simulate not finding the customer.
*
* <p>Imagine that, lately, this operation has experienced intermittent failures due to some weird
* corruption and/or locking in the data. After retrying a few times the customer is found. The
* database is still, however, expected to always be available. While a definitive solution is
* found to the problem, our engineers advise us to retry the operation a set number of times with a
* set delay between retries, although not too many retries otherwise the end user will be left
* waiting for a long time, while delays that are too short will not allow the database to recover
* from the load.
*
* <p>To keep the calling code as decoupled as possible from this workaround, we have implemented
* the retry mechanism as a {@link BusinessOperation} named {@link Retry}.
*
* @author George Aristy (george.aristy@gmail.com)
* @see <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/retry">Retry pattern
* (Microsoft Azure Docs)</a>
*/
public final class App {
private static final Logger LOG = LoggerFactory.getLogger(App.class);
public static final String NOT_FOUND = "not found";
private static BusinessOperation<String> op;
/**
* Entry point.
*
* @param args not used
* @throws Exception not expected
*/
public static void main(String[] args) throws Exception {
noErrors();
errorNoRetry();
errorWithRetry();
errorWithRetryExponentialBackoff();
}
private static void noErrors() throws Exception {
op = new FindCustomer("123");
op.perform();
LOG.info("Sometimes the operation executes with no errors.");
}
private static void errorNoRetry() throws Exception {
op = new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND));
try {
op.perform();
} catch (CustomerNotFoundException e) {
LOG.info("Yet the operation will throw an error every once in a while.");
}
}
private static void errorWithRetry() throws Exception {
final var retry = new Retry<>(
new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)),
3, //3 attempts
100, //100 ms delay between attempts
e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
);
op = retry;
final var customerId = op.perform();
LOG.info(String.format(
"However, retrying the operation while ignoring a recoverable error will eventually yield "
+ "the result %s after a number of attempts %s", customerId, retry.attempts()
));
}
private static void errorWithRetryExponentialBackoff() throws Exception {
final var retry = new RetryExponentialBackoff<>(
new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)),
6, //6 attempts
30000, //30 s max delay between attempts
e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
);
op = retry;
final var customerId = op.perform();
LOG.info(String.format(
"However, retrying the operation while ignoring a recoverable error will eventually yield "
+ "the result %s after a number of attempts %s", customerId, retry.attempts()
));
}
}
| 5,557 | 43.822581 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/main/java/com/iluwatar/retry/Retry.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
/**
* Decorates {@link BusinessOperation business operation} with "retry" capabilities.
*
* @param <T> the remote op's return type
* @author George Aristy (george.aristy@gmail.com)
*/
public final class Retry<T> implements BusinessOperation<T> {
private final BusinessOperation<T> op;
private final int maxAttempts;
private final long delay;
private final AtomicInteger attempts;
private final Predicate<Exception> test;
private final List<Exception> errors;
/**
* Ctor.
*
* @param op the {@link BusinessOperation} to retry
* @param maxAttempts number of times to retry
* @param delay delay (in milliseconds) between attempts
* @param ignoreTests tests to check whether the remote exception can be ignored. No exceptions
* will be ignored if no tests are given
*/
@SafeVarargs
public Retry(
BusinessOperation<T> op,
int maxAttempts,
long delay,
Predicate<Exception>... ignoreTests
) {
this.op = op;
this.maxAttempts = maxAttempts;
this.delay = delay;
this.attempts = new AtomicInteger();
this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false);
this.errors = new ArrayList<>();
}
/**
* The errors encountered while retrying, in the encounter order.
*
* @return the errors encountered while retrying
*/
public List<Exception> errors() {
return Collections.unmodifiableList(this.errors);
}
/**
* The number of retries performed.
*
* @return the number of retries performed
*/
public int attempts() {
return this.attempts.intValue();
}
@Override
public T perform() throws BusinessException {
do {
try {
return this.op.perform();
} catch (BusinessException e) {
this.errors.add(e);
if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) {
throw e;
}
try {
Thread.sleep(this.delay);
} catch (InterruptedException f) {
//ignore
}
}
} while (true);
}
}
| 3,602 | 31.459459 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
/**
* Catastrophic error indicating that we have lost connection to our database.
*
* @author George Aristy (george.aristy@gmail.com)
*/
public final class DatabaseNotAvailableException extends BusinessException {
private static final long serialVersionUID = -3750769625095997799L;
/**
* Ctor.
*
* @param message the error message
*/
public DatabaseNotAvailableException(String message) {
super(message);
}
}
| 1,751 | 38.818182 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/main/java/com/iluwatar/retry/BusinessException.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
/**
* The top-most type in our exception hierarchy that signifies that an unexpected error condition
* occurred. Its use is reserved as a "catch-all" for cases where no other subtype captures the
* specificity of the error condition in question. Calling code is not expected to be able to handle
* this error and should be reported to the maintainers immediately.
*
* @author George Aristy (george.aristy@gmail.com)
*/
public class BusinessException extends Exception {
private static final long serialVersionUID = 6235833142062144336L;
/**
* Ctor.
*
* @param message the error message
*/
public BusinessException(String message) {
super(message);
}
}
| 1,997 | 41.510638 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
/**
* Decorates {@link BusinessOperation business operation} with "retry" capabilities.
*
* @param <T> the remote op's return type
* @author George Aristy (george.aristy@gmail.com)
*/
public final class RetryExponentialBackoff<T> implements BusinessOperation<T> {
private static final Random RANDOM = new Random();
private final BusinessOperation<T> op;
private final int maxAttempts;
private final long maxDelay;
private final AtomicInteger attempts;
private final Predicate<Exception> test;
private final List<Exception> errors;
/**
* Ctor.
*
* @param op the {@link BusinessOperation} to retry
* @param maxAttempts number of times to retry
* @param ignoreTests tests to check whether the remote exception can be ignored. No exceptions
* will be ignored if no tests are given
*/
@SafeVarargs
public RetryExponentialBackoff(
BusinessOperation<T> op,
int maxAttempts,
long maxDelay,
Predicate<Exception>... ignoreTests
) {
this.op = op;
this.maxAttempts = maxAttempts;
this.maxDelay = maxDelay;
this.attempts = new AtomicInteger();
this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false);
this.errors = new ArrayList<>();
}
/**
* The errors encountered while retrying, in the encounter order.
*
* @return the errors encountered while retrying
*/
public List<Exception> errors() {
return Collections.unmodifiableList(this.errors);
}
/**
* The number of retries performed.
*
* @return the number of retries performed
*/
public int attempts() {
return this.attempts.intValue();
}
@Override
public T perform() throws BusinessException {
do {
try {
return this.op.perform();
} catch (BusinessException e) {
this.errors.add(e);
if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) {
throw e;
}
try {
var testDelay = (long) Math.pow(2, this.attempts()) * 1000 + RANDOM.nextInt(1000);
var delay = Math.min(testDelay, this.maxDelay);
Thread.sleep(delay);
} catch (InterruptedException f) {
//ignore
}
}
} while (true);
}
}
| 3,810 | 32.13913 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
/**
* Performs some business operation.
*
* @param <T> the return type
* @author George Aristy (george.aristy@gmail.com)
*/
@FunctionalInterface
public interface BusinessOperation<T> {
/**
* Performs some business operation, returning a value {@code T} if successful, otherwise throwing
* an exception if an error occurs.
*
* @return the return value
* @throws BusinessException if the operation fails. Implementations are allowed to throw more
* specific subtypes depending on the error conditions
*/
T perform() throws BusinessException;
}
| 1,911 | 41.488889 | 140 | java |
java-design-patterns | java-design-patterns-master/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
/**
* Indicates that the customer was not found.
*
* <p>The severity of this error is bounded by its context: was the search for the customer
* triggered by an input from some end user, or were the search parameters pulled from your
* database?
*
* @author George Aristy (george.aristy@gmail.com)
*/
public final class CustomerNotFoundException extends BusinessException {
private static final long serialVersionUID = -6972888602621778664L;
/**
* Ctor.
*
* @param message the error message
*/
public CustomerNotFoundException(String message) {
super(message);
}
}
| 1,910 | 38.8125 | 140 | java |
java-design-patterns | java-design-patterns-master/combinator/src/test/java/com/iluwatar/combinator/CombinatorAppTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.combinator;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
class CombinatorAppTest {
/**
* Issue: Add at least one assertion to this test case.
* <p>
* Solution: Inserted assertion to check whether the execution of the main method in {@link CombinatorApp#main(String[])}
* throws an exception.
*/
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> CombinatorApp.main(new String[]{}));
}
}
| 1,810 | 40.159091 | 140 | java |
java-design-patterns | java-design-patterns-master/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.combinator;
import static com.iluwatar.combinator.Finders.advancedFinder;
import static com.iluwatar.combinator.Finders.expandedFinder;
import static com.iluwatar.combinator.Finders.filteredFinder;
import static com.iluwatar.combinator.Finders.specializedFinder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class FindersTest {
@Test
void advancedFinderTest() {
var res = advancedFinder("it was", "kingdom", "sea").find(text());
assertEquals(1, res.size());
assertEquals( "It was many and many a year ago,", res.get(0));
}
@Test
void filteredFinderTest() {
var res = filteredFinder(" was ", "many", "child").find(text());
assertEquals(1, res.size());
assertEquals( "But we loved with a love that was more than love-", res.get(0));
}
@Test
void specializedFinderTest() {
var res = specializedFinder("love", "heaven").find(text());
assertEquals(1, res.size());
assertEquals( "With a love that the winged seraphs of heaven", res.get(0));
}
@Test
void expandedFinderTest() {
var res = expandedFinder("It was", "kingdom").find(text());
assertEquals(3, res.size());
assertEquals( "It was many and many a year ago,", res.get(0));
assertEquals( "In a kingdom by the sea,", res.get(1));
assertEquals( "In this kingdom by the sea;", res.get(2));
}
private String text() {
return
"It was many and many a year ago,\n"
+ "In a kingdom by the sea,\n"
+ "That a maiden there lived whom you may know\n"
+ "By the name of ANNABEL LEE;\n"
+ "And this maiden she lived with no other thought\n"
+ "Than to love and be loved by me.\n"
+ "I was a child and she was a child,\n"
+ "In this kingdom by the sea;\n"
+ "But we loved with a love that was more than love-\n"
+ "I and my Annabel Lee;\n"
+ "With a love that the winged seraphs of heaven\n"
+ "Coveted her and me.";
}
}
| 3,348 | 38.4 | 140 | java |
java-design-patterns | java-design-patterns-master/combinator/src/test/java/com/iluwatar/combinator/FinderTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.combinator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class FinderTest {
@Test
void contains() {
var example = "the first one \nthe second one \n";
var result = Finder.contains("second").find(example);
assertEquals(1, result.size());
assertEquals( "the second one ", result.get(0));
}
}
| 1,673 | 38.857143 | 140 | java |
java-design-patterns | java-design-patterns-master/combinator/src/main/java/com/iluwatar/combinator/CombinatorApp.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.combinator;
import lombok.extern.slf4j.Slf4j;
/**
* The functional pattern representing a style of organizing libraries
* centered around the idea of combining functions.
* Putting it simply, there is some type T, some functions
* for constructing "primitive" values of type T,
* and some "combinators" which can combine values of type T
* in various ways to build up more complex values of type T.
* The class {@link Finder} defines a simple function {@link Finder#find(String)}
* and connected functions
* {@link Finder#or(Finder)},
* {@link Finder#not(Finder)},
* {@link Finder#and(Finder)}
* Using them the became possible to get more complex functions {@link Finders}
*/
@Slf4j
public class CombinatorApp {
/**
* main.
* @param args args
*/
public static void main(String[] args) {
var queriesOr = new String[]{"many", "Annabel"};
var finder = Finders.expandedFinder(queriesOr);
var res = finder.find(text());
LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res);
var queriesAnd = new String[]{"Annabel", "my"};
finder = Finders.specializedFinder(queriesAnd);
res = finder.find(text());
LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res);
finder = Finders.advancedFinder("it was", "kingdom", "sea");
res = finder.find(text());
LOGGER.info("the result of advanced query is {}", res);
res = Finders.filteredFinder(" was ", "many", "child").find(text());
LOGGER.info("the result of filtered query is {}", res);
}
private static String text() {
return
"It was many and many a year ago,\n"
+ "In a kingdom by the sea,\n"
+ "That a maiden there lived whom you may know\n"
+ "By the name of ANNABEL LEE;\n"
+ "And this maiden she lived with no other thought\n"
+ "Than to love and be loved by me.\n"
+ "I was a child and she was a child,\n"
+ "In this kingdom by the sea;\n"
+ "But we loved with a love that was more than love-\n"
+ "I and my Annabel Lee;\n"
+ "With a love that the winged seraphs of heaven\n"
+ "Coveted her and me.";
}
}
| 3,530 | 39.125 | 140 | java |
java-design-patterns | java-design-patterns-master/combinator/src/main/java/com/iluwatar/combinator/Finder.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.combinator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Functional interface to find lines in text.
*/
public interface Finder {
/**
* The function to find lines in text.
* @param text full tet
* @return result of searching
*/
List<String> find(String text);
/**
* Simple implementation of function {@link #find(String)}.
* @param word for searching
* @return this
*/
static Finder contains(String word) {
return txt -> Stream.of(txt.split("\n"))
.filter(line -> line.toLowerCase().contains(word.toLowerCase()))
.collect(Collectors.toList());
}
/**
* combinator not.
* @param notFinder finder to combine
* @return new finder including previous finders
*/
default Finder not(Finder notFinder) {
return txt -> {
List<String> res = this.find(txt);
res.removeAll(notFinder.find(txt));
return res;
};
}
/**
* combinator or.
* @param orFinder finder to combine
* @return new finder including previous finders
*/
default Finder or(Finder orFinder) {
return txt -> {
List<String> res = this.find(txt);
res.addAll(orFinder.find(txt));
return res;
};
}
/**
* combinator and.
* @param andFinder finder to combine
* @return new finder including previous finders
*/
default Finder and(Finder andFinder) {
return
txt -> this
.find(txt)
.stream()
.flatMap(line -> andFinder.find(line).stream())
.collect(Collectors.toList());
}
}
| 2,903 | 29.568421 | 140 | java |
java-design-patterns | java-design-patterns-master/combinator/src/main/java/com/iluwatar/combinator/Finders.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.combinator;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Complex finders consisting of simple finder.
*/
public class Finders {
private Finders() {
}
/**
* Finder to find a complex query.
* @param query to find
* @param orQuery alternative to find
* @param notQuery exclude from search
* @return new finder
*/
public static Finder advancedFinder(String query, String orQuery, String notQuery) {
return
Finder.contains(query)
.or(Finder.contains(orQuery))
.not(Finder.contains(notQuery));
}
/**
* Filtered finder looking a query with excluded queries as well.
* @param query to find
* @param excludeQueries to exclude
* @return new finder
*/
public static Finder filteredFinder(String query, String... excludeQueries) {
var finder = Finder.contains(query);
for (String q : excludeQueries) {
finder = finder.not(Finder.contains(q));
}
return finder;
}
/**
* Specialized query. Every next query is looked in previous result.
* @param queries array with queries
* @return new finder
*/
public static Finder specializedFinder(String... queries) {
var finder = identMult();
for (String query : queries) {
finder = finder.and(Finder.contains(query));
}
return finder;
}
/**
* Expanded query. Looking for alternatives.
* @param queries array with queries.
* @return new finder
*/
public static Finder expandedFinder(String... queries) {
var finder = identSum();
for (String query : queries) {
finder = finder.or(Finder.contains(query));
}
return finder;
}
private static Finder identMult() {
return txt -> Stream.of(txt.split("\n")).collect(Collectors.toList());
}
private static Finder identSum() {
return txt -> new ArrayList<>();
}
}
| 3,209 | 29.571429 | 140 | java |
java-design-patterns | java-design-patterns-master/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.business.delegate;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for the {@link BusinessDelegate}
*/
class BusinessDelegateTest {
private NetflixService netflixService;
private YouTubeService youTubeService;
private BusinessDelegate businessDelegate;
/**
* This method sets up the instance variables of this test class. It is executed before the
* execution of every test.
*/
@BeforeEach
void setup() {
netflixService = spy(new NetflixService());
youTubeService = spy(new YouTubeService());
BusinessLookup businessLookup = spy(new BusinessLookup());
businessLookup.setNetflixService(netflixService);
businessLookup.setYouTubeService(youTubeService);
businessDelegate = spy(new BusinessDelegate());
businessDelegate.setLookupService(businessLookup);
}
/**
* In this example the client ({@link MobileClient}) utilizes a business delegate (
* {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate
* service and makes the service call.
*/
@Test
void testBusinessDelegate() {
// setup a client object
var client = new MobileClient(businessDelegate);
// action
client.playbackMovie("Die hard");
// verifying that the businessDelegate was used by client during playbackMovie() method.
verify(businessDelegate).playbackMovie(anyString());
verify(netflixService).doProcessing();
// action
client.playbackMovie("Maradona");
// verifying that the businessDelegate was used by client during doTask() method.
verify(businessDelegate, times(2)).playbackMovie(anyString());
verify(youTubeService).doProcessing();
}
}
| 3,204 | 34.611111 | 140 | java |
java-design-patterns | java-design-patterns-master/business-delegate/src/test/java/com/iluwatar/business/delegate/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.business.delegate;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Business Delegate 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,867 | 36.36 | 140 | java |
java-design-patterns | java-design-patterns-master/business-delegate/src/main/java/com/iluwatar/business/delegate/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.business.delegate;
/**
* The Business Delegate pattern adds an abstraction layer between the presentation and business
* tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate
* encapsulates knowledge about how to locate, connect to, and interact with the business objects
* that make up the application.
*
* <p>Some of the services the Business Delegate uses are instantiated directly, and some can be
* retrieved through service lookups. The Business Delegate itself may contain business logic too
* potentially tying together multiple service calls, exception handling, retrying etc.
*
* <p>In this example the client ({@link MobileClient}) utilizes a business delegate (
* {@link BusinessDelegate}) to search for movies in video streaming services. The Business Delegate
* then selects the appropriate service and makes the service call.
*/
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// prepare the objects
var businessDelegate = new BusinessDelegate();
var businessLookup = new BusinessLookup();
businessLookup.setNetflixService(new NetflixService());
businessLookup.setYouTubeService(new YouTubeService());
businessDelegate.setLookupService(businessLookup);
// create the client and use the business delegate
var client = new MobileClient(businessDelegate);
client.playbackMovie("Die Hard 2");
client.playbackMovie("Maradona: The Greatest Ever");
}
}
| 2,855 | 44.333333 | 140 | java |
java-design-patterns | java-design-patterns-master/business-delegate/src/main/java/com/iluwatar/business/delegate/NetflixService.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.business.delegate;
import lombok.extern.slf4j.Slf4j;
/**
* NetflixService implementation.
*/
@Slf4j
public class NetflixService implements VideoStreamingService {
@Override
public void doProcessing() {
LOGGER.info("NetflixService is now processing");
}
}
| 1,575 | 38.4 | 140 | java |
java-design-patterns | java-design-patterns-master/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.business.delegate;
import java.util.Locale;
import lombok.Setter;
/**
* Class for performing service lookups.
*/
@Setter
public class BusinessLookup {
private NetflixService netflixService;
private YouTubeService youTubeService;
/**
* Gets service instance based on given movie search string.
*
* @param movie Search string for the movie.
* @return Service instance.
*/
public VideoStreamingService getBusinessService(String movie) {
if (movie.toLowerCase(Locale.ROOT).contains("die hard")) {
return netflixService;
} else {
return youTubeService;
}
}
}
| 1,915 | 34.481481 | 140 | java |
java-design-patterns | java-design-patterns-master/business-delegate/src/main/java/com/iluwatar/business/delegate/VideoStreamingService.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.business.delegate;
/**
* Interface for video streaming service implementations.
*/
public interface VideoStreamingService {
void doProcessing();
}
| 1,458 | 41.911765 | 140 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.