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/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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.Setter; /** * BusinessDelegate separates the presentation and business tiers. */ @Setter public class BusinessDelegate { private BusinessLookup lookupService; public void playbackMovie(String movie) { VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie); videoStreamingService.doProcessing(); } }
1,688
39.214286
140
java
java-design-patterns
java-design-patterns-master/business-delegate/src/main/java/com/iluwatar/business/delegate/YouTubeService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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; /** * YouTubeService implementation. */ @Slf4j public class YouTubeService implements VideoStreamingService { @Override public void doProcessing() { LOGGER.info("YouTubeService 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/MobileClient.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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; /** * MobileClient utilizes BusinessDelegate to call the business tier. */ public class MobileClient { private final BusinessDelegate businessDelegate; public MobileClient(BusinessDelegate businessDelegate) { this.businessDelegate = businessDelegate; } public void playbackMovie(String movie) { businessDelegate.playbackMovie(movie); } }
1,686
39.166667
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Date: 12/20/15 - 2:10 PM * * @author Jeroen Meulemeester */ class GiantModelTest { /** * Verify if the health value is set properly though the constructor and setter */ @Test void testSetHealth() { final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Health.HEALTHY, model.getHealth()); var messageFormat = "The giant looks %s, alert and saturated."; for (final var health : Health.values()) { model.setHealth(health); assertEquals(health, model.getHealth()); assertEquals(String.format(messageFormat, health), model.toString()); } } /** * Verify if the fatigue level is set properly though the constructor and setter */ @Test void testSetFatigue() { final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Fatigue.ALERT, model.getFatigue()); var messageFormat = "The giant looks healthy, %s and saturated."; for (final var fatigue : Fatigue.values()) { model.setFatigue(fatigue); assertEquals(fatigue, model.getFatigue()); assertEquals(String.format(messageFormat, fatigue), model.toString()); } } /** * Verify if the nourishment level is set properly though the constructor and setter */ @Test void testSetNourishment() { final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Nourishment.SATURATED, model.getNourishment()); var messageFormat = "The giant looks healthy, alert and %s."; for (final var nourishment : Nourishment.values()) { model.setNourishment(nourishment); assertEquals(nourishment, model.getNourishment()); assertEquals(String.format(messageFormat, nourishment), model.toString()); } } }
3,245
37.642857
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** * Date: 12/20/15 - 2:04 PM * * @author Jeroen Meulemeester */ class GiantViewTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(GiantView.class); } @AfterEach void tearDown() { appender.stop(); } /** * Verify if the {@link GiantView} does what it has to do: Print the {@link GiantModel} to the * standard out stream, nothing more, nothing less. */ @Test void testDisplayGiant() { final var view = new GiantView(); final var model = mock(GiantModel.class); view.displayGiant(model); assertEquals(model.toString(), appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } /** * Logging Appender Implementation */ public static class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender(Class<?> clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public String getLastMessage() { return log.get(log.size() - 1).getMessage(); } public int getLogSize() { return log.size(); } } }
3,059
29.909091
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.controller; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; /** * Date: 12/20/15 - 2:19 PM * * @author Jeroen Meulemeester */ class GiantControllerTest { /** * Verify if the controller passes the health level through to the model and vice versa */ @Test void testSetHealth() { final var model = mock(GiantModel.class); final var view = mock(GiantView.class); final var controller = new GiantController(model, view); verifyNoMoreInteractions(model, view); for (final var health : Health.values()) { controller.setHealth(health); verify(model).setHealth(health); verifyNoMoreInteractions(view); } controller.getHealth(); //noinspection ResultOfMethodCallIgnored verify(model).getHealth(); verifyNoMoreInteractions(model, view); } /** * Verify if the controller passes the fatigue level through to the model and vice versa */ @Test void testSetFatigue() { final var model = mock(GiantModel.class); final var view = mock(GiantView.class); final var controller = new GiantController(model, view); verifyNoMoreInteractions(model, view); for (final var fatigue : Fatigue.values()) { controller.setFatigue(fatigue); verify(model).setFatigue(fatigue); verifyNoMoreInteractions(view); } controller.getFatigue(); //noinspection ResultOfMethodCallIgnored verify(model).getFatigue(); verifyNoMoreInteractions(model, view); } /** * Verify if the controller passes the nourishment level through to the model and vice versa */ @Test void testSetNourishment() { final var model = mock(GiantModel.class); final var view = mock(GiantView.class); final var controller = new GiantController(model, view); verifyNoMoreInteractions(model, view); for (final var nourishment : Nourishment.values()) { controller.setNourishment(nourishment); verify(model).setNourishment(nourishment); verifyNoMoreInteractions(view); } controller.getNourishment(); //noinspection ResultOfMethodCallIgnored verify(model).getNourishment(); verifyNoMoreInteractions(model, view); } @Test void testUpdateView() { final var model = mock(GiantModel.class); final var view = mock(GiantView.class); final var controller = new GiantController(model, view); verifyNoMoreInteractions(model, view); controller.updateView(); verify(view).displayGiant(model); verifyNoMoreInteractions(model, view); } }
3,967
30.492063
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/test/java/com/iluwatar/model/view/controller/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.model.view.controller; 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,600
38.04878
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/main/java/com/iluwatar/model/view/controller/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.model.view.controller; /** * Model-View-Controller is a pattern for implementing user interfaces. It divides the application * into three interconnected parts namely the model, the view and the controller. * * <p>The central component of MVC, the model, captures the behavior of the application in terms of * its problem domain, independent of the user interface. The model directly manages the data, logic * and rules of the application. A view can be any output representation of information, such as a * chart or a diagram The third part, the controller, accepts input and converts it to commands for * the model or view. * * <p>In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and * nourishment. {@link GiantView} can display the giant with its current status. {@link * GiantController} receives input affecting the model and delegates redrawing the giant to the * view. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // create model, view and controller var giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); var view = new GiantView(); var controller = new GiantController(giant, view); // initial display controller.updateView(); // controller receives some interactions that affect the giant controller.setHealth(Health.WOUNDED); controller.setNourishment(Nourishment.HUNGRY); controller.setFatigue(Fatigue.TIRED); // redisplay controller.updateView(); } }
2,897
44.28125
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.controller; import lombok.AllArgsConstructor; /** * Fatigue enumeration. */ @AllArgsConstructor public enum Fatigue { ALERT("alert"), TIRED("tired"), SLEEPING("sleeping"); private final String title; @Override public String toString() { return title; } }
1,596
33.717391
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.controller; import lombok.AllArgsConstructor; /** * Nourishment enumeration. */ @AllArgsConstructor public enum Nourishment { SATURATED("saturated"), HUNGRY("hungry"), STARVING("starving"); private final String title; @Override public String toString() { return title; } }
1,614
34.108696
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.controller; import lombok.AllArgsConstructor; /** * Health enumeration. */ @AllArgsConstructor public enum Health { HEALTHY("healthy"), WOUNDED("wounded"), DEAD("dead"); private final String title; @Override public String toString() { return title; } }
1,594
33.673913
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.controller; import lombok.extern.slf4j.Slf4j; /** * GiantView displays the giant. */ @Slf4j public class GiantView { public void displayGiant(GiantModel giant) { LOGGER.info(giant.toString()); } }
1,526
38.153846
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.controller; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * GiantModel contains the giant data. */ @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor public class GiantModel { private Health health; private Fatigue fatigue; private Nourishment nourishment; @Override public String toString() { return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment); } }
1,828
33.509434
140
java
java-design-patterns
java-design-patterns-master/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.model.view.controller; /** * GiantController can update the giant data and redraw it using the view. */ public class GiantController { private final GiantModel giant; private final GiantView view; public GiantController(GiantModel giant, GiantView view) { this.giant = giant; this.view = view; } @SuppressWarnings("UnusedReturnValue") public Health getHealth() { return giant.getHealth(); } public void setHealth(Health health) { this.giant.setHealth(health); } @SuppressWarnings("UnusedReturnValue") public Fatigue getFatigue() { return giant.getFatigue(); } public void setFatigue(Fatigue fatigue) { this.giant.setFatigue(fatigue); } @SuppressWarnings("UnusedReturnValue") public Nourishment getNourishment() { return giant.getNourishment(); } public void setNourishment(Nourishment nourishment) { this.giant.setNourishment(nourishment); } public void updateView() { this.view.displayGiant(giant); } }
2,299
31.394366
140
java
java-design-patterns
java-design-patterns-master/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishV2Test.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.tolerantreader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Date: 12/30/15 - 18:35 PM * * @author Jeroen Meulemeester */ class RainbowFishV2Test { /** * Verify if the getters of a {@link RainbowFish} return the expected values */ @Test void testValues() { final var fish = new RainbowFishV2("name", 1, 2, 3, false, true, false); assertEquals("name", fish.getName()); assertEquals(1, fish.getAge()); assertEquals(2, fish.getLengthMeters()); assertEquals(3, fish.getWeightTons()); assertFalse(fish.isSleeping()); assertTrue(fish.isHungry()); assertFalse(fish.isAngry()); } }
2,109
37.363636
140
java
java-design-patterns
java-design-patterns-master/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.tolerantreader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; /** * Date: 12/30/15 - 18:39 PM * * @author Jeroen Meulemeester */ class RainbowFishSerializerTest { /** * Create a temporary folder, used to generate files in during this test */ @TempDir static Path testFolder; @BeforeEach void beforeEach() { assertTrue(Files.isDirectory(testFolder)); } /** * Rainbow fish version 1 used during the tests */ private static final RainbowFish V1 = new RainbowFish("version1", 1, 2, 3); /** * Rainbow fish version 2 used during the tests */ private static final RainbowFishV2 V2 = new RainbowFishV2("version2", 4, 5, 6, true, false, true); /** * Verify if a fish, written as version 1 can be read back as version 1 */ @Test void testWriteV1ReadV1() throws Exception { final var outputPath = Files.createFile(testFolder.resolve("outputFile")); RainbowFishSerializer.writeV1(V1, outputPath.toString()); final var fish = RainbowFishSerializer.readV1(outputPath.toString()); assertNotSame(V1, fish); assertEquals(V1.getName(), fish.getName()); assertEquals(V1.getAge(), fish.getAge()); assertEquals(V1.getLengthMeters(), fish.getLengthMeters()); assertEquals(V1.getWeightTons(), fish.getWeightTons()); } /** * Verify if a fish, written as version 2 can be read back as version 1 */ @Test void testWriteV2ReadV1() throws Exception { final var outputPath = Files.createFile(testFolder.resolve("outputFile2")); RainbowFishSerializer.writeV2(V2, outputPath.toString()); final var fish = RainbowFishSerializer.readV1(outputPath.toString()); assertNotSame(V2, fish); assertEquals(V2.getName(), fish.getName()); assertEquals(V2.getAge(), fish.getAge()); assertEquals(V2.getLengthMeters(), fish.getLengthMeters()); assertEquals(V2.getWeightTons(), fish.getWeightTons()); } }
3,523
34.24
140
java
java-design-patterns
java-design-patterns-master/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/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.tolerantreader; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import java.io.File; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Application test */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } @BeforeEach @AfterEach void cleanup() { var file1 = new File("fish1.out"); file1.delete(); var file2 = new File("fish2.out"); file2.delete(); } }
1,853
33.981132
140
java
java-design-patterns
java-design-patterns-master/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.tolerantreader; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Date: 12/30/15 - 18:34 PM * * @author Jeroen Meulemeester */ class RainbowFishTest { /** * Verify if the getters of a {@link RainbowFish} return the expected values */ @Test void testValues() { final var fish = new RainbowFish("name", 1, 2, 3); assertEquals("name", fish.getName()); assertEquals(1, fish.getAge()); assertEquals(2, fish.getLengthMeters()); assertEquals(3, fish.getWeightTons()); } }
1,864
36.3
140
java
java-design-patterns
java-design-patterns-master/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFish.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.tolerantreader; import java.io.Serializable; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * RainbowFish is the initial schema. */ @Getter @RequiredArgsConstructor public class RainbowFish implements Serializable { private static final long serialVersionUID = 1L; private final String name; private final int age; private final int lengthMeters; private final int weightTons; }
1,719
36.391304
140
java
java-design-patterns
java-design-patterns-master/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishV2.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.tolerantreader; import lombok.Getter; /** * RainbowFishV2 is the evolved schema. */ @Getter public class RainbowFishV2 extends RainbowFish { private static final long serialVersionUID = 1L; private boolean sleeping; private boolean hungry; private boolean angry; public RainbowFishV2(String name, int age, int lengthMeters, int weightTons) { super(name, age, lengthMeters, weightTons); } /** * Constructor. */ public RainbowFishV2(String name, int age, int lengthMeters, int weightTons, boolean sleeping, boolean hungry, boolean angry) { this(name, age, lengthMeters, weightTons); this.sleeping = sleeping; this.hungry = hungry; this.angry = angry; } }
2,034
34.701754
140
java
java-design-patterns
java-design-patterns-master/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.tolerantreader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Map; /** * RainbowFishSerializer provides methods for reading and writing {@link RainbowFish} objects to * file. Tolerant Reader pattern is implemented here by serializing maps instead of {@link * RainbowFish} objects. This way the reader does not break even though new properties are added to * the schema. */ public final class RainbowFishSerializer { public static final String LENGTH_METERS = "lengthMeters"; public static final String WEIGHT_TONS = "weightTons"; private RainbowFishSerializer() { } /** * Write V1 RainbowFish to file. */ public static void writeV1(RainbowFish rainbowFish, String filename) throws IOException { var map = Map.of( "name", rainbowFish.getName(), "age", String.format("%d", rainbowFish.getAge()), LENGTH_METERS, String.format("%d", rainbowFish.getLengthMeters()), WEIGHT_TONS, String.format("%d", rainbowFish.getWeightTons()) ); try (var fileOut = new FileOutputStream(filename); var objOut = new ObjectOutputStream(fileOut)) { objOut.writeObject(map); } } /** * Write V2 RainbowFish to file. */ public static void writeV2(RainbowFishV2 rainbowFish, String filename) throws IOException { var map = Map.of( "name", rainbowFish.getName(), "age", String.format("%d", rainbowFish.getAge()), LENGTH_METERS, String.format("%d", rainbowFish.getLengthMeters()), WEIGHT_TONS, String.format("%d", rainbowFish.getWeightTons()), "angry", Boolean.toString(rainbowFish.isAngry()), "hungry", Boolean.toString(rainbowFish.isHungry()), "sleeping", Boolean.toString(rainbowFish.isSleeping()) ); try (var fileOut = new FileOutputStream(filename); var objOut = new ObjectOutputStream(fileOut)) { objOut.writeObject(map); } } /** * Read V1 RainbowFish from file. */ public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException { Map<String, String> map; try (var fileIn = new FileInputStream(filename); var objIn = new ObjectInputStream(fileIn)) { map = (Map<String, String>) objIn.readObject(); } return new RainbowFish( map.get("name"), Integer.parseInt(map.get("age")), Integer.parseInt(map.get(LENGTH_METERS)), Integer.parseInt(map.get(WEIGHT_TONS)) ); } }
3,884
36.355769
140
java
java-design-patterns
java-design-patterns-master/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/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.tolerantreader; import java.io.IOException; import lombok.extern.slf4j.Slf4j; /** * Tolerant Reader is an integration pattern that helps creating robust communication systems. The * idea is to be as tolerant as possible when reading data from another service. This way, when the * communication schema changes, the readers must not break. * * <p>In this example we use Java serialization to write representations of {@link RainbowFish} * objects to file. {@link RainbowFish} is the initial version which we can easily read and write * using {@link RainbowFishSerializer} methods. {@link RainbowFish} then evolves to {@link * RainbowFishV2} and we again write it to file with a method designed to do just that. However, the * reader client does not know about the new format and still reads with the method designed for V1 * schema. Fortunately the reading method has been designed with the Tolerant Reader pattern and * does not break even though {@link RainbowFishV2} has new fields that are serialized. */ @Slf4j public class App { /** * Program entry point. */ public static void main(String[] args) throws IOException, ClassNotFoundException { // Write V1 var fishV1 = new RainbowFish("Zed", 10, 11, 12); LOGGER.info("fishV1 name={} age={} length={} weight={}", fishV1.getName(), fishV1.getAge(), fishV1.getLengthMeters(), fishV1.getWeightTons()); RainbowFishSerializer.writeV1(fishV1, "fish1.out"); // Read V1 var deserializedRainbowFishV1 = RainbowFishSerializer.readV1("fish1.out"); LOGGER.info("deserializedFishV1 name={} age={} length={} weight={}", deserializedRainbowFishV1.getName(), deserializedRainbowFishV1.getAge(), deserializedRainbowFishV1.getLengthMeters(), deserializedRainbowFishV1.getWeightTons()); // Write V2 var fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true); LOGGER.info( "fishV2 name={} age={} length={} weight={} sleeping={} hungry={} angry={}", fishV2.getName(), fishV2.getAge(), fishV2.getLengthMeters(), fishV2.getWeightTons(), fishV2.isHungry(), fishV2.isAngry(), fishV2.isSleeping()); RainbowFishSerializer.writeV2(fishV2, "fish2.out"); // Read V2 with V1 method var deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out"); LOGGER.info("deserializedFishV2 name={} age={} length={} weight={}", deserializedFishV2.getName(), deserializedFishV2.getAge(), deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons()); } }
3,840
50.905405
140
java
java-design-patterns
java-design-patterns-master/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.execute.around; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; import java.nio.file.Files; import org.junit.Rule; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; import org.junit.rules.TemporaryFolder; /** * Date: 12/12/15 - 3:21 PM * * @author Jeroen Meulemeester */ @EnableRuleMigrationSupport class SimpleFileWriterTest { @Rule public final TemporaryFolder testFolder = new TemporaryFolder(); @Test void testWriterNotNull() throws Exception { final var temporaryFile = this.testFolder.newFile(); new SimpleFileWriter(temporaryFile.getPath(), Assertions::assertNotNull); } @Test void testCreatesNonExistentFile() throws Exception { final var nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file"); assertFalse(nonExistingFile.exists()); new SimpleFileWriter(nonExistingFile.getPath(), Assertions::assertNotNull); assertTrue(nonExistingFile.exists()); } @Test void testContentsAreWrittenToFile() throws Exception { final var testMessage = "Test message"; final var temporaryFile = this.testFolder.newFile(); assertTrue(temporaryFile.exists()); new SimpleFileWriter(temporaryFile.getPath(), writer -> writer.write(testMessage)); assertTrue(Files.lines(temporaryFile.toPath()).allMatch(testMessage::equals)); } @Test void testRipplesIoExceptionOccurredWhileWriting() { var message = "Some error"; assertThrows(IOException.class, () -> { final var temporaryFile = this.testFolder.newFile(); new SimpleFileWriter(temporaryFile.getPath(), writer -> { throw new IOException(message); }); }, message); } }
3,237
35.382022
140
java
java-design-patterns
java-design-patterns-master/execute-around/src/test/java/com/iluwatar/execute/around/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.execute.around; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests execute-around example. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } @BeforeEach @AfterEach void cleanup() { var file = new File("testfile.txt"); file.delete(); } }
1,847
34.538462
140
java
java-design-patterns
java-design-patterns-master/execute-around/src/main/java/com/iluwatar/execute/around/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.execute.around; import java.io.File; import java.io.IOException; import java.util.Scanner; import lombok.extern.slf4j.Slf4j; /** * The Execute Around idiom specifies executable code before and after a method. Typically * the idiom is used when the API has methods to be executed in pairs, such as resource * allocation/deallocation or lock acquisition/release. * * <p>In this example, we have {@link SimpleFileWriter} class that opens and closes the file for * the user. The user specifies only what to do with the file by providing the {@link * FileWriterAction} implementation. */ @Slf4j public class App { /** * Program entry point. */ public static void main(String[] args) throws IOException { // create the file writer and execute the custom action FileWriterAction writeHello = writer -> { writer.write("Gandalf was here"); }; new SimpleFileWriter("testfile.txt", writeHello); // print the file contents try (var scanner = new Scanner(new File("testfile.txt"))) { while (scanner.hasNextLine()) { LOGGER.info(scanner.nextLine()); } } } }
2,428
37.555556
140
java
java-design-patterns
java-design-patterns-master/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.execute.around; import java.io.FileWriter; import java.io.IOException; /** * Interface for specifying what to do with the file resource. */ @FunctionalInterface public interface FileWriterAction { void writeFile(FileWriter writer) throws IOException; }
1,566
39.179487
140
java
java-design-patterns
java-design-patterns-master/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.execute.around; import java.io.FileWriter; import java.io.IOException; import lombok.extern.slf4j.Slf4j; /** * SimpleFileWriter handles opening and closing file for the user. The user only has to specify what * to do with the file resource through {@link FileWriterAction} parameter. */ @Slf4j public class SimpleFileWriter { /** * Constructor. */ public SimpleFileWriter(String filename, FileWriterAction action) throws IOException { LOGGER.info("Opening the file"); try (var writer = new FileWriter(filename)) { LOGGER.info("Executing the action"); action.writeFile(writer); LOGGER.info("Closing the file"); } } }
1,969
38.4
140
java
java-design-patterns
java-design-patterns-master/metadata-mapping/src/test/java/com/iluwatar/metamapping/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.metamapping; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that metadata mapping 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 shouldExecuteMetaMappingWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,843
39.977778
140
java
java-design-patterns
java-design-patterns-master/metadata-mapping/src/main/java/com/iluwatar/metamapping/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.metamapping; import com.iluwatar.metamapping.model.User; import com.iluwatar.metamapping.service.UserService; import com.iluwatar.metamapping.utils.DatabaseUtil; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.hibernate.service.ServiceRegistry; /** * Metadata Mapping specifies the mapping * between classes and tables so that * we could treat a table of any database like a Java class. * * <p>With hibernate, we achieve list/create/update/delete/get operations: * 1)Create the H2 Database in {@link DatabaseUtil}. * 2)Hibernate resolve hibernate.cfg.xml and generate service like save/list/get/delete. * For learning metadata mapping pattern, we go deeper into Hibernate here: * a)read properties from hibernate.cfg.xml and mapping from *.hbm.xml * b)create session factory to generate session interacting with database * c)generate session with factory pattern * d)create query object or use basic api with session, * hibernate will convert all query to database query according to metadata * 3)We encapsulate hibernate service in {@link UserService} for our use. * @see org.hibernate.cfg.Configuration#configure(String) * @see org.hibernate.cfg.Configuration#buildSessionFactory(ServiceRegistry) * @see org.hibernate.internal.SessionFactoryImpl#openSession() */ @Slf4j public class App { /** * Program entry point. * * @param args command line args. * @throws Exception if any error occurs. */ public static void main(String[] args) throws Exception { // get service var userService = new UserService(); // use create service to add users for (var user : generateSampleUsers()) { var id = userService.createUser(user); LOGGER.info("Add user" + user + "at" + id + "."); } // use list service to get users var users = userService.listUser(); LOGGER.info(String.valueOf(users)); // use get service to get a user var user = userService.getUser(1); LOGGER.info(String.valueOf(user)); // change password of user 1 user.setPassword("new123"); // use update service to update user 1 userService.updateUser(1, user); // use delete service to delete user 2 userService.deleteUser(2); // close service userService.close(); } /** * Generate users. * * @return list of users. */ public static List<User> generateSampleUsers() { final var user1 = new User("ZhangSan", "zhs123"); final var user2 = new User("LiSi", "ls123"); final var user3 = new User("WangWu", "ww123"); return List.of(user1, user2, user3); } }
3,898
39.614583
140
java
java-design-patterns
java-design-patterns-master/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.metamapping.service; import com.iluwatar.metamapping.model.User; import com.iluwatar.metamapping.utils.HibernateUtil; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; /** * Service layer for user. */ @Slf4j public class UserService { private static final SessionFactory factory = HibernateUtil.getSessionFactory(); /** * List all users. * @return list of users */ public List<User> listUser() { LOGGER.info("list all users."); List<User> users = new ArrayList<>(); try (var session = factory.openSession()) { var tx = session.beginTransaction(); List<User> userIter = session.createQuery("FROM User").list(); for (var iterator = userIter.iterator(); iterator.hasNext();) { users.add(iterator.next()); } tx.commit(); } catch (HibernateException e) { LOGGER.debug("fail to get users", e); } return users; } /** * Add a user. * @param user user entity * @return user id */ public int createUser(User user) { LOGGER.info("create user: " + user.getUsername()); var id = -1; try (var session = factory.openSession()) { var tx = session.beginTransaction(); id = (Integer) session.save(user); tx.commit(); } catch (HibernateException e) { LOGGER.debug("fail to create user", e); } LOGGER.info("create user " + user.getUsername() + " at " + id); return id; } /** * Update user. * @param id user id * @param user new user entity */ public void updateUser(Integer id, User user) { LOGGER.info("update user at " + id); try (var session = factory.openSession()) { var tx = session.beginTransaction(); user.setId(id); session.update(user); tx.commit(); } catch (HibernateException e) { LOGGER.debug("fail to update user", e); } } /** * Delete user. * @param id user id */ public void deleteUser(Integer id) { LOGGER.info("delete user at: " + id); try (var session = factory.openSession()) { var tx = session.beginTransaction(); var user = session.get(User.class, id); session.delete(user); tx.commit(); } catch (HibernateException e) { LOGGER.debug("fail to delete user", e); } } /** * Get user. * @param id user id * @return deleted user */ public User getUser(Integer id) { LOGGER.info("get user at: " + id); User user = null; try (var session = factory.openSession()) { var tx = session.beginTransaction(); user = session.get(User.class, id); tx.commit(); } catch (HibernateException e) { LOGGER.debug("fail to get user", e); } return user; } /** * Close hibernate. */ public void close() { HibernateUtil.shutdown(); } }
4,200
29.442029
140
java
java-design-patterns
java-design-patterns-master/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.metamapping.utils; import java.sql.SQLException; import lombok.extern.slf4j.Slf4j; import org.h2.jdbcx.JdbcDataSource; /** * Create h2 database. */ @Slf4j public class DatabaseUtil { private static final String DB_URL = "jdbc:h2:mem:metamapping"; private static final String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS `user_account`;" + "CREATE TABLE `user_account` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `username` varchar(255) NOT NULL,\n" + " `password` varchar(255) NOT NULL,\n" + " PRIMARY KEY (`id`)\n" + ");"; /** * Hide constructor. */ private DatabaseUtil() {} static { LOGGER.info("create h2 database"); var source = new JdbcDataSource(); source.setURL(DB_URL); try (var statement = source.getConnection().createStatement()) { statement.execute(CREATE_SCHEMA_SQL); } catch (SQLException e) { LOGGER.error("unable to create h2 data source", e); } } }
2,278
36.983333
140
java
java-design-patterns
java-design-patterns-master/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/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.metamapping.utils; import lombok.extern.slf4j.Slf4j; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Manage hibernate. */ @Slf4j public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); /** * Hide constructor. */ private HibernateUtil() {} /** * Build session factory. * @return session factory */ private static SessionFactory buildSessionFactory() { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } /** * Get session factory. * @return session factory */ public static SessionFactory getSessionFactory() { return sessionFactory; } /** * Close session factory. */ public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } }
2,205
30.971014
140
java
java-design-patterns
java-design-patterns-master/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.metamapping.model; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * User Entity. */ @Setter @Getter @ToString public class User { private Integer id; private String username; private String password; public User() {} /** * Get a user. * @param username user name * @param password user password */ public User(String username, String password) { this.username = username; this.password = password; } }
1,771
32.433962
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for abstract factory. */ class AbstractFactoryTest { private final App app = new App(); @Test void verifyKingCreation() { app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); final var kingdom = app.getKingdom(); final var elfKing = kingdom.getKing(); assertTrue(elfKing instanceof ElfKing); assertEquals(ElfKing.DESCRIPTION, elfKing.getDescription()); app.createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); final var orcKing = kingdom.getKing(); assertTrue(orcKing instanceof OrcKing); assertEquals(OrcKing.DESCRIPTION, orcKing.getDescription()); } @Test void verifyCastleCreation() { app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); final var kingdom = app.getKingdom(); final var elfCastle = kingdom.getCastle(); assertTrue(elfCastle instanceof ElfCastle); assertEquals(ElfCastle.DESCRIPTION, elfCastle.getDescription()); app.createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); final var orcCastle = kingdom.getCastle(); assertTrue(orcCastle instanceof OrcCastle); assertEquals(OrcCastle.DESCRIPTION, orcCastle.getDescription()); } @Test void verifyArmyCreation() { app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); final var kingdom = app.getKingdom(); final var elfArmy = kingdom.getArmy(); assertTrue(elfArmy instanceof ElfArmy); assertEquals(ElfArmy.DESCRIPTION, elfArmy.getDescription()); app.createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); final var orcArmy = kingdom.getArmy(); assertTrue(orcArmy instanceof OrcArmy); assertEquals(OrcArmy.DESCRIPTION, orcArmy.getDescription()); } @Test void verifyElfKingdomCreation() { app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); final var kingdom = app.getKingdom(); final var king = kingdom.getKing(); final var castle = kingdom.getCastle(); final var army = kingdom.getArmy(); assertTrue(king instanceof ElfKing); assertEquals(ElfKing.DESCRIPTION, king.getDescription()); assertTrue(castle instanceof ElfCastle); assertEquals(ElfCastle.DESCRIPTION, castle.getDescription()); assertTrue(army instanceof ElfArmy); assertEquals(ElfArmy.DESCRIPTION, army.getDescription()); } @Test void verifyOrcKingdomCreation() { app.createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); final var kingdom = app.getKingdom(); final var king = kingdom.getKing(); final var castle = kingdom.getCastle(); final var army = kingdom.getArmy(); assertTrue(king instanceof OrcKing); assertEquals(OrcKing.DESCRIPTION, king.getDescription()); assertTrue(castle instanceof OrcCastle); assertEquals(OrcCastle.DESCRIPTION, castle.getDescription()); assertTrue(army instanceof OrcArmy); assertEquals(OrcArmy.DESCRIPTION, army.getDescription()); } }
4,340
36.422414
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/test/java/com/iluwatar/abstractfactory/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.abstractfactory; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Check whether the execution of the main method in {@link App} throws an exception. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,664
38.642857
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * Castle interface. */ public interface Castle { String getDescription(); }
1,408
40.441176
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/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.abstractfactory; import lombok.extern.slf4j.Slf4j; /** * The Abstract Factory pattern provides a way to encapsulate a group of individual factories that * have a common theme without specifying their concrete classes. In normal usage, the client * software creates a concrete implementation of the abstract factory and then uses the generic * interface of the factory to create the concrete objects that are part of the theme. The client * does not know (or care) which concrete objects it gets from each of these internal factories, * since it uses only the generic interfaces of their products. This pattern separates the details * of implementation of a set of objects from their general usage and relies on object composition, * as object creation is implemented in methods exposed in the factory interface. * * <p>The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) * and its implementations ( {@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses * both concrete implementations to create a king, a castle, and an army. */ @Slf4j public class App implements Runnable { private final Kingdom kingdom = new Kingdom(); public Kingdom getKingdom() { return kingdom; } /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var app = new App(); app.run(); } @Override public void run() { LOGGER.info("elf kingdom"); createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); LOGGER.info(kingdom.getArmy().getDescription()); LOGGER.info(kingdom.getCastle().getDescription()); LOGGER.info(kingdom.getKing().getDescription()); LOGGER.info("orc kingdom"); createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); LOGGER.info(kingdom.getArmy().getDescription()); LOGGER.info(kingdom.getCastle().getDescription()); LOGGER.info(kingdom.getKing().getDescription()); } /** * Creates kingdom. * @param kingdomType type of Kingdom */ public void createKingdom(final Kingdom.FactoryMaker.KingdomType kingdomType) { final KingdomFactory kingdomFactory = Kingdom.FactoryMaker.makeFactory(kingdomType); kingdom.setKing(kingdomFactory.createKing()); kingdom.setCastle(kingdomFactory.createCastle()); kingdom.setArmy(kingdomFactory.createArmy()); } }
3,671
41.206897
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * ElfArmy. */ public class ElfArmy implements Army { static final String DESCRIPTION = "This is the elven army!"; @Override public String getDescription() { return DESCRIPTION; } }
1,524
38.102564
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * OrcArmy. */ public class OrcArmy implements Army { static final String DESCRIPTION = "This is the orc army!"; @Override public String getDescription() { return DESCRIPTION; } }
1,522
38.051282
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * ElfCastle. */ public class ElfCastle implements Castle { static final String DESCRIPTION = "This is the elven castle!"; @Override public String getDescription() { return DESCRIPTION; } }
1,532
38.307692
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * OrcCastle. */ public class OrcCastle implements Castle { static final String DESCRIPTION = "This is the orc castle!"; @Override public String getDescription() { return DESCRIPTION; } }
1,530
38.25641
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * ElfKingdomFactory concrete factory. */ public class ElfKingdomFactory implements KingdomFactory { @Override public Castle createCastle() { return new ElfCastle(); } @Override public King createKing() { return new ElfKing(); } @Override public Army createArmy() { return new ElfArmy(); } }
1,654
33.479167
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/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.abstractfactory; /** * OrcKing. */ public class OrcKing implements King { static final String DESCRIPTION = "This is the orc king!"; @Override public String getDescription() { return DESCRIPTION; } }
1,522
38.051282
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Kingdom.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; import lombok.Getter; import lombok.Setter; /** * Helper class to manufacture {@link KingdomFactory} beans. */ @Getter @Setter public class Kingdom { private King king; private Castle castle; private Army army; /** * The factory of kingdom factories. */ public static class FactoryMaker { /** * Enumeration for the different types of Kingdoms. */ public enum KingdomType { ELF, ORC } /** * The factory method to create KingdomFactory concrete objects. */ public static KingdomFactory makeFactory(KingdomType type) { return switch (type) { case ELF -> new ElfKingdomFactory(); case ORC -> new OrcKingdomFactory(); default -> throw new IllegalArgumentException("KingdomType not supported."); }; } } }
2,134
31.846154
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * Army interface. */ public interface Army { String getDescription(); }
1,404
40.323529
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * ElfKing. */ public class ElfKing implements King { static final String DESCRIPTION = "This is the elven king!"; @Override public String getDescription() { return DESCRIPTION; } }
1,524
38.102564
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * King interface. */ public interface King { String getDescription(); }
1,404
40.323529
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * KingdomFactory factory interface. */ public interface KingdomFactory { Castle createCastle(); King createKing(); Army createArmy(); }
1,475
36.846154
140
java
java-design-patterns
java-design-patterns-master/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractfactory; /** * OrcKingdomFactory concrete factory. */ public class OrcKingdomFactory implements KingdomFactory { @Override public Castle createCastle() { return new OrcCastle(); } @Override public King createKing() { return new OrcKing(); } @Override public Army createArmy() { return new OrcArmy(); } }
1,653
34.191489
140
java
java-design-patterns
java-design-patterns-master/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; /** * Date: 12/30/15 - 19:45 PM. * * @author Jeroen Meulemeester */ class CommanderTest extends UnitTest<Commander> { /** * Create a new test instance for the given {@link Commander}. */ public CommanderTest() { super(Commander::new); } @Override void verifyVisit(Commander unit, UnitVisitor mockedVisitor) { verify(mockedVisitor).visit(eq(unit)); } }
1,789
35.530612
140
java
java-design-patterns
java-design-patterns-master/visitor/src/test/java/com/iluwatar/visitor/SoldierVisitorTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import java.util.Optional; /** * Date: 12/30/15 - 18:59 PM. * * @author Jeroen Meulemeester */ class SoldierVisitorTest extends VisitorTest<SoldierVisitor> { /** * Create a new test instance for the given visitor. */ public SoldierVisitorTest() { super( new SoldierVisitor(), Optional.empty(), Optional.empty(), Optional.of("Greetings soldier") ); } }
1,726
34.244898
140
java
java-design-patterns
java-design-patterns-master/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; /** * Date: 12/30/15 - 19:45 PM. * * @author Jeroen Meulemeester */ class SergeantTest extends UnitTest<Sergeant> { /** * Create a new test instance for the given {@link Sergeant}. */ public SergeantTest() { super(Sergeant::new); } @Override void verifyVisit(Sergeant unit, UnitVisitor mockedVisitor) { verify(mockedVisitor).visit(eq(unit)); } }
1,783
35.408163
140
java
java-design-patterns
java-design-patterns-master/visitor/src/test/java/com/iluwatar/visitor/CommanderVisitorTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import java.util.Optional; /** * Date: 12/30/15 - 18:43 PM. * * @author Jeroen Meulemeester */ class CommanderVisitorTest extends VisitorTest<CommanderVisitor> { /** * Create a new test instance for the given visitor. */ public CommanderVisitorTest() { super( new CommanderVisitor(), Optional.of("Good to see you commander"), Optional.empty(), Optional.empty() ); } }
1,742
34.571429
140
java
java-design-patterns
java-design-patterns-master/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import static org.junit.jupiter.api.Assertions.assertEquals; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** * Date: 12/30/15 - 18:59 PM. Test case for Visitor Pattern * * @param <V> Type of UnitVisitor * @author Jeroen Meulemeester */ public abstract class VisitorTest<V extends UnitVisitor> { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } /** * The tested visitor instance. */ private final V visitor; /** * The optional expected response when being visited by a commander. */ private final Optional<String> commanderResponse; /** * The optional expected response when being visited by a sergeant. */ private final Optional<String> sergeantResponse; /** * The optional expected response when being visited by a soldier. */ private final Optional<String> soldierResponse; /** * Create a new test instance for the given visitor. * * @param commanderResponse The optional expected response when being visited by a commander * @param sergeantResponse The optional expected response when being visited by a sergeant * @param soldierResponse The optional expected response when being visited by a soldier */ public VisitorTest( final V visitor, final Optional<String> commanderResponse, final Optional<String> sergeantResponse, final Optional<String> soldierResponse ) { this.visitor = visitor; this.commanderResponse = commanderResponse; this.sergeantResponse = sergeantResponse; this.soldierResponse = soldierResponse; } @Test void testVisitCommander() { this.visitor.visit(new Commander()); if (this.commanderResponse.isPresent()) { assertEquals(this.commanderResponse.get(), appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } } @Test void testVisitSergeant() { this.visitor.visit(new Sergeant()); if (this.sergeantResponse.isPresent()) { assertEquals(this.sergeantResponse.get(), appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } } @Test void testVisitSoldier() { this.visitor.visit(new Soldier()); if (this.soldierResponse.isPresent()) { assertEquals(this.soldierResponse.get(), appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } } private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public int getLogSize() { return log.size(); } public String getLastMessage() { return log.get(log.size() - 1).getFormattedMessage(); } } }
4,591
30.027027
140
java
java-design-patterns
java-design-patterns-master/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; /** * Date: 12/30/15 - 19:45 PM. * * @author Jeroen Meulemeester */ class SoldierTest extends UnitTest<Soldier> { /** * Create a new test instance for the given {@link Soldier}. */ public SoldierTest() { super(Soldier::new); } @Override void verifyVisit(Soldier unit, UnitVisitor mockedVisitor) { verify(mockedVisitor).visit(eq(unit)); } }
1,777
35.285714
140
java
java-design-patterns
java-design-patterns-master/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.Arrays; import java.util.function.Function; import org.junit.jupiter.api.Test; /** * Date: 12/30/15 - 18:59 PM. Test related to Units * * @param <U> Type of Unit * @author Jeroen Meulemeester */ public abstract class UnitTest<U extends Unit> { /** * Factory to create new instances of the tested unit. */ private final Function<Unit[], U> factory; /** * Create a new test instance for the given unit type {@link U}. * * @param factory Factory to create new instances of the tested unit */ public UnitTest(final Function<Unit[], U> factory) { this.factory = factory; } @Test void testAccept() { final var children = new Unit[5]; Arrays.setAll(children, (i) -> mock(Unit.class)); final var unit = this.factory.apply(children); final var visitor = mock(UnitVisitor.class); unit.accept(visitor); verifyVisit(unit, visitor); Arrays.stream(children).forEach(child -> verify(child).accept(eq(visitor))); verifyNoMoreInteractions(children); verifyNoMoreInteractions(visitor); } /** * Verify if the correct visit method is called on the mock, depending on the tested instance. * * @param unit The tested unit instance * @param mockedVisitor The mocked {@link UnitVisitor} who should have gotten a visit by the unit */ abstract void verifyVisit(final U unit, final UnitVisitor mockedVisitor); }
2,923
34.228916
140
java
java-design-patterns
java-design-patterns-master/visitor/src/test/java/com/iluwatar/visitor/SergeantVisitorTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import java.util.Optional; /** * Date: 12/30/15 - 18:36 PM. * * @author Jeroen Meulemeester */ class SergeantVisitorTest extends VisitorTest<SergeantVisitor> { /** * Create a new test instance for the given visitor. */ public SergeantVisitorTest() { super( new SergeantVisitor(), Optional.empty(), Optional.of("Hello sergeant"), Optional.empty() ); } }
1,727
34.265306
140
java
java-design-patterns
java-design-patterns-master/visitor/src/test/java/com/iluwatar/visitor/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.visitor; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test. */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,576
37.463415
140
java
java-design-patterns
java-design-patterns-master/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; /** * Visitor interface. */ public interface UnitVisitor { void visit(Soldier soldier); void visit(Sergeant sergeant); void visit(Commander commander); }
1,481
37
140
java
java-design-patterns
java-design-patterns-master/visitor/src/main/java/com/iluwatar/visitor/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.visitor; /** * <p>Visitor pattern defines a mechanism to apply operations on nodes in a hierarchy. New * operations can be added without altering the node interface.</p> * * <p>In this example there is a unit hierarchy beginning from {@link Commander}. This hierarchy is * traversed by visitors. {@link SoldierVisitor} applies its operation on {@link Soldier}s, {@link * SergeantVisitor} on {@link Sergeant}s and so on.</p> */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var commander = new Commander( new Sergeant(new Soldier(), new Soldier(), new Soldier()), new Sergeant(new Soldier(), new Soldier(), new Soldier()) ); commander.accept(new SoldierVisitor()); commander.accept(new SergeantVisitor()); commander.accept(new CommanderVisitor()); } }
2,199
39.740741
140
java
java-design-patterns
java-design-patterns-master/visitor/src/main/java/com/iluwatar/visitor/Soldier.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; /** * Soldier. */ public class Soldier extends Unit { public Soldier(Unit... children) { super(children); } /** * Accept a Visitor. * @param visitor UnitVisitor to be accepted */ @Override public void accept(UnitVisitor visitor) { visitor.visit(this); super.accept(visitor); } @Override public String toString() { return "soldier"; } }
1,699
32.333333
140
java
java-design-patterns
java-design-patterns-master/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import lombok.extern.slf4j.Slf4j; /** * CommanderVisitor. */ @Slf4j public class CommanderVisitor implements UnitVisitor { /** * Soldier Visitor method. * @param soldier Soldier to be visited */ @Override public void visit(Soldier soldier) { // Do nothing } /** * Sergeant Visitor method. * @param sergeant Sergeant to be visited */ @Override public void visit(Sergeant sergeant) { // Do nothing } /** * Commander Visitor method. * @param commander Commander to be visited */ @Override public void visit(Commander commander) { LOGGER.info("Good to see you {}", commander); } }
1,961
30.645161
140
java
java-design-patterns
java-design-patterns-master/visitor/src/main/java/com/iluwatar/visitor/Unit.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import java.util.Arrays; /** * Interface for the nodes in hierarchy. */ public abstract class Unit { private final Unit[] children; public Unit(Unit... children) { this.children = children; } /** * Accept visitor. */ public void accept(UnitVisitor visitor) { Arrays.stream(children).forEach(child -> child.accept(visitor)); } }
1,675
34.659574
140
java
java-design-patterns
java-design-patterns-master/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import lombok.extern.slf4j.Slf4j; /** * SoldierVisitor. */ @Slf4j public class SoldierVisitor implements UnitVisitor { /** * Soldier Visitor method. * @param soldier Soldier to be visited */ @Override public void visit(Soldier soldier) { LOGGER.info("Greetings {}", soldier); } /** * Sergeant Visitor method. * @param sergeant Sergeant to be visited */ @Override public void visit(Sergeant sergeant) { // Do nothing } /** * Commander Visitor method. * @param commander Commander to be visited */ @Override public void visit(Commander commander) { // Do nothing } }
1,949
30.451613
140
java
java-design-patterns
java-design-patterns-master/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; /** * Sergeant. */ public class Sergeant extends Unit { public Sergeant(Unit... children) { super(children); } /** * Accept a Visitor. * @param visitor UnitVisitor to be accepted */ @Override public void accept(UnitVisitor visitor) { visitor.visit(this); super.accept(visitor); } @Override public String toString() { return "sergeant"; } }
1,703
32.411765
140
java
java-design-patterns
java-design-patterns-master/visitor/src/main/java/com/iluwatar/visitor/Commander.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; /** * Commander. */ public class Commander extends Unit { public Commander(Unit... children) { super(children); } /** * Accept a Visitor. * @param visitor UnitVisitor to be accepted */ @Override public void accept(UnitVisitor visitor) { visitor.visit(this); super.accept(visitor); } @Override public String toString() { return "commander"; } }
1,707
32.490196
140
java
java-design-patterns
java-design-patterns-master/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import lombok.extern.slf4j.Slf4j; /** * SergeantVisitor. */ @Slf4j public class SergeantVisitor implements UnitVisitor { /** * Soldier Visitor method. * @param soldier Soldier to be visited */ @Override public void visit(Soldier soldier) { // Do nothing } /** * Sergeant Visitor method. * @param sergeant Sergeant to be visited */ @Override public void visit(Sergeant sergeant) { LOGGER.info("Hello {}", sergeant); } /** * Commander Visitor method. * @param commander Commander to be visited */ @Override public void visit(Commander commander) { // Do nothing } }
1,948
30.435484
140
java
java-design-patterns
java-design-patterns-master/builder/src/test/java/com/iluwatar/builder/HeroTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.builder; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; /** * Date: 12/6/15 - 11:01 PM * * @author Jeroen Meulemeester */ class HeroTest { /** * Test if we get the expected exception when trying to create a hero without a profession */ @Test void testMissingProfession() { assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(null, "Sir without a job")); } /** * Test if we get the expected exception when trying to create a hero without a name */ @Test void testMissingName() { assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(Profession.THIEF, null)); } /** * Test if the hero build by the builder has the correct attributes, as requested */ @Test void testBuildHero() { final String heroName = "Sir Lancelot"; final var hero = new Hero.Builder(Profession.WARRIOR, heroName) .withArmor(Armor.CHAIN_MAIL) .withWeapon(Weapon.SWORD) .withHairType(HairType.LONG_CURLY) .withHairColor(HairColor.BLOND) .build(); assertNotNull(hero); assertNotNull(hero.toString()); assertEquals(Profession.WARRIOR, hero.profession()); assertEquals(heroName, hero.name()); assertEquals(Armor.CHAIN_MAIL, hero.armor()); assertEquals(Weapon.SWORD, hero.weapon()); assertEquals(HairType.LONG_CURLY, hero.hairType()); assertEquals(HairColor.BLOND, hero.hairColor()); } }
2,900
34.814815
140
java
java-design-patterns
java-design-patterns-master/builder/src/test/java/com/iluwatar/builder/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.builder; 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,787
36.25
140
java
java-design-patterns
java-design-patterns-master/builder/src/main/java/com/iluwatar/builder/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.builder; import com.iluwatar.builder.Hero.Builder; import lombok.extern.slf4j.Slf4j; /** * The intention of the Builder pattern is to find a solution to the telescoping constructor * anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object * constructor parameter combination leads to an exponential list of constructors. Instead of using * numerous constructors, the builder pattern uses another object, a builder, that receives each * initialization parameter step by step and then returns the resulting constructed object at once. * * <p>The Builder pattern has another benefit. It can be used for objects that contain flat data * (html code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. * This type of data cannot be edited step by step and must be edited at once. The best way to * construct such an object is to use a builder class. * * <p>In this example we have the Builder pattern variation as described by Joshua Bloch in * Effective Java 2nd Edition. * * <p>We want to build {@link Hero} objects, but its construction is complex because of the many * parameters needed. To aid the user we introduce {@link Builder} class. {@link Hero.Builder} takes * the minimum parameters to build {@link Hero} object in its constructor. After that additional * configuration for the {@link Hero} object can be done using the fluent {@link Builder} interface. * When configuration is ready the build method is called to receive the final {@link Hero} object. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var mage = new Hero.Builder(Profession.MAGE, "Riobard") .withHairColor(HairColor.BLACK) .withWeapon(Weapon.DAGGER) .build(); LOGGER.info(mage.toString()); var warrior = new Hero.Builder(Profession.WARRIOR, "Amberjill") .withHairColor(HairColor.BLOND) .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD) .build(); LOGGER.info(warrior.toString()); var thief = new Hero.Builder(Profession.THIEF, "Desmond") .withHairType(HairType.BALD) .withWeapon(Weapon.BOW) .build(); LOGGER.info(thief.toString()); } }
3,644
44.5625
140
java
java-design-patterns
java-design-patterns-master/builder/src/main/java/com/iluwatar/builder/Armor.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.builder; import lombok.AllArgsConstructor; /** * Armor enumeration. */ @AllArgsConstructor public enum Armor { CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), PLATE_MAIL("plate mail"); private final String title; @Override public String toString() { return title; } }
1,618
33.446809
140
java
java-design-patterns
java-design-patterns-master/builder/src/main/java/com/iluwatar/builder/HairType.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.builder; import lombok.AllArgsConstructor; /** * HairType enumeration. */ @AllArgsConstructor public enum HairType { BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY("long curly"); private final String title; @Override public String toString() { return title; } }
1,638
33.145833
140
java
java-design-patterns
java-design-patterns-master/builder/src/main/java/com/iluwatar/builder/Profession.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.builder; /** * Profession enumeration. */ public enum Profession { WARRIOR, THIEF, MAGE, PRIEST; @Override public String toString() { return name().toLowerCase(); } }
1,489
37.205128
140
java
java-design-patterns
java-design-patterns-master/builder/src/main/java/com/iluwatar/builder/HairColor.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.builder; /** * HairColor enumeration. */ public enum HairColor { WHITE, BLOND, RED, BROWN, BLACK; @Override public String toString() { return name().toLowerCase(); } }
1,499
33.090909
140
java
java-design-patterns
java-design-patterns-master/builder/src/main/java/com/iluwatar/builder/Hero.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.builder; /** * Hero,the record class. */ public record Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { private Hero(Builder builder) { this(builder.profession, builder.name, builder.hairType, builder.hairColor, builder.armor, builder.weapon); } @Override public String toString() { var sb = new StringBuilder(); sb.append("This is a ") .append(profession) .append(" named ") .append(name); if (hairColor != null || hairType != null) { sb.append(" with "); if (hairColor != null) { sb.append(hairColor).append(' '); } if (hairType != null) { sb.append(hairType).append(' '); } sb.append(hairType != HairType.BALD ? "hair" : "head"); } if (armor != null) { sb.append(" wearing ").append(armor); } if (weapon != null) { sb.append(" and wielding a ").append(weapon); } sb.append('.'); return sb.toString(); } /** * The builder class. */ public static class Builder { private final Profession profession; private final String name; private HairType hairType; private HairColor hairColor; private Armor armor; private Weapon weapon; /** * Constructor. */ public Builder(Profession profession, String name) { if (profession == null || name == null) { throw new IllegalArgumentException("profession and name can not be null"); } this.profession = profession; this.name = name; } public Builder withHairType(HairType hairType) { this.hairType = hairType; return this; } public Builder withHairColor(HairColor hairColor) { this.hairColor = hairColor; return this; } public Builder withArmor(Armor armor) { this.armor = armor; return this; } public Builder withWeapon(Weapon weapon) { this.weapon = weapon; return this; } public Hero build() { return new Hero(this); } } }
3,371
28.840708
140
java
java-design-patterns
java-design-patterns-master/builder/src/main/java/com/iluwatar/builder/Weapon.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.builder; /** * Weapon enumeration. */ public enum Weapon { DAGGER, SWORD, AXE, WARHAMMER, BOW; @Override public String toString() { return name().toLowerCase(); } }
1,487
37.153846
140
java
java-design-patterns
java-design-patterns-master/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/SquareNumberRequestTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.fanout.fanin; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class SquareNumberRequestTest { @Test void delayedSquaringTest() { Consumer consumer = new Consumer(10L); SquareNumberRequest squareNumberRequest = new SquareNumberRequest(5L); squareNumberRequest.delayedSquaring(consumer); Assertions.assertEquals(35, consumer.getSumOfSquaredNumbers().get()); } }
1,721
39.046512
140
java
java-design-patterns
java-design-patterns-master/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/FanOutFanInTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.fanout.fanin; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; class FanOutFanInTest { @Test void fanOutFanInTest() { final List<Long> numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L); final List<SquareNumberRequest> requests = numbers.stream().map(SquareNumberRequest::new).toList(); final Consumer consumer = new Consumer(0L); final Long sumOfSquaredNumbers = FanOutFanIn.fanOutFanIn(requests, consumer); Assertions.assertEquals(139, sumOfSquaredNumbers); } }
1,878
38.145833
140
java
java-design-patterns
java-design-patterns-master/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/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.fanout.fanin; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; class AppTest { @Test void shouldLaunchApp() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,548
39.763158
140
java
java-design-patterns
java-design-patterns-master/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/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.fanout.fanin; import java.util.Arrays; import java.util.List; import lombok.extern.slf4j.Slf4j; /** * FanOut/FanIn pattern is a concurrency pattern that refers to executing multiple instances of the * activity function concurrently. The "fan out" part is essentially splitting the data into * multiple chunks and then calling the activity function multiple times, passing the chunks. * * <p>When each chunk has been processed, the "fan in" takes place that aggregates results from each * instance of function and forms a single final result. * * <p>This pattern is only really useful if you can “chunk” the workload in a meaningful way for * splitting up to be processed in parallel. */ @Slf4j public class App { /** * Entry point. * * <p>Implementation provided has a list of numbers that has to be squared and added. The list can * be chunked in any way and the "activity function" {@link * SquareNumberRequest#delayedSquaring(Consumer)} i.e. squaring the number ca be done * concurrently. The "fan in" part is handled by the {@link Consumer} that takes in the result * from each instance of activity and aggregates it whenever that particular activity function * gets over. */ public static void main(String[] args) { final List<Long> numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L); LOGGER.info("Numbers to be squared and get sum --> {}", numbers); final List<SquareNumberRequest> requests = numbers.stream().map(SquareNumberRequest::new).toList(); var consumer = new Consumer(0L); // Pass the request and the consumer to fanOutFanIn or sometimes referred as Orchestrator // function final Long sumOfSquaredNumbers = FanOutFanIn.fanOutFanIn(requests, consumer); LOGGER.info("Sum of all squared numbers --> {}", sumOfSquaredNumbers); } }
3,135
41.378378
140
java
java-design-patterns
java-design-patterns-master/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.fanout.fanin; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * FanOutFanIn class processes long running requests, when any of the processes gets over, result is * passed over to the consumer or the callback function. Consumer will aggregate the results as they * keep on completing. */ public class FanOutFanIn { /** * the main fanOutFanIn function or orchestrator function. * @param requests List of numbers that need to be squared and summed up * @param consumer Takes in the squared number from {@link SquareNumberRequest} and sums it up * @return Aggregated sum of all squared numbers. */ public static Long fanOutFanIn( final List<SquareNumberRequest> requests, final Consumer consumer) { ExecutorService service = Executors.newFixedThreadPool(requests.size()); // fanning out List<CompletableFuture<Void>> futures = requests.stream() .map( request -> CompletableFuture.runAsync(() -> request.delayedSquaring(consumer), service)) .toList(); CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); return consumer.getSumOfSquaredNumbers().get(); } }
2,615
40.52381
140
java
java-design-patterns
java-design-patterns-master/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/Consumer.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.fanout.fanin; import java.util.concurrent.atomic.AtomicLong; import lombok.Getter; /** * Consumer or callback class that will be called everytime a request is complete This will * aggregate individual result to form a final result. */ @Getter public class Consumer { private final AtomicLong sumOfSquaredNumbers; Consumer(Long init) { sumOfSquaredNumbers = new AtomicLong(init); } public Long add(final Long num) { return sumOfSquaredNumbers.addAndGet(num); } }
1,795
35.653061
140
java
java-design-patterns
java-design-patterns-master/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.fanout.fanin; import java.security.SecureRandom; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Squares the number with a little timeout to give impression of long running process that return * at different times. */ @Slf4j @AllArgsConstructor public class SquareNumberRequest { private final Long number; /** * Squares the number with a little timeout to give impression of long running process that return * at different times. * @param consumer callback class that takes the result after the delay. * */ public void delayedSquaring(final Consumer consumer) { var minTimeOut = 5000L; SecureRandom secureRandom = new SecureRandom(); var randomTimeOut = secureRandom.nextInt(2000); try { // this will make the thread sleep from 5-7s. Thread.sleep(minTimeOut + randomTimeOut); } catch (InterruptedException e) { LOGGER.error("Exception while sleep ", e); Thread.currentThread().interrupt(); } finally { consumer.add(number * number); } } }
2,359
35.875
140
java
java-design-patterns
java-design-patterns-master/state/src/test/java/com/iluwatar/state/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.state; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,573
37.390244
140
java
java-design-patterns
java-design-patterns-master/state/src/test/java/com/iluwatar/state/MammothTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.state; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** * Date: 12/29/15 - 8:27 PM * * @author Jeroen Meulemeester */ class MammothTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } /** * Switch to a complete mammoth 'mood'-cycle and verify if the observed mood matches the expected * value. */ @Test void testTimePasses() { final var mammoth = new Mammoth(); mammoth.observe(); assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); assertEquals(1, appender.getLogSize()); mammoth.timePasses(); assertEquals("The mammoth gets angry!", appender.getLastMessage()); assertEquals(2, appender.getLogSize()); mammoth.observe(); assertEquals("The mammoth is furious!", appender.getLastMessage()); assertEquals(3, appender.getLogSize()); mammoth.timePasses(); assertEquals("The mammoth calms down.", appender.getLastMessage()); assertEquals(4, appender.getLogSize()); mammoth.observe(); assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); assertEquals(5, appender.getLogSize()); } /** * Verify if {@link Mammoth#toString()} gives the expected value */ @Test void testToString() { final var toString = new Mammoth().toString(); assertNotNull(toString); assertEquals("The mammoth", toString); } private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public int getLogSize() { return log.size(); } public String getLastMessage() { return log.get(log.size() - 1).getFormattedMessage(); } } }
3,731
29.590164
140
java
java-design-patterns
java-design-patterns-master/state/src/main/java/com/iluwatar/state/PeacefulState.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.state; import lombok.extern.slf4j.Slf4j; /** * Peaceful state. */ @Slf4j public class PeacefulState implements State { private final Mammoth mammoth; public PeacefulState(Mammoth mammoth) { this.mammoth = mammoth; } @Override public void observe() { LOGGER.info("{} is calm and peaceful.", mammoth); } @Override public void onEnterState() { LOGGER.info("{} calms down.", mammoth); } }
1,729
32.269231
140
java
java-design-patterns
java-design-patterns-master/state/src/main/java/com/iluwatar/state/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.state; /** * In the State pattern, the container object has an internal state object that defines the current * behavior. The state object can be changed to alter the behavior. * * <p>This can be a cleaner way for an object to change its behavior at runtime without resorting * to large monolithic conditional statements and thus improves maintainability. * * <p>In this example the {@link Mammoth} changes its behavior as time passes by. */ public class App { /** * Program entry point. */ public static void main(String[] args) { var mammoth = new Mammoth(); mammoth.observe(); mammoth.timePasses(); mammoth.observe(); mammoth.timePasses(); mammoth.observe(); } }
2,019
37.846154
140
java
java-design-patterns
java-design-patterns-master/state/src/main/java/com/iluwatar/state/AngryState.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.state; import lombok.extern.slf4j.Slf4j; /** * Angry state. */ @Slf4j public class AngryState implements State { private final Mammoth mammoth; public AngryState(Mammoth mammoth) { this.mammoth = mammoth; } @Override public void observe() { LOGGER.info("{} is furious!", mammoth); } @Override public void onEnterState() { LOGGER.info("{} gets angry!", mammoth); } }
1,710
31.903846
140
java
java-design-patterns
java-design-patterns-master/state/src/main/java/com/iluwatar/state/Mammoth.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.state; /** * Mammoth has internal state that defines its behavior. */ public class Mammoth { private State state; public Mammoth() { state = new PeacefulState(this); } /** * Makes time pass for the mammoth. */ public void timePasses() { if (state.getClass().equals(PeacefulState.class)) { changeStateTo(new AngryState(this)); } else { changeStateTo(new PeacefulState(this)); } } private void changeStateTo(State newState) { this.state = newState; this.state.onEnterState(); } @Override public String toString() { return "The mammoth"; } public void observe() { this.state.observe(); } }
1,977
30.396825
140
java
java-design-patterns
java-design-patterns-master/state/src/main/java/com/iluwatar/state/State.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.state; /** * State interface. */ public interface State { void onEnterState(); void observe(); }
1,411
38.222222
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; import static org.junit.jupiter.api.Assertions.assertTrue; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.time.LocalDateTime; import java.util.LinkedList; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** * Date: 12/27/15 - 9:45 PM * * @author Jeroen Meulemeester */ class ConsumerTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(Consumer.class); } @AfterEach void tearDown() { appender.stop(); } @Test void testConsume() throws Exception { final var messages = List.of( createMessage("you", "Hello!"), createMessage("me", "Hi!"), Message.POISON_PILL, createMessage("late_for_the_party", "Hello? Anyone here?") ); final var queue = new SimpleMessageQueue(messages.size()); for (final var message : messages) { queue.put(message); } new Consumer("NSA", queue).consume(); assertTrue(appender.logContains("Message [Hello!] from [you] received by [NSA]")); assertTrue(appender.logContains("Message [Hi!] from [me] received by [NSA]")); assertTrue(appender.logContains("Consumer NSA receive request to terminate.")); } /** * Create a new message from the given sender with the given message body * * @param sender The sender's name * @param message The message body * @return The message instance */ private static Message createMessage(final String sender, final String message) { final var msg = new SimpleMessage(); msg.addHeader(Message.Headers.SENDER, sender); msg.addHeader(Message.Headers.DATE, LocalDateTime.now().toString()); msg.setBody(message); return msg; } private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public boolean logContains(String message) { return log.stream().map(ILoggingEvent::getFormattedMessage).anyMatch(message::equals); } } }
3,744
31.850877
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; import static com.iluwatar.poison.pill.Message.Headers; import static com.iluwatar.poison.pill.Message.POISON_PILL; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; /** * Date: 12/27/15 - 10:30 PM * * @author Jeroen Meulemeester */ class PoisonMessageTest { @Test void testAddHeader() { assertThrows(UnsupportedOperationException.class, () -> { POISON_PILL.addHeader(Headers.SENDER, "sender"); }); } @Test void testGetHeader() { assertThrows(UnsupportedOperationException.class, () -> { POISON_PILL.getHeader(Headers.SENDER); }); } @Test void testGetHeaders() { assertThrows(UnsupportedOperationException.class, POISON_PILL::getHeaders); } @Test void testSetBody() { assertThrows(UnsupportedOperationException.class, () -> { POISON_PILL.setBody("Test message."); }); } @Test void testGetBody() { assertThrows(UnsupportedOperationException.class, POISON_PILL::getBody); } }
2,331
31.388889
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; /** * Date: 12/27/15 - 10:32 PM * * @author Jeroen Meulemeester */ class ProducerTest { @Test void testSend() throws Exception { final var publishPoint = mock(MqPublishPoint.class); final var producer = new Producer("producer", publishPoint); verifyNoMoreInteractions(publishPoint); producer.send("Hello!"); final var messageCaptor = ArgumentCaptor.forClass(Message.class); verify(publishPoint).put(messageCaptor.capture()); final var message = messageCaptor.getValue(); assertNotNull(message); assertEquals("producer", message.getHeader(Message.Headers.SENDER)); assertNotNull(message.getHeader(Message.Headers.DATE)); assertEquals("Hello!", message.getBody()); verifyNoMoreInteractions(publishPoint); } @Test void testStop() throws Exception { final var publishPoint = mock(MqPublishPoint.class); final var producer = new Producer("producer", publishPoint); verifyNoMoreInteractions(publishPoint); producer.stop(); verify(publishPoint).put(eq(Message.POISON_PILL)); try { producer.send("Hello!"); fail("Expected 'IllegalStateException' at this point, since the producer has stopped!"); } catch (IllegalStateException e) { assertNotNull(e); assertNotNull(e.getMessage()); assertEquals("Producer Hello! was stopped and fail to deliver requested message [producer].", e.getMessage()); } verifyNoMoreInteractions(publishPoint); } }
3,236
35.784091
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Date: 12/27/15 - 10:25 PM * * @author Jeroen Meulemeester */ class SimpleMessageTest { @Test void testGetHeaders() { final var message = new SimpleMessage(); assertNotNull(message.getHeaders()); assertTrue(message.getHeaders().isEmpty()); final var senderName = "test"; message.addHeader(Message.Headers.SENDER, senderName); assertNotNull(message.getHeaders()); assertFalse(message.getHeaders().isEmpty()); assertEquals(senderName, message.getHeaders().get(Message.Headers.SENDER)); } @Test void testUnModifiableHeaders() { final var message = new SimpleMessage(); final var headers = message.getHeaders(); assertThrows(UnsupportedOperationException.class, () -> { headers.put(Message.Headers.SENDER, "test"); }); } }
2,457
36.815385
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/test/java/com/iluwatar/poison/pill/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.poison.pill; 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/poison-pill/src/main/java/com/iluwatar/poison/pill/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.poison.pill; /** * One of the possible approaches to terminate Producer-Consumer pattern is using the Poison Pill * idiom. If you use Poison Pill as the termination signal then Producer is responsible to notify * Consumer that the exchange is over and reject any further messages. The Consumer receiving Poison * Pill will stop reading messages from the queue. You must also ensure that the Poison Pill will be * the last message that will be read from the queue (if you have prioritized queue then this can be * tricky). * * <p>In simple cases the Poison Pill can be just a null-reference, but holding a unique separate * shared object-marker (with name "Poison" or "Poison Pill") is more clear and self describing. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var queue = new SimpleMessageQueue(10000); final var producer = new Producer("PRODUCER_1", queue); final var consumer = new Consumer("CONSUMER_1", queue); new Thread(consumer::consume).start(); new Thread(() -> { producer.send("hand shake"); producer.send("some very important information"); producer.send("bye!"); producer.stop(); }).start(); } }
2,578
41.278689
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; /** * Endpoint to publish {@link Message} to queue. */ public interface MqPublishPoint { void put(Message msg) throws InterruptedException; }
1,466
42.147059
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; /** * Endpoint to retrieve {@link Message} from queue. */ public interface MqSubscribePoint { Message take() throws InterruptedException; }
1,464
42.088235
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; import com.iluwatar.poison.pill.Message.Headers; import java.util.Date; import lombok.extern.slf4j.Slf4j; /** * Class responsible for producing unit of work that can be expressed as message and submitted to * queue. */ @Slf4j public class Producer { private final MqPublishPoint queue; private final String name; private boolean isStopped; /** * Constructor. */ public Producer(String name, MqPublishPoint queue) { this.name = name; this.queue = queue; this.isStopped = false; } /** * Send message to queue. */ public void send(String body) { if (isStopped) { throw new IllegalStateException(String.format( "Producer %s was stopped and fail to deliver requested message [%s].", body, name)); } var msg = new SimpleMessage(); msg.addHeader(Headers.DATE, new Date().toString()); msg.addHeader(Headers.SENDER, name); msg.setBody(body); try { queue.put(msg); } catch (InterruptedException e) { // allow thread to exit LOGGER.error("Exception caught.", e); } } /** * Stop system by sending poison pill. */ public void stop() { isStopped = true; try { queue.put(Message.POISON_PILL); } catch (InterruptedException e) { // allow thread to exit LOGGER.error("Exception caught.", e); } } }
2,667
30.388235
140
java
java-design-patterns
java-design-patterns-master/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.poison.pill; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * {@link Message} basic implementation. */ public class SimpleMessage implements Message { private final Map<Headers, String> headers = new HashMap<>(); private String body; @Override public void addHeader(Headers header, String value) { headers.put(header, value); } @Override public String getHeader(Headers header) { return headers.get(header); } @Override public Map<Headers, String> getHeaders() { return Collections.unmodifiableMap(headers); } @Override public void setBody(String body) { this.body = body; } @Override public String getBody() { return body; } }
2,032
30.765625
140
java