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/service-layer/src/test/java/com/iluwatar/servicelayer/app/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.servicelayer.app; import com.iluwatar.servicelayer.hibernate.HibernateUtil; import org.junit.jupiter.api.AfterEach; 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[]{})); } @AfterEach void tearDown() { HibernateUtil.dropSession(); } }
1,754
34.816327
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.magic; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.iluwatar.servicelayer.spell.Spell; import com.iluwatar.servicelayer.spell.SpellDao; import com.iluwatar.servicelayer.spellbook.Spellbook; import com.iluwatar.servicelayer.spellbook.SpellbookDao; import com.iluwatar.servicelayer.wizard.Wizard; import com.iluwatar.servicelayer.wizard.WizardDao; import java.util.Set; import org.junit.jupiter.api.Test; /** * Date: 12/29/15 - 12:06 AM * * @author Jeroen Meulemeester */ class MagicServiceImplTest { @Test void testFindAllWizards() { final var wizardDao = mock(WizardDao.class); final var spellbookDao = mock(SpellbookDao.class); final var spellDao = mock(SpellDao.class); final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyNoInteractions(wizardDao, spellbookDao, spellDao); service.findAllWizards(); verify(wizardDao).findAll(); verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); } @Test void testFindAllSpellbooks() { final var wizardDao = mock(WizardDao.class); final var spellbookDao = mock(SpellbookDao.class); final var spellDao = mock(SpellDao.class); final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyNoInteractions(wizardDao, spellbookDao, spellDao); service.findAllSpellbooks(); verify(spellbookDao).findAll(); verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); } @Test void testFindAllSpells() { final var wizardDao = mock(WizardDao.class); final var spellbookDao = mock(SpellbookDao.class); final var spellDao = mock(SpellDao.class); final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyNoInteractions(wizardDao, spellbookDao, spellDao); service.findAllSpells(); verify(spellDao).findAll(); verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); } @Test void testFindWizardsWithSpellbook() { final var bookname = "bookname"; final var spellbook = mock(Spellbook.class); final var wizards = Set.of( mock(Wizard.class), mock(Wizard.class), mock(Wizard.class) ); when(spellbook.getWizards()).thenReturn(wizards); final var spellbookDao = mock(SpellbookDao.class); when(spellbookDao.findByName(bookname)).thenReturn(spellbook); final var wizardDao = mock(WizardDao.class); final var spellDao = mock(SpellDao.class); final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyNoInteractions(wizardDao, spellbookDao, spellDao, spellbook); final var result = service.findWizardsWithSpellbook(bookname); verify(spellbookDao).findByName(bookname); verify(spellbook).getWizards(); assertNotNull(result); assertEquals(3, result.size()); verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); } @Test void testFindWizardsWithSpell() throws Exception { final var wizards = Set.of( mock(Wizard.class), mock(Wizard.class), mock(Wizard.class) ); final var spellbook = mock(Spellbook.class); when(spellbook.getWizards()).thenReturn(wizards); final var spellbookDao = mock(SpellbookDao.class); final var wizardDao = mock(WizardDao.class); final var spell = mock(Spell.class); when(spell.getSpellbook()).thenReturn(spellbook); final var spellName = "spellname"; final var spellDao = mock(SpellDao.class); when(spellDao.findByName(spellName)).thenReturn(spell); final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyNoInteractions(wizardDao, spellbookDao, spellDao, spellbook); final var result = service.findWizardsWithSpell(spellName); verify(spellDao).findByName(spellName); verify(spellbook).getWizards(); assertNotNull(result); assertEquals(3, result.size()); verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); } }
5,597
34.43038
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.spellbook; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.iluwatar.servicelayer.common.BaseDaoTest; import org.junit.jupiter.api.Test; /** * Date: 12/28/15 - 11:44 PM * * @author Jeroen Meulemeester */ class SpellbookDaoImplTest extends BaseDaoTest<Spellbook, SpellbookDaoImpl> { public SpellbookDaoImplTest() { super(Spellbook::new, new SpellbookDaoImpl()); } @Test void testFindByName() { final var dao = getDao(); final var allBooks = dao.findAll(); for (final var book : allBooks) { final var spellByName = dao.findByName(book.getName()); assertNotNull(spellByName); assertEquals(book.getId(), spellByName.getId()); assertEquals(book.getName(), spellByName.getName()); } } }
2,148
36.701754
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.spell; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.iluwatar.servicelayer.common.BaseDaoTest; import org.junit.jupiter.api.Test; /** * Date: 12/28/15 - 11:02 PM * * @author Jeroen Meulemeester */ class SpellDaoImplTest extends BaseDaoTest<Spell, SpellDaoImpl> { public SpellDaoImplTest() { super(Spell::new, new SpellDaoImpl()); } @Test void testFindByName() { final var dao = getDao(); final var allSpells = dao.findAll(); for (final var spell : allSpells) { final var spellByName = dao.findByName(spell.getName()); assertNotNull(spellByName); assertEquals(spell.getId(), spellByName.getId()); assertEquals(spell.getName(), spellByName.getName()); } } }
2,126
36.315789
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/Wizard.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.wizard; import com.iluwatar.servicelayer.common.BaseEntity; import com.iluwatar.servicelayer.spellbook.Spellbook; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; /** * Wizard entity. */ @Entity @Table(name = "WIZARD") public class Wizard extends BaseEntity { @Id @GeneratedValue @Column(name = "WIZARD_ID") private Long id; private String name; @ManyToMany(cascade = CascadeType.ALL) private Set<Spellbook> spellbooks; public Wizard() { spellbooks = new HashSet<>(); } public Wizard(String name) { this(); this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Spellbook> getSpellbooks() { return spellbooks; } public void setSpellbooks(Set<Spellbook> spellbooks) { this.spellbooks = spellbooks; } public void addSpellbook(Spellbook spellbook) { spellbook.getWizards().add(this); spellbooks.add(spellbook); } @Override public String toString() { return name; } }
2,697
26.252525
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.wizard; import com.iluwatar.servicelayer.common.DaoBaseImpl; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.Transaction; import org.hibernate.query.Query; /** * WizardDao implementation. */ public class WizardDaoImpl extends DaoBaseImpl<Wizard> implements WizardDao { @Override public Wizard findByName(String name) { Transaction tx = null; Wizard result; try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<Wizard> builderQuery = criteriaBuilder.createQuery(Wizard.class); Root<Wizard> root = builderQuery.from(Wizard.class); builderQuery.select(root).where(criteriaBuilder.equal(root.get("name"), name)); Query<Wizard> query = session.createQuery(builderQuery); result = query.uniqueResult(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; } return result; } }
2,453
39.229508
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDao.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.wizard; import com.iluwatar.servicelayer.common.Dao; /** * WizardDao interface. */ public interface WizardDao extends Dao<Wizard> { Wizard findByName(String name); }
1,492
39.351351
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.common; import com.iluwatar.servicelayer.hibernate.HibernateUtil; import java.lang.reflect.ParameterizedType; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; /** * Base class for Dao implementations. * * @param <E> Type of Entity */ public abstract class DaoBaseImpl<E extends BaseEntity> implements Dao<E> { @SuppressWarnings("unchecked") protected Class<E> persistentClass = (Class<E>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; /* * Making this getSessionFactory() instead of getSession() so that it is the responsibility * of the caller to open as well as close the session (prevents potential resource leak). */ protected SessionFactory getSessionFactory() { return HibernateUtil.getSessionFactory(); } @Override public E find(Long id) { Transaction tx = null; E result; try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<E> builderQuery = criteriaBuilder.createQuery(persistentClass); Root<E> root = builderQuery.from(persistentClass); builderQuery.select(root).where(criteriaBuilder.equal(root.get("id"), id)); Query<E> query = session.createQuery(builderQuery); result = query.uniqueResult(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; } return result; } @Override public void persist(E entity) { Transaction tx = null; try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); session.persist(entity); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; } } @Override public E merge(E entity) { Transaction tx = null; E result = null; try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); result = (E) session.merge(entity); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; } return result; } @Override public void delete(E entity) { Transaction tx = null; try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); session.delete(entity); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; } } @Override public List<E> findAll() { Transaction tx = null; List<E> result; try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<E> builderQuery = criteriaBuilder.createQuery(persistentClass); Root<E> root = builderQuery.from(persistentClass); builderQuery.select(root); Query<E> query = session.createQuery(builderQuery); result = query.getResultList(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; } return result; } }
4,734
31.431507
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/common/BaseEntity.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.common; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.MappedSuperclass; /** * Base class for entities. */ @MappedSuperclass @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public abstract class BaseEntity { /** * Indicates the unique id of this entity. * * @return The id of the entity, or 'null' when not persisted */ public abstract Long getId(); /** * Set the id of this entity. * * @param id The new id */ public abstract void setId(Long id); /** * Get the name of this entity. * * @return The name of the entity */ public abstract String getName(); /** * Set the name of this entity. * * @param name The new name */ public abstract void setName(final String name); }
2,131
30.820896
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/common/Dao.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.common; import java.util.List; /** * Dao interface. * * @param <E> Type of Entity */ public interface Dao<E extends BaseEntity> { E find(Long id); void persist(E entity); E merge(E entity); void delete(E entity); List<E> findAll(); }
1,573
33.217391
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.app; import com.iluwatar.servicelayer.magic.MagicService; import com.iluwatar.servicelayer.magic.MagicServiceImpl; import com.iluwatar.servicelayer.spell.Spell; import com.iluwatar.servicelayer.spell.SpellDaoImpl; import com.iluwatar.servicelayer.spellbook.Spellbook; import com.iluwatar.servicelayer.spellbook.SpellbookDaoImpl; import com.iluwatar.servicelayer.wizard.Wizard; import com.iluwatar.servicelayer.wizard.WizardDaoImpl; import lombok.extern.slf4j.Slf4j; /** * Service layer defines an application's boundary with a layer of services that establishes a set * of available operations and coordinates the application's response in each operation. * * <p>Enterprise applications typically require different kinds of interfaces to the data they * store and the logic they implement: data loaders, user interfaces, integration gateways, and * others. Despite their different purposes, these interfaces often need common interactions with * the application to access and manipulate its data and invoke its business logic. The interactions * may be complex, involving transactions across multiple resources and the coordination of several * responses to an action. Encoding the logic of the interactions separately in each interface * causes a lot of duplication. * * <p>The example application demonstrates interactions between a client ({@link App}) and a * service ({@link MagicService}). The service is implemented with 3-layer architecture (entity, * dao, service). For persistence the example uses in-memory H2 database which is populated on each * application startup. */ @Slf4j public class App { public static final String BOOK_OF_IDORES = "Book of Idores"; /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // populate the in-memory database initData(); // query the data using the service queryData(); } /** * Initialize data. */ public static void initData() { // spells var spell1 = new Spell("Ice dart"); var spell2 = new Spell("Invisibility"); var spell3 = new Spell("Stun bolt"); var spell4 = new Spell("Confusion"); var spell5 = new Spell("Darkness"); var spell6 = new Spell("Fireball"); var spell7 = new Spell("Enchant weapon"); var spell8 = new Spell("Rock armour"); var spell9 = new Spell("Light"); var spell10 = new Spell("Bee swarm"); var spell11 = new Spell("Haste"); var spell12 = new Spell("Levitation"); var spell13 = new Spell("Magic lock"); var spell14 = new Spell("Summon hell bat"); var spell15 = new Spell("Water walking"); var spell16 = new Spell("Magic storm"); var spell17 = new Spell("Entangle"); var spellDao = new SpellDaoImpl(); spellDao.persist(spell1); spellDao.persist(spell2); spellDao.persist(spell3); spellDao.persist(spell4); spellDao.persist(spell5); spellDao.persist(spell6); spellDao.persist(spell7); spellDao.persist(spell8); spellDao.persist(spell9); spellDao.persist(spell10); spellDao.persist(spell11); spellDao.persist(spell12); spellDao.persist(spell13); spellDao.persist(spell14); spellDao.persist(spell15); spellDao.persist(spell16); spellDao.persist(spell17); // spellbooks var spellbookDao = new SpellbookDaoImpl(); var spellbook1 = new Spellbook("Book of Orgymon"); spellbookDao.persist(spellbook1); spellbook1.addSpell(spell1); spellbook1.addSpell(spell2); spellbook1.addSpell(spell3); spellbook1.addSpell(spell4); spellbookDao.merge(spellbook1); var spellbook2 = new Spellbook("Book of Aras"); spellbookDao.persist(spellbook2); spellbook2.addSpell(spell5); spellbook2.addSpell(spell6); spellbookDao.merge(spellbook2); var spellbook3 = new Spellbook("Book of Kritior"); spellbookDao.persist(spellbook3); spellbook3.addSpell(spell7); spellbook3.addSpell(spell8); spellbook3.addSpell(spell9); spellbookDao.merge(spellbook3); var spellbook4 = new Spellbook("Book of Tamaex"); spellbookDao.persist(spellbook4); spellbook4.addSpell(spell10); spellbook4.addSpell(spell11); spellbook4.addSpell(spell12); spellbookDao.merge(spellbook4); var spellbook5 = new Spellbook(BOOK_OF_IDORES); spellbookDao.persist(spellbook5); spellbook5.addSpell(spell13); spellbookDao.merge(spellbook5); var spellbook6 = new Spellbook("Book of Opaen"); spellbookDao.persist(spellbook6); spellbook6.addSpell(spell14); spellbook6.addSpell(spell15); spellbookDao.merge(spellbook6); var spellbook7 = new Spellbook("Book of Kihione"); spellbookDao.persist(spellbook7); spellbook7.addSpell(spell16); spellbook7.addSpell(spell17); spellbookDao.merge(spellbook7); // wizards var wizardDao = new WizardDaoImpl(); var wizard1 = new Wizard("Aderlard Boud"); wizardDao.persist(wizard1); wizard1.addSpellbook(spellbookDao.findByName("Book of Orgymon")); wizard1.addSpellbook(spellbookDao.findByName("Book of Aras")); wizardDao.merge(wizard1); var wizard2 = new Wizard("Anaxis Bajraktari"); wizardDao.persist(wizard2); wizard2.addSpellbook(spellbookDao.findByName("Book of Kritior")); wizard2.addSpellbook(spellbookDao.findByName("Book of Tamaex")); wizardDao.merge(wizard2); var wizard3 = new Wizard("Xuban Munoa"); wizardDao.persist(wizard3); wizard3.addSpellbook(spellbookDao.findByName(BOOK_OF_IDORES)); wizard3.addSpellbook(spellbookDao.findByName("Book of Opaen")); wizardDao.merge(wizard3); var wizard4 = new Wizard("Blasius Dehooge"); wizardDao.persist(wizard4); wizard4.addSpellbook(spellbookDao.findByName("Book of Kihione")); wizardDao.merge(wizard4); } /** * Query the data. */ public static void queryData() { var wizardDao = new WizardDaoImpl(); var spellbookDao = new SpellbookDaoImpl(); var spellDao = new SpellDaoImpl(); var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); LOGGER.info("Enumerating all wizards"); service.findAllWizards().stream().map(Wizard::getName).forEach(LOGGER::info); LOGGER.info("Enumerating all spellbooks"); service.findAllSpellbooks().stream().map(Spellbook::getName).forEach(LOGGER::info); LOGGER.info("Enumerating all spells"); service.findAllSpells().stream().map(Spell::getName).forEach(LOGGER::info); LOGGER.info("Find wizards with spellbook 'Book of Idores'"); var wizardsWithSpellbook = service.findWizardsWithSpellbook(BOOK_OF_IDORES); wizardsWithSpellbook.forEach(w -> LOGGER.info("{} has 'Book of Idores'", w.getName())); LOGGER.info("Find wizards with spell 'Fireball'"); var wizardsWithSpell = service.findWizardsWithSpell("Fireball"); wizardsWithSpell.forEach(w -> LOGGER.info("{} has 'Fireball'", w.getName())); } }
8,221
40.525253
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/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.servicelayer.hibernate; import com.iluwatar.servicelayer.spell.Spell; import com.iluwatar.servicelayer.spellbook.Spellbook; import com.iluwatar.servicelayer.wizard.Wizard; import lombok.extern.slf4j.Slf4j; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Produces the Hibernate {@link SessionFactory}. */ @Slf4j public final class HibernateUtil { /** * The cached session factory. */ private static volatile SessionFactory sessionFactory; private HibernateUtil() { } /** * Create the current session factory instance, create a new one when there is none yet. * * @return The session factory */ public static synchronized SessionFactory getSessionFactory() { if (sessionFactory == null) { try { sessionFactory = new Configuration() .addAnnotatedClass(Wizard.class) .addAnnotatedClass(Spellbook.class) .addAnnotatedClass(Spell.class) .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect") .setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1") .setProperty("hibernate.current_session_context_class", "thread") .setProperty("hibernate.show_sql", "false") .setProperty("hibernate.hbm2ddl.auto", "create-drop").buildSessionFactory(); } catch (Throwable ex) { LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } return sessionFactory; } /** * Drop the current connection, resulting in a create-drop clean database next time. This is * mainly used for JUnit testing since one test should not influence the other */ public static void dropSession() { getSessionFactory().close(); sessionFactory = null; } }
3,146
36.915663
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.magic; import com.iluwatar.servicelayer.spell.Spell; import com.iluwatar.servicelayer.spellbook.Spellbook; import com.iluwatar.servicelayer.wizard.Wizard; import java.util.List; /** * Service interface. */ public interface MagicService { List<Wizard> findAllWizards(); List<Spellbook> findAllSpellbooks(); List<Spell> findAllSpells(); List<Wizard> findWizardsWithSpellbook(String name); List<Wizard> findWizardsWithSpell(String name); }
1,775
36
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.magic; import com.iluwatar.servicelayer.spell.Spell; import com.iluwatar.servicelayer.spell.SpellDao; import com.iluwatar.servicelayer.spellbook.Spellbook; import com.iluwatar.servicelayer.spellbook.SpellbookDao; import com.iluwatar.servicelayer.wizard.Wizard; import com.iluwatar.servicelayer.wizard.WizardDao; import java.util.ArrayList; import java.util.List; /** * Service implementation. */ public class MagicServiceImpl implements MagicService { private final WizardDao wizardDao; private final SpellbookDao spellbookDao; private final SpellDao spellDao; /** * Constructor. */ public MagicServiceImpl(WizardDao wizardDao, SpellbookDao spellbookDao, SpellDao spellDao) { this.wizardDao = wizardDao; this.spellbookDao = spellbookDao; this.spellDao = spellDao; } @Override public List<Wizard> findAllWizards() { return wizardDao.findAll(); } @Override public List<Spellbook> findAllSpellbooks() { return spellbookDao.findAll(); } @Override public List<Spell> findAllSpells() { return spellDao.findAll(); } @Override public List<Wizard> findWizardsWithSpellbook(String name) { var spellbook = spellbookDao.findByName(name); return new ArrayList<>(spellbook.getWizards()); } @Override public List<Wizard> findWizardsWithSpell(String name) { var spell = spellDao.findByName(name); var spellbook = spell.getSpellbook(); return new ArrayList<>(spellbook.getWizards()); } }
2,792
33.060976
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/Spellbook.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.spellbook; import com.iluwatar.servicelayer.common.BaseEntity; import com.iluwatar.servicelayer.spell.Spell; import com.iluwatar.servicelayer.wizard.Wizard; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; /** * Spellbook entity. */ @Entity @Table(name = "SPELLBOOK") public class Spellbook extends BaseEntity { @Id @GeneratedValue @Column(name = "SPELLBOOK_ID") private Long id; private String name; @ManyToMany(mappedBy = "spellbooks", fetch = FetchType.EAGER) private Set<Wizard> wizards; @OneToMany(mappedBy = "spellbook", orphanRemoval = true, cascade = CascadeType.ALL) private Set<Spell> spells; public Spellbook() { spells = new HashSet<>(); wizards = new HashSet<>(); } public Spellbook(String name) { this(); this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Wizard> getWizards() { return wizards; } public void setWizards(Set<Wizard> wizards) { this.wizards = wizards; } public Set<Spell> getSpells() { return spells; } public void setSpells(Set<Spell> spells) { this.spells = spells; } public void addSpell(Spell spell) { spell.setSpellbook(this); spells.add(spell); } @Override public String toString() { return name; } }
3,072
25.95614
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.spellbook; import com.iluwatar.servicelayer.common.DaoBaseImpl; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.Transaction; import org.hibernate.query.Query; /** * SpellbookDao implementation. */ public class SpellbookDaoImpl extends DaoBaseImpl<Spellbook> implements SpellbookDao { @Override public Spellbook findByName(String name) { Transaction tx = null; Spellbook result; try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<Spellbook> builderQuery = criteriaBuilder.createQuery(Spellbook.class); Root<Spellbook> root = builderQuery.from(Spellbook.class); builderQuery.select(root).where(criteriaBuilder.equal(root.get("name"), name)); Query<Spellbook> query = session.createQuery(builderQuery); result = query.uniqueResult(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; } return result; } }
2,491
38.555556
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDao.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.spellbook; import com.iluwatar.servicelayer.common.Dao; /** * SpellbookDao interface. */ public interface SpellbookDao extends Dao<Spellbook> { Spellbook findByName(String name); }
1,507
39.756757
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/spell/Spell.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.spell; import com.iluwatar.servicelayer.common.BaseEntity; import com.iluwatar.servicelayer.spellbook.Spellbook; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * Spell entity. */ @Entity @Table(name = "SPELL") public class Spell extends BaseEntity { private String name; @Id @GeneratedValue @Column(name = "SPELL_ID") private Long id; @ManyToOne @JoinColumn(name = "SPELLBOOK_ID_FK", referencedColumnName = "SPELLBOOK_ID") private Spellbook spellbook; public Spell() { } public Spell(String name) { this(); this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Spellbook getSpellbook() { return spellbook; } public void setSpellbook(Spellbook spellbook) { this.spellbook = spellbook; } @Override public String toString() { return name; } }
2,511
26.304348
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.spell; import com.iluwatar.servicelayer.common.DaoBaseImpl; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.Transaction; import org.hibernate.query.Query; /** * SpellDao implementation. */ public class SpellDaoImpl extends DaoBaseImpl<Spell> implements SpellDao { @Override public Spell findByName(String name) { Transaction tx = null; Spell result; try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<Spell> builderQuery = criteriaBuilder.createQuery(Spell.class); Root<Spell> root = builderQuery.from(Spell.class); builderQuery.select(root).where(criteriaBuilder.equal(root.get("name"), name)); Query<Spell> query = session.createQuery(builderQuery); result = query.uniqueResult(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; } return result; } }
2,442
38.403226
140
java
java-design-patterns
java-design-patterns-master/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDao.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servicelayer.spell; import com.iluwatar.servicelayer.common.Dao; /** * SpellDao interface. */ public interface SpellDao extends Dao<Spell> { Spell findByName(String name); }
1,487
39.216216
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.HashMap; import org.junit.jupiter.api.Test; /** * Testing methods in Bubble class. */ class BubbleTest { @Test void moveTest() { var b = new Bubble(10, 10, 1, 2); var initialX = b.coordinateX; var initialY = b.coordinateY; b.move(); //change in x and y < |2| assertTrue(b.coordinateX - initialX < 2 && b.coordinateX - initialX > -2); assertTrue(b.coordinateY - initialY < 2 && b.coordinateY - initialY > -2); } @Test void touchesTest() { var b1 = new Bubble(0, 0, 1, 2); var b2 = new Bubble(1, 1, 2, 1); var b3 = new Bubble(10, 10, 3, 1); //b1 touches b2 but not b3 assertTrue(b1.touches(b2)); assertFalse(b1.touches(b3)); } @Test void popTest() { var b1 = new Bubble(10, 10, 1, 2); var b2 = new Bubble(0, 0, 2, 2); var bubbles = new HashMap<Integer, Bubble>(); bubbles.put(1, b1); bubbles.put(2, b2); b1.pop(bubbles); //after popping, bubble no longer in hashMap containing all bubbles assertNull(bubbles.get(1)); assertNotNull(bubbles.get(2)); } @Test void handleCollisionTest() { var b1 = new Bubble(0, 0, 1, 2); var b2 = new Bubble(1, 1, 2, 1); var b3 = new Bubble(10, 10, 3, 1); var bubbles = new HashMap<Integer, Bubble>(); bubbles.put(1, b1); bubbles.put(2, b2); bubbles.put(3, b3); var bubblesToCheck = new ArrayList<Point>(); bubblesToCheck.add(b2); bubblesToCheck.add(b3); b1.handleCollision(bubblesToCheck, bubbles); //b1 touches b2 and not b3, so b1, b2 will be popped assertNull(bubbles.get(1)); assertNull(bubbles.get(2)); assertNotNull(bubbles.get(3)); } }
3,262
33.347368
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.HashMap; import org.junit.jupiter.api.Test; /** * Testing SpatialPartition_Bubbles class. */ class SpatialPartitionBubblesTest { @Test void handleCollisionsUsingQtTest() { var b1 = new Bubble(10, 10, 1, 3); var b2 = new Bubble(5, 5, 2, 1); var b3 = new Bubble(9, 9, 3, 1); var b4 = new Bubble(8, 8, 4, 2); var bubbles = new HashMap<Integer, Bubble>(); bubbles.put(1, b1); bubbles.put(2, b2); bubbles.put(3, b3); bubbles.put(4, b4); var r = new Rect(10, 10, 20, 20); var qt = new QuadTree(r, 4); qt.insert(b1); qt.insert(b2); qt.insert(b3); qt.insert(b4); var sp = new SpatialPartitionBubbles(bubbles, qt); sp.handleCollisionsUsingQt(b1); //b1 touches b3 and b4 but not b2 - so b1,b3,b4 get popped assertNull(bubbles.get(1)); assertNotNull(bubbles.get(2)); assertNull(bubbles.get(3)); assertNull(bubbles.get(4)); } }
2,378
35.6
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.Random; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; /** * Testing QuadTree class. */ class QuadTreeTest { @Test void queryTest() { var points = new ArrayList<Point>(); var rand = new Random(); for (int i = 0; i < 20; i++) { var p = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); points.add(p); } var field = new Rect(150, 150, 300, 300); //size of field var queryRange = new Rect(70, 130, 100, 100); //result = all points lying in this rectangle //points found in the query range using quadtree and normal method is same var points1 = QuadTreeTest.quadTreeTest(points, field, queryRange); var points2 = QuadTreeTest.verify(points, queryRange); assertEquals(points1, points2); } static Hashtable<Integer, Point> quadTreeTest(Collection<Point> points, Rect field, Rect queryRange) { //creating quadtree and inserting all points var qTree = new QuadTree(queryRange, 4); points.forEach(qTree::insert); return qTree .query(field, new ArrayList<>()) .stream() .collect(Collectors.toMap(p -> p.id, p -> p, (a, b) -> b, Hashtable::new)); } static Hashtable<Integer, Point> verify(Collection<Point> points, Rect queryRange) { return points.stream() .filter(queryRange::contains) .collect(Collectors.toMap(point -> point.id, point -> point, (a, b) -> b, Hashtable::new)); } }
2,942
38.24
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Testing Rect class. */ class RectTest { @Test void containsTest() { var r = new Rect(10, 10, 20, 20); var b1 = new Bubble(2, 2, 1, 1); var b2 = new Bubble(30, 30, 2, 1); //r contains b1 and not b2 assertTrue(r.contains(b1)); assertFalse(r.contains(b2)); } @Test void intersectsTest() { var r1 = new Rect(10, 10, 20, 20); var r2 = new Rect(15, 15, 20, 20); var r3 = new Rect(50, 50, 20, 20); //r1 intersects r2 and not r3 assertTrue(r1.intersects(r2)); assertFalse(r1.intersects(r3)); } }
2,039
34.172414
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/main/java/com/iluwatar/spatialpartition/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.spatialpartition; import java.security.SecureRandom; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; /** * <p>The idea behind the <b>Spatial Partition</b> design pattern is to enable efficient location * of objects by storing them in a data structure that is organised by their positions. This is * especially useful in the gaming world, where one may need to look up all the objects within a * certain boundary, or near a certain other object, repeatedly. The data structure can be used to * store moving and static objects, though in order to keep track of the moving objects, their * positions will have to be reset each time they move. This would mean having to create a new * instance of the data structure each frame, which would use up additional memory, and so this * pattern should only be used if one does not mind trading memory for speed and the number of * objects to keep track of is large to justify the use of the extra space.</p> * <p>In our example, we use <b>{@link QuadTree} data structure</b> which divides into 4 (quad) * sub-sections when the number of objects added to it exceeds a certain number (int field * capacity). There is also a * <b>{@link Rect}</b> class to define the boundary of the quadtree. We use an abstract class * <b>{@link Point}</b> * with x and y coordinate fields and also an id field so that it can easily be put and looked up in * the hashmap. This class has abstract methods to define how the object moves (move()), when to * check for collision with any object (touches(obj)) and how to handle collision * (handleCollision(obj)), and will be extended by any object whose position has to be kept track of * in the quadtree. The <b>{@link SpatialPartitionGeneric}</b> abstract class has 2 fields - a * hashmap containing all objects (we use hashmap for faster lookups, insertion and deletion) * and a quadtree, and contains an abstract method which defines how to handle interactions between * objects using the quadtree.</p> * <p>Using the quadtree data structure will reduce the time complexity of finding the objects * within a certain range from <b>O(n^2) to O(nlogn)</b>, increasing the speed of computations * immensely in case of large number of objects, which will have a positive effect on the rendering * speed of the game.</p> */ @Slf4j public class App { private static final String BUBBLE = "Bubble "; static void noSpatialPartition(int numOfMovements, HashMap<Integer, Bubble> bubbles) { //all bubbles have to be checked for collision for all bubbles var bubblesToCheck = bubbles.values(); //will run numOfMovement times or till all bubbles have popped while (numOfMovements > 0 && !bubbles.isEmpty()) { bubbles.forEach((i, bubble) -> { // bubble moves, new position gets updated // and collisions are checked with all bubbles in bubblesToCheck bubble.move(); bubbles.replace(i, bubble); bubble.handleCollision(bubblesToCheck, bubbles); }); numOfMovements--; } //bubbles not popped bubbles.keySet().stream().map(key -> BUBBLE + key + " not popped").forEach(LOGGER::info); } static void withSpatialPartition( int height, int width, int numOfMovements, HashMap<Integer, Bubble> bubbles) { //creating quadtree var rect = new Rect(width / 2D, height / 2D, width, height); var quadTree = new QuadTree(rect, 4); //will run numOfMovement times or till all bubbles have popped while (numOfMovements > 0 && !bubbles.isEmpty()) { //quadtree updated each time bubbles.values().forEach(quadTree::insert); bubbles.forEach((i, bubble) -> { //bubble moves, new position gets updated, quadtree used to reduce computations bubble.move(); bubbles.replace(i, bubble); var sp = new SpatialPartitionBubbles(bubbles, quadTree); sp.handleCollisionsUsingQt(bubble); }); numOfMovements--; } //bubbles not popped bubbles.keySet().stream().map(key -> BUBBLE + key + " not popped").forEach(LOGGER::info); } /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var bubbles1 = new HashMap<Integer, Bubble>(); var bubbles2 = new HashMap<Integer, Bubble>(); var rand = new SecureRandom(); for (int i = 0; i < 10000; i++) { var b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); bubbles1.put(i, b); bubbles2.put(i, b); LOGGER.info(BUBBLE, i, " with radius ", b.radius, " added at (", b.coordinateX, ",", b.coordinateY + ")"); } var start1 = System.currentTimeMillis(); App.noSpatialPartition(20, bubbles1); var end1 = System.currentTimeMillis(); var start2 = System.currentTimeMillis(); App.withSpatialPartition(300, 300, 20, bubbles2); var end2 = System.currentTimeMillis(); LOGGER.info("Without spatial partition takes ", (end1 - start1), "ms"); LOGGER.info("With spatial partition takes ", (end2 - start2), "ms"); } }
6,392
46.355556
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; import java.util.Hashtable; /** * This abstract class has 2 fields, one of which is a hashtable containing all objects that * currently exist on the field and a quadtree which keeps track of locations. * * @param <T> T will be type of object (that extends Point) */ public abstract class SpatialPartitionGeneric<T> { Hashtable<Integer, T> playerPositions; QuadTree quadTree; /** * handles collisions for object obj using quadtree. * * @param obj is the object for which collisions need to be checked */ abstract void handleCollisionsUsingQt(T obj); }
1,904
38.6875
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; /** * The Rect class helps in defining the boundary of the quadtree and is also used to define the * range within which objects need to be found in our example. */ public class Rect { double coordinateX; double coordinateY; double width; double height; //(x,y) - centre of rectangle Rect(double x, double y, double width, double height) { this.coordinateX = x; this.coordinateY = y; this.width = width; this.height = height; } boolean contains(Point p) { return p.coordinateX >= this.coordinateX - this.width / 2 && p.coordinateX <= this.coordinateX + this.width / 2 && p.coordinateY >= this.coordinateY - this.height / 2 && p.coordinateY <= this.coordinateY + this.height / 2; } boolean intersects(Rect other) { return !(this.coordinateX + this.width / 2 <= other.coordinateX - other.width / 2 || this.coordinateX - this.width / 2 >= other.coordinateX + other.width / 2 || this.coordinateY + this.height / 2 <= other.coordinateY - other.height / 2 || this.coordinateY - this.height / 2 >= other.coordinateY + other.height / 2); } }
2,460
38.693548
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; import java.security.SecureRandom; import java.util.Collection; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; /** * Bubble class extends Point. In this example, we create several bubbles in the field, let them * move and keep track of which ones have popped and which ones remain. */ @Slf4j public class Bubble extends Point<Bubble> { private static final SecureRandom RANDOM = new SecureRandom(); final int radius; Bubble(int x, int y, int id, int radius) { super(x, y, id); this.radius = radius; } void move() { //moves by 1 unit in either direction this.coordinateX += RANDOM.nextInt(3) - 1; this.coordinateY += RANDOM.nextInt(3) - 1; } boolean touches(Bubble b) { //distance between them is greater than sum of radii (both sides of equation squared) return (this.coordinateX - b.coordinateX) * (this.coordinateX - b.coordinateX) + (this.coordinateY - b.coordinateY) * (this.coordinateY - b.coordinateY) <= (this.radius + b.radius) * (this.radius + b.radius); } void pop(HashMap<Integer, Bubble> allBubbles) { LOGGER.info("Bubble ", this.id, " popped at (", this.coordinateX, ",", this.coordinateY, ")!"); allBubbles.remove(this.id); } void handleCollision(Collection<? extends Point> toCheck, HashMap<Integer, Bubble> allBubbles) { var toBePopped = false; //if any other bubble collides with it, made true for (var point : toCheck) { var otherId = point.id; if (allBubbles.get(otherId) != null //the bubble hasn't been popped yet && this.id != otherId //the two bubbles are not the same && this.touches(allBubbles.get(otherId))) { //the bubbles touch allBubbles.get(otherId).pop(allBubbles); toBePopped = true; } } if (toBePopped) { this.pop(allBubbles); } } }
3,179
37.313253
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; import java.util.Collection; import java.util.Hashtable; /** * The quadtree data structure is being used to keep track of the objects' locations. It has the * insert(Point) and query(range) methods to insert a new object and find the objects within a * certain (rectangular) range respectively. */ public class QuadTree { Rect boundary; int capacity; boolean divided; Hashtable<Integer, Point> points; QuadTree northwest; QuadTree northeast; QuadTree southwest; QuadTree southeast; QuadTree(Rect boundary, int capacity) { this.boundary = boundary; this.capacity = capacity; this.divided = false; this.points = new Hashtable<>(); this.northwest = null; this.northeast = null; this.southwest = null; this.southeast = null; } void insert(Point p) { if (this.boundary.contains(p)) { if (this.points.size() < this.capacity) { points.put(p.id, p); } else { if (!this.divided) { this.divide(); } if (this.northwest.boundary.contains(p)) { this.northwest.insert(p); } else if (this.northeast.boundary.contains(p)) { this.northeast.insert(p); } else if (this.southwest.boundary.contains(p)) { this.southwest.insert(p); } else if (this.southeast.boundary.contains(p)) { this.southeast.insert(p); } } } } void divide() { var x = this.boundary.coordinateX; var y = this.boundary.coordinateY; var width = this.boundary.width; var height = this.boundary.height; var nw = new Rect(x - width / 4, y + height / 4, width / 2, height / 2); this.northwest = new QuadTree(nw, this.capacity); var ne = new Rect(x + width / 4, y + height / 4, width / 2, height / 2); this.northeast = new QuadTree(ne, this.capacity); var sw = new Rect(x - width / 4, y - height / 4, width / 2, height / 2); this.southwest = new QuadTree(sw, this.capacity); var se = new Rect(x + width / 4, y - height / 4, width / 2, height / 2); this.southeast = new QuadTree(se, this.capacity); this.divided = true; } Collection<Point> query(Rect r, Collection<Point> relevantPoints) { //could also be a circle instead of a rectangle if (this.boundary.intersects(r)) { this.points .values() .stream() .filter(r::contains) .forEach(relevantPoints::add); if (this.divided) { this.northwest.query(r, relevantPoints); this.northeast.query(r, relevantPoints); this.southwest.query(r, relevantPoints); this.southeast.query(r, relevantPoints); } } return relevantPoints; } }
4,009
34.803571
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; import java.util.Collection; import java.util.HashMap; /** * The abstract Point class which will be extended by any object in the field whose location has to * be kept track of. Defined by x,y coordinates and an id for easy hashing into hashtable. * * @param <T> T will be type subclass */ public abstract class Point<T> { public int coordinateX; public int coordinateY; public final int id; Point(int x, int y, int id) { this.coordinateX = x; this.coordinateY = y; this.id = id; } /** * defines how the object moves. */ abstract void move(); /** * defines conditions for interacting with an object obj. * * @param obj is another object on field which also extends Point * @return whether the object can interact with the other or not */ abstract boolean touches(T obj); /** * handling interactions/collisions with other objects. * * @param toCheck contains the objects which need to be checked * @param all contains hashtable of all points on field at this time */ abstract void handleCollision(Collection<? extends Point> toCheck, HashMap<Integer, T> all); }
2,471
34.314286
140
java
java-design-patterns
java-design-patterns-master/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.spatialpartition; import java.util.ArrayList; import java.util.HashMap; /** * This class extends the generic SpatialPartition abstract class and is used in our example to keep * track of all the bubbles that collide, pop and stay un-popped. */ public class SpatialPartitionBubbles extends SpatialPartitionGeneric<Bubble> { private final HashMap<Integer, Bubble> bubbles; private final QuadTree bubblesQuadTree; SpatialPartitionBubbles(HashMap<Integer, Bubble> bubbles, QuadTree bubblesQuadTree) { this.bubbles = bubbles; this.bubblesQuadTree = bubblesQuadTree; } void handleCollisionsUsingQt(Bubble b) { // finding points within area of a square drawn with centre same as // centre of bubble and length = radius of bubble var rect = new Rect(b.coordinateX, b.coordinateY, 2D * b.radius, 2D * b.radius); var quadTreeQueryResult = new ArrayList<Point>(); this.bubblesQuadTree.query(rect, quadTreeQueryResult); //handling these collisions b.handleCollision(quadTreeQueryResult, this.bubbles); } }
2,356
41.854545
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/test/java/com/iluwatar/factorykit/app/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.factorykit.app; import com.iluwatar.factorykit.App; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application Test Entrypoint */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,641
37.186047
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit.factorykit; import static org.junit.jupiter.api.Assertions.assertTrue; import com.iluwatar.factorykit.Axe; import com.iluwatar.factorykit.Spear; import com.iluwatar.factorykit.Sword; import com.iluwatar.factorykit.Weapon; import com.iluwatar.factorykit.WeaponFactory; import com.iluwatar.factorykit.WeaponType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Test Factory Kit Pattern */ class FactoryKitTest { private WeaponFactory factory; @BeforeEach void init() { factory = WeaponFactory.factory(builder -> { builder.add(WeaponType.SPEAR, Spear::new); builder.add(WeaponType.AXE, Axe::new); builder.add(WeaponType.SWORD, Sword::new); }); } /** * Testing {@link WeaponFactory} to produce a SPEAR asserting that the Weapon is an instance of * {@link Spear} */ @Test void testSpearWeapon() { var weapon = factory.create(WeaponType.SPEAR); verifyWeapon(weapon, Spear.class); } /** * Testing {@link WeaponFactory} to produce a AXE asserting that the Weapon is an instance of * {@link Axe} */ @Test void testAxeWeapon() { var weapon = factory.create(WeaponType.AXE); verifyWeapon(weapon, Axe.class); } /** * Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of * {@link Sword} */ @Test void testWeapon() { var weapon = factory.create(WeaponType.SWORD); verifyWeapon(weapon, Sword.class); } /** * This method asserts that the weapon object that is passed is an instance of the clazz * * @param weapon weapon object which is to be verified * @param clazz expected class of the weapon */ private void verifyWeapon(Weapon weapon, Class<?> clazz) { assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); } }
3,171
32.389474
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; import java.util.function.Supplier; /** * Functional interface that allows adding builder with name to the factory. */ public interface Builder { void add(WeaponType name, Supplier<Weapon> supplier); }
1,525
42.6
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/main/java/com/iluwatar/factorykit/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.factorykit; import java.util.ArrayList; import lombok.extern.slf4j.Slf4j; /** * Factory kit is a creational pattern that defines a factory of immutable content with separated * builder and factory interfaces to deal with the problem of creating one of the objects specified * directly in the factory kit instance. * * <p>In the given example {@link WeaponFactory} represents the factory kit, that contains four * {@link Builder}s for creating new objects of the classes implementing {@link Weapon} interface. * * <p>Each of them can be called with {@link WeaponFactory#create(WeaponType)} method, with * an input representing an instance of {@link WeaponType} that needs to be mapped explicitly with * desired class type in the factory instance. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var factory = WeaponFactory.factory(builder -> { builder.add(WeaponType.SWORD, Sword::new); builder.add(WeaponType.AXE, Axe::new); builder.add(WeaponType.SPEAR, Spear::new); builder.add(WeaponType.BOW, Bow::new); }); var list = new ArrayList<Weapon>(); list.add(factory.create(WeaponType.AXE)); list.add(factory.create(WeaponType.SPEAR)); list.add(factory.create(WeaponType.SWORD)); list.add(factory.create(WeaponType.BOW)); list.forEach(weapon -> LOGGER.info("{}", weapon.toString())); } }
2,764
41.538462
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; import java.util.HashMap; import java.util.function.Consumer; import java.util.function.Supplier; /** * Functional interface, an example of the factory-kit design pattern. * <br>Instance created locally gives an opportunity to strictly define * which objects types the instance of a factory will be able to create. * <br>Factory is a placeholder for {@link Builder}s * with {@link WeaponFactory#create(WeaponType)} method to initialize new objects. */ public interface WeaponFactory { /** * Creates an instance of the given type. * * @param name representing enum of an object type to be created. * @return new instance of a requested class implementing {@link Weapon} interface. */ Weapon create(WeaponType name); /** * Creates factory - placeholder for specified {@link Builder}s. * * @param consumer for the new builder to the factory. * @return factory with specified {@link Builder}s */ static WeaponFactory factory(Consumer<Builder> consumer) { var map = new HashMap<WeaponType, Supplier<Weapon>>(); consumer.accept(map::put); return name -> map.get(name).get(); } }
2,452
39.883333
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; /** * Class representing Swords. */ public class Sword implements Weapon { @Override public String toString() { return "Sword"; } }
1,462
39.638889
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; /** * Class representing Bows. */ public class Bow implements Weapon { @Override public String toString() { return "Bow"; } }
1,456
39.472222
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; /** * Class representing Spear. */ public class Spear implements Weapon { @Override public String toString() { return "Spear"; } }
1,461
39.611111
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponType.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; /** * Enumerates {@link Weapon} types. */ public enum WeaponType { SWORD, AXE, BOW, SPEAR }
1,420
38.472222
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; /** * Class representing Axe. */ public class Axe implements Weapon { @Override public String toString() { return "Axe"; } }
1,455
39.444444
140
java
java-design-patterns
java-design-patterns-master/factory-kit/src/main/java/com/iluwatar/factorykit/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.factorykit; /** * Interface representing weapon. */ public interface Weapon { }
1,388
42.40625
140
java
java-design-patterns
java-design-patterns-master/version-number/src/test/java/com/iluwatar/versionnumber/BookRepositoryTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.versionnumber; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * Tests for {@link BookRepository} */ class BookRepositoryTest { private final long bookId = 1; private final BookRepository bookRepository = new BookRepository(); @BeforeEach void setUp() throws BookDuplicateException { var book = new Book(); book.setId(bookId); bookRepository.add(book); } @Test void testDefaultVersionRemainsZeroAfterAdd() throws BookNotFoundException { var book = bookRepository.get(bookId); assertEquals(0, book.getVersion()); } @Test void testAliceAndBobHaveDifferentVersionsAfterAliceUpdate() throws BookNotFoundException, VersionMismatchException { final var aliceBook = bookRepository.get(bookId); final var bobBook = bookRepository.get(bookId); aliceBook.setTitle("Kama Sutra"); bookRepository.update(aliceBook); assertEquals(1, aliceBook.getVersion()); assertEquals(0, bobBook.getVersion()); var actualBook = bookRepository.get(bookId); assertEquals(aliceBook.getVersion(), actualBook.getVersion()); assertEquals(aliceBook.getTitle(), actualBook.getTitle()); assertNotEquals(aliceBook.getTitle(), bobBook.getTitle()); } @Test void testShouldThrowVersionMismatchExceptionOnStaleUpdate() throws BookNotFoundException, VersionMismatchException { final var aliceBook = bookRepository.get(bookId); final var bobBook = bookRepository.get(bookId); aliceBook.setTitle("Kama Sutra"); bookRepository.update(aliceBook); bobBook.setAuthor("Vatsyayana Mallanaga"); try { bookRepository.update(bobBook); } catch (VersionMismatchException e) { assertEquals(0, bobBook.getVersion()); var actualBook = bookRepository.get(bookId); assertEquals(1, actualBook.getVersion()); assertEquals(aliceBook.getVersion(), actualBook.getVersion()); assertEquals("", bobBook.getTitle()); assertNotEquals(aliceBook.getAuthor(), bobBook.getAuthor()); } } }
3,376
36.94382
140
java
java-design-patterns
java-design-patterns-master/version-number/src/test/java/com/iluwatar/versionnumber/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.versionnumber; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} * throws an exception. */ @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,808
36.6875
140
java
java-design-patterns
java-design-patterns-master/version-number/src/main/java/com/iluwatar/versionnumber/BookNotFoundException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.versionnumber; /** * Client has tried to make an operation with book which repository does not have. */ public class BookNotFoundException extends Exception { public BookNotFoundException(String message) { super(message); } }
1,542
43.085714
140
java
java-design-patterns
java-design-patterns-master/version-number/src/main/java/com/iluwatar/versionnumber/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.versionnumber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Version Number pattern helps to resolve concurrency conflicts in applications. * Usually these conflicts arise in database operations, when multiple clients are trying * to update the same record simultaneously. * Resolving such conflicts requires determining whether an object has changed. * For this reason we need a version number that is incremented with each change * to the underlying data, e.g. database. The version number can be used by repositories * to check for external changes and to report concurrency issues to the users. * * <p>In this example we show how Alice and Bob will try to update the {@link Book} * and save it simultaneously to {@link BookRepository}, which represents a typical database. * * <p>As in real databases, each client operates with copy of the data instead of original data * passed by reference, that's why we are using {@link Book} copy-constructor here. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Program entry point. * * @param args command line args */ public static void main(String[] args) throws BookDuplicateException, BookNotFoundException, VersionMismatchException { var bookId = 1; var bookRepository = new BookRepository(); var book = new Book(); book.setId(bookId); bookRepository.add(book); // adding a book with empty title and author LOGGER.info("An empty book with version {} was added to repository", book.getVersion()); // Alice and Bob took the book concurrently final var aliceBook = bookRepository.get(bookId); final var bobBook = bookRepository.get(bookId); aliceBook.setTitle("Kama Sutra"); // Alice has updated book title bookRepository.update(aliceBook); // and successfully saved book in database LOGGER.info("Alice updates the book with new version {}", aliceBook.getVersion()); // now Bob has the stale version of the book with empty title and version = 0 // while actual book in database has filled title and version = 1 bobBook.setAuthor("Vatsyayana Mallanaga"); // Bob updates the author try { LOGGER.info("Bob tries to update the book with his version {}", bobBook.getVersion()); bookRepository.update(bobBook); // Bob tries to save his book to database } catch (VersionMismatchException e) { // Bob update fails, and book in repository remained untouchable LOGGER.info("Exception: {}", e.getMessage()); // Now Bob should reread actual book from repository, do his changes again and save again } } }
3,979
45.27907
140
java
java-design-patterns
java-design-patterns-master/version-number/src/main/java/com/iluwatar/versionnumber/BookDuplicateException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.versionnumber; /** * When someone has tried to add a book which repository already have. */ public class BookDuplicateException extends Exception { public BookDuplicateException(String message) { super(message); } }
1,532
42.8
140
java
java-design-patterns
java-design-patterns-master/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.versionnumber; import java.util.HashMap; import java.util.Map; /** * This repository represents simplified database. * As a typical database do, repository operates with copies of object. * So client and repo has different copies of book, which can lead to concurrency conflicts * as much as in real databases. */ public class BookRepository { private final Map<Long, Book> collection = new HashMap<>(); /** * Adds book to collection. * Actually we are putting copy of book (saving a book by value, not by reference); */ public void add(Book book) throws BookDuplicateException { if (collection.containsKey(book.getId())) { throw new BookDuplicateException("Duplicated book with id: " + book.getId()); } // add copy of the book collection.put(book.getId(), new Book(book)); } /** * Updates book in collection only if client has modified the latest version of the book. */ public void update(Book book) throws BookNotFoundException, VersionMismatchException { if (!collection.containsKey(book.getId())) { throw new BookNotFoundException("Not found book with id: " + book.getId()); } var latestBook = collection.get(book.getId()); if (book.getVersion() != latestBook.getVersion()) { throw new VersionMismatchException( "Tried to update stale version " + book.getVersion() + " while actual version is " + latestBook.getVersion() ); } // update version, including client representation - modify by reference here book.setVersion(book.getVersion() + 1); // save book copy to repository collection.put(book.getId(), new Book(book)); } /** * Returns book representation to the client. * Representation means we are returning copy of the book. */ public Book get(long bookId) throws BookNotFoundException { if (!collection.containsKey(bookId)) { throw new BookNotFoundException("Not found book with id: " + bookId); } // return copy of the book return new Book(collection.get(bookId)); } }
3,362
37.215909
140
java
java-design-patterns
java-design-patterns-master/version-number/src/main/java/com/iluwatar/versionnumber/VersionMismatchException.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.versionnumber; /** * Client has tried to update a stale version of the book. */ public class VersionMismatchException extends Exception { public VersionMismatchException(String message) { super(message); } }
1,524
42.571429
140
java
java-design-patterns
java-design-patterns-master/version-number/src/main/java/com/iluwatar/versionnumber/Book.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.versionnumber; /** * Model class for Book entity. */ public class Book { private long id; private String title = ""; private String author = ""; private long version = 0; // version number public Book() { } /** * We need this copy constructor to copy book representation in {@link BookRepository}. */ public Book(Book book) { this.id = book.id; this.title = book.title; this.author = book.author; this.version = book.version; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } }
2,254
26.168675
140
java
java-design-patterns
java-design-patterns-master/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * test to check choreography saga */ class SagaChoreographyTest { @Test void executeTest() { var sd = serviceDiscovery(); var service = sd.findAny(); var badOrderSaga = service.execute(newSaga("bad_order")); var goodOrderSaga = service.execute(newSaga("good_order")); assertEquals(Saga.SagaResult.ROLLBACKED, badOrderSaga.getResult()); assertEquals(Saga.SagaResult.FINISHED, goodOrderSaga.getResult()); } private static Saga newSaga(Object value) { return Saga .create() .chapter("init an order").setInValue(value) .chapter("booking a Fly") .chapter("booking a Hotel") .chapter("withdrawing Money"); } private static ServiceDiscoveryService serviceDiscovery() { var sd = new ServiceDiscoveryService(); return sd .discover(new OrderService(sd)) .discover(new FlyBookingService(sd)) .discover(new HotelBookingService(sd)) .discover(new WithdrawMoneyService(sd)); } }
2,420
36.246154
140
java
java-design-patterns
java-design-patterns-master/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import com.iluwatar.saga.orchestration.SagaApplication; import org.junit.jupiter.api.Test; /*** * empty test */ class SagaApplicationTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> SagaApplication.main(new String[]{})); } }
1,659
39.487805
140
java
java-design-patterns
java-design-patterns-master/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * test to check general logic */ class SagaOrchestratorTest { @Test void execute() { SagaOrchestrator sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); Saga.Result badOrder = sagaOrchestrator.execute("bad_order"); Saga.Result crashedOrder = sagaOrchestrator.execute("crashed_order"); assertEquals(Saga.Result.ROLLBACK, badOrder); assertEquals(Saga.Result.CRASHED, crashedOrder); } private static Saga newSaga() { return Saga .create() .chapter("init an order") .chapter("booking a Fly") .chapter("booking a Hotel") .chapter("withdrawing Money"); } private static ServiceDiscoveryService serviceDiscovery() { return new ServiceDiscoveryService() .discover(new OrderService()) .discover(new FlyBookingService()) .discover(new HotelBookingService()) .discover(new WithdrawMoneyService()); } }
2,383
36.84127
140
java
java-design-patterns
java-design-patterns-master/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; import org.junit.jupiter.api.Test; import static com.iluwatar.saga.orchestration.Saga.Result; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; /** * test to test orchestration logic */ class SagaOrchestratorInternallyTest { private final List<String> records = new ArrayList<>(); @Test void executeTest() { var sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); var result = sagaOrchestrator.execute(1); assertEquals(Result.ROLLBACK, result); assertArrayEquals( new String[]{"+1", "+2", "+3", "+4", "-4", "-3", "-2", "-1"}, records.toArray(new String[]{})); } private static Saga newSaga() { return Saga.create() .chapter("1") .chapter("2") .chapter("3") .chapter("4"); } private ServiceDiscoveryService serviceDiscovery() { return new ServiceDiscoveryService() .discover(new Service1()) .discover(new Service2()) .discover(new Service3()) .discover(new Service4()); } class Service1 extends Service<Integer> { @Override public String getName() { return "1"; } @Override public ChapterResult<Integer> process(Integer value) { records.add("+1"); return ChapterResult.success(value); } @Override public ChapterResult<Integer> rollback(Integer value) { records.add("-1"); return ChapterResult.success(value); } } class Service2 extends Service<Integer> { @Override public String getName() { return "2"; } @Override public ChapterResult<Integer> process(Integer value) { records.add("+2"); return ChapterResult.success(value); } @Override public ChapterResult<Integer> rollback(Integer value) { records.add("-2"); return ChapterResult.success(value); } } class Service3 extends Service<Integer> { @Override public String getName() { return "3"; } @Override public ChapterResult<Integer> process(Integer value) { records.add("+3"); return ChapterResult.success(value); } @Override public ChapterResult<Integer> rollback(Integer value) { records.add("-3"); return ChapterResult.success(value); } } class Service4 extends Service<Integer> { @Override public String getName() { return "4"; } @Override public ChapterResult<Integer> process(Integer value) { records.add("+4"); return ChapterResult.failure(value); } @Override public ChapterResult<Integer> rollback(Integer value) { records.add("-4"); return ChapterResult.success(value); } } }
4,143
27
140
java
java-design-patterns
java-design-patterns-master/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * Test if the application starts without throwing an exception. */ class SagaApplicationTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> SagaApplication.main(new String[]{})); } }
1,666
39.658537
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; import lombok.extern.slf4j.Slf4j; /** * This pattern is used in distributed services to perform a group of operations atomically. This is * an analog of transaction in a database but in terms of microservices architecture this is * executed in a distributed environment * * <p>A saga is a sequence of local transactions in a certain context. * If one transaction fails for some reason, the saga executes compensating transactions(rollbacks) * to undo the impact of the preceding transactions. * * <p>In this approach, there are no mediators or orchestrators services. * All chapters are handled and moved by services manually. * * <p>The major difference with choreography saga is an ability to handle crashed services * (otherwise in choreography services very hard to prevent a saga if one of them has been crashed) * * @see com.iluwatar.saga.choreography.Saga * @see Service */ @Slf4j public class SagaApplication { /** * main method. */ public static void main(String[] args) { var sd = serviceDiscovery(); var service = sd.findAny(); var goodOrderSaga = service.execute(newSaga("good_order")); var badOrderSaga = service.execute(newSaga("bad_order")); LOGGER.info("orders: goodOrder is {}, badOrder is {}", goodOrderSaga.getResult(), badOrderSaga.getResult()); } private static Saga newSaga(Object value) { return Saga .create() .chapter("init an order").setInValue(value) .chapter("booking a Fly") .chapter("booking a Hotel") .chapter("withdrawing Money"); } private static ServiceDiscoveryService serviceDiscovery() { var sd = new ServiceDiscoveryService(); return sd .discover(new OrderService(sd)) .discover(new FlyBookingService(sd)) .discover(new HotelBookingService(sd)) .discover(new WithdrawMoneyService(sd)); } }
3,208
38.134146
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/choreography/ServiceDiscoveryService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; /** * The class representing a service discovery pattern. */ public class ServiceDiscoveryService { private final Map<String, ChoreographyChapter> services; /** * find any service. * * @return any service * @throws NoSuchElementException if no elements further */ public ChoreographyChapter findAny() { return services.values().iterator().next(); } public Optional<ChoreographyChapter> find(String service) { return Optional.ofNullable(services.getOrDefault(service, null)); } public ServiceDiscoveryService discover(ChoreographyChapter chapterService) { services.put(chapterService.getName(), chapterService); return this; } public ServiceDiscoveryService() { this.services = new HashMap<>(); } }
2,203
33.984127
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/choreography/Service.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Common abstraction class representing services. implementing a general contract @see {@link * ChoreographyChapter} */ public abstract class Service implements ChoreographyChapter { protected static final Logger LOGGER = LoggerFactory.getLogger(Service.class); private final ServiceDiscoveryService sd; public Service(ServiceDiscoveryService service) { this.sd = service; } @Override public Saga execute(Saga saga) { var nextSaga = saga; Object nextVal; var chapterName = saga.getCurrent().getName(); if (chapterName.equals(getName())) { if (saga.isForward()) { nextSaga = process(saga); nextVal = nextSaga.getCurrentValue(); if (nextSaga.isCurrentSuccess()) { nextSaga.forward(); } else { nextSaga.back(); } } else { nextSaga = rollback(saga); nextVal = nextSaga.getCurrentValue(); nextSaga.back(); } if (isSagaFinished(nextSaga)) { return nextSaga; } nextSaga.setCurrentValue(nextVal); } var finalNextSaga = nextSaga; return sd.find(chapterName).map(ch -> ch.execute(finalNextSaga)) .orElseThrow(serviceNotFoundException(chapterName)); } private Supplier<RuntimeException> serviceNotFoundException(String chServiceName) { return () -> new RuntimeException( String.format("the service %s has not been found", chServiceName)); } @Override public Saga process(Saga saga) { var inValue = saga.getCurrentValue(); LOGGER.info("The chapter '{}' has been started. " + "The data {} has been stored or calculated successfully", getName(), inValue); saga.setCurrentStatus(Saga.ChapterResult.SUCCESS); saga.setCurrentValue(inValue); return saga; } @Override public Saga rollback(Saga saga) { var inValue = saga.getCurrentValue(); LOGGER.info("The Rollback for a chapter '{}' has been started. " + "The data {} has been rollbacked successfully", getName(), inValue); saga.setCurrentStatus(Saga.ChapterResult.ROLLBACK); saga.setCurrentValue(inValue); return saga; } private boolean isSagaFinished(Saga saga) { if (!saga.isPresent()) { saga.setFinished(true); LOGGER.info(" the saga has been finished with {} status", saga.getResult()); return true; } return false; } }
3,821
32.234783
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/choreography/FlyBookingService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; /** * Class representing a service to book a fly. */ public class FlyBookingService extends Service { public FlyBookingService(ServiceDiscoveryService service) { super(service); } @Override public String getName() { return "booking a Fly"; } }
1,591
37.829268
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; /** * Class representing a service to withdraw a money. */ public class WithdrawMoneyService extends Service { public WithdrawMoneyService(ServiceDiscoveryService service) { super(service); } @Override public String getName() { return "withdrawing Money"; } @Override public Saga process(Saga saga) { var inValue = saga.getCurrentValue(); if (inValue.equals("bad_order")) { LOGGER.info("The chapter '{}' has been started. But the exception has been raised." + "The rollback is about to start", getName(), inValue); saga.setCurrentStatus(Saga.ChapterResult.ROLLBACK); return saga; } return super.process(saga); } }
2,027
35.872727
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/choreography/OrderService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; /** * Class representing a service to init a new order. */ public class OrderService extends Service { public OrderService(ServiceDiscoveryService service) { super(service); } @Override public String getName() { return "init an order"; } }
1,588
36.833333
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/choreography/HotelBookingService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; /** * Class representing a service to book a hotel. */ public class HotelBookingService extends Service { public HotelBookingService(ServiceDiscoveryService service) { super(service); } @Override public String getName() { return "booking a Hotel"; } }
1,601
36.255814
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/choreography/ChoreographyChapter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; /** * ChoreographyChapter is an interface representing a contract for an external service. In that * case, a service needs to make a decision what to do further hence the server needs to get all * context representing {@link Saga} */ public interface ChoreographyChapter { /** * In that case, every method is responsible to make a decision on what to do then. * * @param saga incoming saga * @return saga result */ Saga execute(Saga saga); /** * get name method. * * @return service name. */ String getName(); /** * The operation executed in general case. * * @param saga incoming saga * @return result {@link Saga} */ Saga process(Saga saga); /** * The operation executed in rollback case. * * @param saga incoming saga * @return result {@link Saga} */ Saga rollback(Saga saga); }
2,191
31.235294
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Saga representation. Saga consists of chapters. Every ChoreographyChapter is executed a certain * service. */ public class Saga { private final List<Chapter> chapters; private int pos; private boolean forward; private boolean finished; public static Saga create() { return new Saga(); } /** * get resuzlt of saga. * * @return result of saga @see {@link SagaResult} */ public SagaResult getResult() { if (finished) { return forward ? SagaResult.FINISHED : SagaResult.ROLLBACKED; } return SagaResult.PROGRESS; } /** * add chapter to saga. * * @param name chapter name * @return this */ public Saga chapter(String name) { this.chapters.add(new Chapter(name)); return this; } /** * set value to last chapter. * * @param value invalue * @return this */ public Saga setInValue(Object value) { if (chapters.isEmpty()) { return this; } chapters.get(chapters.size() - 1).setInValue(value); return this; } /** * get value from current chapter. * * @return value */ public Object getCurrentValue() { return chapters.get(pos).getInValue(); } /** * set value to current chapter. * * @param value to set */ public void setCurrentValue(Object value) { chapters.get(pos).setInValue(value); } /** * set status for current chapter. * * @param result to set */ public void setCurrentStatus(ChapterResult result) { chapters.get(pos).setResult(result); } void setFinished(boolean finished) { this.finished = finished; } boolean isForward() { return forward; } int forward() { return ++pos; } int back() { this.forward = false; return --pos; } private Saga() { this.chapters = new ArrayList<>(); this.pos = 0; this.forward = true; this.finished = false; } Chapter getCurrent() { return chapters.get(pos); } boolean isPresent() { return pos >= 0 && pos < chapters.size(); } boolean isCurrentSuccess() { return chapters.get(pos).isSuccess(); } /** * Class presents a chapter status and incoming parameters(incoming parameter transforms to * outcoming parameter). */ public static class Chapter { private final String name; private ChapterResult result; private Object inValue; public Chapter(String name) { this.name = name; this.result = ChapterResult.INIT; } public Object getInValue() { return inValue; } public void setInValue(Object object) { this.inValue = object; } public String getName() { return name; } /** * set result. * * @param result {@link ChapterResult} */ public void setResult(ChapterResult result) { this.result = result; } /** * the result for chapter is good. * * @return true if is good otherwise bad */ public boolean isSuccess() { return result == ChapterResult.SUCCESS; } } /** * result for chapter. */ public enum ChapterResult { INIT, SUCCESS, ROLLBACK } /** * result for saga. */ public enum SagaResult { PROGRESS, FINISHED, ROLLBACKED } @Override public String toString() { return "Saga{" + "chapters=" + Arrays.toString(chapters.toArray()) + ", pos=" + pos + ", forward=" + forward + '}'; } }
4,897
20.768889
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/OrchestrationChapter.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; /** * ChoreographyChapter is an interface representing a contract for an external service. * * @param <K> is type for passing params */ public interface OrchestrationChapter<K> { /** * method get name. * * @return service name. */ String getName(); /** * The operation executed in general case. * * @param value incoming value * @return result {@link ChapterResult} */ ChapterResult<K> process(K value); /** * The operation executed in rollback case. * * @param value incoming value * @return result {@link ChapterResult} */ ChapterResult<K> rollback(K value); }
1,951
32.655172
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; import lombok.extern.slf4j.Slf4j; /** * This pattern is used in distributed services to perform a group of operations atomically. This is * an analog of transaction in a database but in terms of microservices architecture this is * executed in a distributed environment * * <p>A saga is a sequence of local transactions in a certain context. * If one transaction fails for some reason, the saga executes compensating transactions(rollbacks) * to undo the impact of the preceding transactions. * * <p>In this approach, there is an orchestrator @see {@link SagaOrchestrator} * that manages all the transactions and directs the participant services to execute local * transactions based on events. The major difference with choreography saga is an ability to handle * crashed services (otherwise in choreography services very hard to prevent a saga if one of them * has been crashed) * * @see Saga * @see SagaOrchestrator * @see Service */ @Slf4j public class SagaApplication { /** * method to show common saga logic. */ public static void main(String[] args) { var sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); Saga.Result goodOrder = sagaOrchestrator.execute("good_order"); Saga.Result badOrder = sagaOrchestrator.execute("bad_order"); Saga.Result crashedOrder = sagaOrchestrator.execute("crashed_order"); LOGGER.info("orders: goodOrder is {}, badOrder is {},crashedOrder is {}", goodOrder, badOrder, crashedOrder); } private static Saga newSaga() { return Saga .create() .chapter("init an order") .chapter("booking a Fly") .chapter("booking a Hotel") .chapter("withdrawing Money"); } private static ServiceDiscoveryService serviceDiscovery() { return new ServiceDiscoveryService() .discover(new OrderService()) .discover(new FlyBookingService()) .discover(new HotelBookingService()) .discover(new WithdrawMoneyService()); } }
3,331
39.144578
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/ServiceDiscoveryService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * The class representing a service discovery pattern. */ public class ServiceDiscoveryService { private final Map<String, OrchestrationChapter<?>> services; public Optional<OrchestrationChapter> find(String service) { return Optional.ofNullable(services.getOrDefault(service, null)); } public ServiceDiscoveryService discover(OrchestrationChapter<?> orchestrationChapterService) { services.put(orchestrationChapterService.getName(), orchestrationChapterService); return this; } public ServiceDiscoveryService() { this.services = new HashMap<>(); } }
1,993
37.346154
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Common abstraction class representing services. implementing a general contract @see {@link * OrchestrationChapter} * * @param <K> type of incoming param */ public abstract class Service<K> implements OrchestrationChapter<K> { protected static final Logger LOGGER = LoggerFactory.getLogger(Service.class); @Override public abstract String getName(); @Override public ChapterResult<K> process(K value) { LOGGER.info("The chapter '{}' has been started. " + "The data {} has been stored or calculated successfully", getName(), value); return ChapterResult.success(value); } @Override public ChapterResult<K> rollback(K value) { LOGGER.info("The Rollback for a chapter '{}' has been started. " + "The data {} has been rollbacked successfully", getName(), value); return ChapterResult.success(value); } }
2,275
36.311475
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/FlyBookingService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; /** * Class representing a service to book a fly. */ public class FlyBookingService extends Service<String> { @Override public String getName() { return "booking a Fly"; } }
1,512
41.027778
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/WithdrawMoneyService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; /** * Class representing a service to withdraw a money. */ public class WithdrawMoneyService extends Service<String> { @Override public String getName() { return "withdrawing Money"; } @Override public ChapterResult<String> process(String value) { if (value.equals("bad_order") || value.equals("crashed_order")) { LOGGER.info("The chapter '{}' has been started. But the exception has been raised." + "The rollback is about to start", getName(), value); return ChapterResult.failure(value); } return super.process(value); } }
1,918
39.829787
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; import static com.iluwatar.saga.orchestration.Saga.Result; import static com.iluwatar.saga.orchestration.Saga.Result.CRASHED; import static com.iluwatar.saga.orchestration.Saga.Result.FINISHED; import static com.iluwatar.saga.orchestration.Saga.Result.ROLLBACK; import lombok.extern.slf4j.Slf4j; /** * The orchestrator that manages all the transactions and directs the participant services to * execute local transactions based on events. */ @Slf4j public class SagaOrchestrator { private final Saga saga; private final ServiceDiscoveryService sd; private final CurrentState state; /** * Create a new service to orchetrate sagas. * * @param saga saga to process * @param sd service discovery @see {@link ServiceDiscoveryService} */ public SagaOrchestrator(Saga saga, ServiceDiscoveryService sd) { this.saga = saga; this.sd = sd; this.state = new CurrentState(); } /** * pipeline to execute saga process/story. * * @param value incoming value * @param <K> type for incoming value * @return result @see {@link Result} */ @SuppressWarnings("unchecked") public <K> Result execute(K value) { state.cleanUp(); LOGGER.info(" The new saga is about to start"); var result = FINISHED; K tempVal = value; while (true) { var next = state.current(); var ch = saga.get(next); var srvOpt = sd.find(ch.name); if (srvOpt.isEmpty()) { state.directionToBack(); state.back(); continue; } var srv = srvOpt.get(); if (state.isForward()) { var processRes = srv.process(tempVal); if (processRes.isSuccess()) { next = state.forward(); tempVal = (K) processRes.getValue(); } else { state.directionToBack(); } } else { var rlRes = srv.rollback(tempVal); if (rlRes.isSuccess()) { next = state.back(); tempVal = (K) rlRes.getValue(); } else { result = CRASHED; next = state.back(); } } if (!saga.isPresent(next)) { return state.isForward() ? FINISHED : result == CRASHED ? CRASHED : ROLLBACK; } } } private static class CurrentState { int currentNumber; boolean isForward; void cleanUp() { currentNumber = 0; isForward = true; } CurrentState() { this.currentNumber = 0; this.isForward = true; } boolean isForward() { return isForward; } void directionToBack() { isForward = false; } int forward() { return ++currentNumber; } int back() { return --currentNumber; } int current() { return currentNumber; } } }
4,079
26.2
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/OrderService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; /** * Class representing a service to init a new order. */ public class OrderService extends Service<String> { @Override public String getName() { return "init an order"; } }
1,513
41.055556
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/ChapterResult.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; /** * Executing result for chapter. * * @param <K> incoming value */ public class ChapterResult<K> { private final K value; private final State state; public K getValue() { return value; } ChapterResult(K value, State state) { this.value = value; this.state = state; } public boolean isSuccess() { return state == State.SUCCESS; } public static <K> ChapterResult<K> success(K val) { return new ChapterResult<>(val, State.SUCCESS); } public static <K> ChapterResult<K> failure(K val) { return new ChapterResult<>(val, State.FAILURE); } /** * state for chapter. */ public enum State { SUCCESS, FAILURE } }
2,004
30.328125
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/HotelBookingService.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; /** * Class representing a service to book a hotel. */ public class HotelBookingService extends Service<String> { @Override public String getName() { return "booking a Hotel"; } @Override public ChapterResult<String> rollback(String value) { if (value.equals("crashed_order")) { LOGGER.info("The Rollback for a chapter '{}' has been started. " + "The data {} has been failed.The saga has been crashed.", getName(), value); return ChapterResult.failure(value); } LOGGER.info("The Rollback for a chapter '{}' has been started. " + "The data {} has been rollbacked successfully", getName(), value); return super.rollback(value); } }
2,051
37
140
java
java-design-patterns
java-design-patterns-master/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.orchestration; import java.util.ArrayList; import java.util.List; /** * Saga representation. Saga consists of chapters. Every ChoreographyChapter is executed by a * certain service. */ public class Saga { private final List<Chapter> chapters; private Saga() { this.chapters = new ArrayList<>(); } public Saga chapter(String name) { this.chapters.add(new Chapter(name)); return this; } public Chapter get(int idx) { return chapters.get(idx); } public boolean isPresent(int idx) { return idx >= 0 && idx < chapters.size(); } public static Saga create() { return new Saga(); } /** * result for saga. */ public enum Result { FINISHED, ROLLBACK, CRASHED } /** * class represents chapter name. */ public static class Chapter { String name; public Chapter(String name) { this.name = name; } public String getName() { return name; } } }
2,264
25.647059
140
java
java-design-patterns
java-design-patterns-master/update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.updatemethod; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class SkeletonTest { private static Skeleton skeleton; @BeforeAll public static void setup() { skeleton = new Skeleton(1); } @AfterAll public static void tearDown() { skeleton = null; } @Test void testUpdateForPatrollingLeft() { skeleton.patrollingLeft = true; skeleton.setPosition(50); skeleton.update(); assertEquals(49, skeleton.getPosition()); } @Test void testUpdateForPatrollingRight() { skeleton.patrollingLeft = false; skeleton.setPosition(50); skeleton.update(); assertEquals(51, skeleton.getPosition()); } @Test void testUpdateForReverseDirectionFromLeftToRight() { skeleton.patrollingLeft = true; skeleton.setPosition(1); skeleton.update(); assertEquals(0, skeleton.getPosition()); assertFalse(skeleton.patrollingLeft); } @Test void testUpdateForReverseDirectionFromRightToLeft() { skeleton.patrollingLeft = false; skeleton.setPosition(99); skeleton.update(); assertEquals(100, skeleton.getPosition()); assertTrue(skeleton.patrollingLeft); } }
2,696
31.493976
140
java
java-design-patterns
java-design-patterns-master/update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.updatemethod; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class WorldTest { private static World world; @BeforeAll public static void setup() { world = new World(); } @AfterAll public static void tearDown() { world = null; } @Test void testRun() { world.run(); assertTrue(world.isRunning); } @Test void testStop() { world.stop(); assertFalse(world.isRunning); } @Test void testAddEntity() { var entity = new Skeleton(1); world.addEntity(entity); assertEquals(entity, world.entities.get(0)); } }
2,127
30.294118
140
java
java-design-patterns
java-design-patterns-master/update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.updatemethod; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class StatueTest { private static Statue statue; @BeforeAll public static void setup() { statue = new Statue(1, 20); } @AfterAll public static void tearDown() { statue = null; } @Test void testUpdateForPendingShoot() { statue.frames = 10; statue.update(); assertEquals(11, statue.frames); } @Test void testUpdateForShooting() { statue.frames = 19; statue.update(); assertEquals(0, statue.frames); } }
1,961
31.163934
140
java
java-design-patterns
java-design-patterns-master/update-method/src/test/java/com/iluwatar/updatemethod/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.updatemethod; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,563
40.157895
140
java
java-design-patterns
java-design-patterns-master/update-method/src/main/java/com/iluwatar/updatemethod/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.updatemethod; import lombok.extern.slf4j.Slf4j; /** * This pattern simulate a collection of independent objects by telling each to * process one frame of behavior at a time. The game world maintains a collection * of objects. Each object implements an update method that simulates one frame of * the object’s behavior. Each frame, the game updates every object in the collection. */ @Slf4j public class App { private static final int GAME_RUNNING_TIME = 2000; /** * Program entry point. * @param args runtime arguments */ public static void main(String[] args) { try { var world = new World(); var skeleton1 = new Skeleton(1, 10); var skeleton2 = new Skeleton(2, 70); var statue = new Statue(3, 20); world.addEntity(skeleton1); world.addEntity(skeleton2); world.addEntity(statue); world.run(); Thread.sleep(GAME_RUNNING_TIME); world.stop(); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } } }
2,321
37.065574
140
java
java-design-patterns
java-design-patterns-master/update-method/src/main/java/com/iluwatar/updatemethod/Skeleton.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.updatemethod; /** * Skeletons are always patrolling on the game map. Initially all the skeletons * patrolling to the right, and after them reach the bounding, it will start * patrolling to the left. For each frame, one skeleton will move 1 position * step. */ public class Skeleton extends Entity { private static final int PATROLLING_LEFT_BOUNDING = 0; private static final int PATROLLING_RIGHT_BOUNDING = 100; protected boolean patrollingLeft; /** * Constructor of Skeleton. * * @param id id of skeleton */ public Skeleton(int id) { super(id); patrollingLeft = false; } /** * Constructor of Skeleton. * * @param id id of skeleton * @param position position of skeleton */ public Skeleton(int id, int position) { super(id); this.position = position; patrollingLeft = false; } @Override public void update() { if (patrollingLeft) { position -= 1; if (position == PATROLLING_LEFT_BOUNDING) { patrollingLeft = false; } } else { position += 1; if (position == PATROLLING_RIGHT_BOUNDING) { patrollingLeft = true; } } logger.info("Skeleton {} is on position {}.", id, position); } }
2,535
30.7
140
java
java-design-patterns
java-design-patterns-master/update-method/src/main/java/com/iluwatar/updatemethod/Statue.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.updatemethod; /** * Statues shoot lightning at regular intervals. */ public class Statue extends Entity { protected int frames; protected int delay; /** * Constructor of Statue. * * @param id id of statue */ public Statue(int id) { super(id); this.frames = 0; this.delay = 0; } /** * Constructor of Statue. * * @param id id of statue * @param delay the number of frames between two lightning */ public Statue(int id, int delay) { super(id); this.frames = 0; this.delay = delay; } @Override public void update() { if (++frames == delay) { shootLightning(); frames = 0; } } private void shootLightning() { logger.info("Statue " + id + " shoots lightning!"); } }
2,075
28.239437
140
java
java-design-patterns
java-design-patterns-master/update-method/src/main/java/com/iluwatar/updatemethod/World.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.updatemethod; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; import java.util.Random; import lombok.extern.slf4j.Slf4j; /** * The game world class. Maintain all the objects existed in the game frames. */ @Slf4j public class World { protected List<Entity> entities; protected volatile boolean isRunning; public World() { entities = new ArrayList<>(); isRunning = false; } /** * Main game loop. This loop will always run until the game is over. For * each loop it will process user input, update internal status, and render * the next frames. For more detail please refer to the game-loop pattern. */ private void gameLoop() { while (isRunning) { processInput(); update(); render(); } } /** * Handle any user input that has happened since the last call. In order to * simulate the situation in real-life game, here we add a random time lag. * The time lag ranges from 50 ms to 250 ms. */ private void processInput() { try { int lag = new SecureRandom().nextInt(200) + 50; Thread.sleep(lag); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); Thread.currentThread().interrupt(); } } /** * Update internal status. The update method pattern invoke udpate method for * each entity in the game. */ private void update() { for (var entity : entities) { entity.update(); } } /** * Render the next frame. Here we do nothing since it is not related to the * pattern. */ private void render() { // Does Nothing } /** * Run game loop. */ public void run() { LOGGER.info("Start game."); isRunning = true; var thread = new Thread(this::gameLoop); thread.start(); } /** * Stop game loop. */ public void stop() { LOGGER.info("Stop game."); isRunning = false; } public void addEntity(Entity entity) { entities.add(entity); } }
3,300
27.213675
140
java
java-design-patterns
java-design-patterns-master/update-method/src/main/java/com/iluwatar/updatemethod/Entity.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.updatemethod; import lombok.Getter; import lombok.Setter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract class for all the entity types. */ public abstract class Entity { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected int id; @Getter @Setter protected int position; public Entity(int id) { this.id = id; this.position = 0; } public abstract void update(); }
1,759
32.207547
140
java
java-design-patterns
java-design-patterns-master/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java
package com.iluwatar.client.session; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ServerTest { @Test void checkGetSession() { Server server = new Server("localhost", 8080); Session session = server.getSession("Session"); assertEquals("Session", session.getClientName()); } }
353
22.6
60
java
java-design-patterns
java-design-patterns-master/client-session/src/test/java/com/iluwatar/client/session/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.client.session; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; class AppTest { @Test void appStartsWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,551
38.794872
140
java
java-design-patterns
java-design-patterns-master/client-session/src/main/java/com/iluwatar/client/session/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.client.session; /** * The Client-Session pattern allows the session data to be stored on the client side and send this * data to the server with each request. * * <p> In this example, The {@link Server} class represents the server that would process the * incoming {@link Request} and also assign {@link Session} to a client. Here one instance of Server * is created. The we create two sessions for two different clients. These sessions are then passed * on to the server in the request along with the data. The server is then able to interpret the * client based on the session associated with it. * </p> */ public class App { /** * Program entry point. * * @param args Command line args */ public static void main(String[] args) { var server = new Server("localhost", 8080); var session1 = server.getSession("Session1"); var session2 = server.getSession("Session2"); var request1 = new Request("Data1", session1); var request2 = new Request("Data2", session2); server.process(request1); server.process(request2); } }
2,383
41.571429
140
java
java-design-patterns
java-design-patterns-master/client-session/src/main/java/com/iluwatar/client/session/Request.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.client.session; import lombok.AllArgsConstructor; import lombok.Data; /** * The Request class which contains the Session details and data. */ @Data @AllArgsConstructor public class Request { private String data; private Session session; }
1,556
35.209302
140
java
java-design-patterns
java-design-patterns-master/client-session/src/main/java/com/iluwatar/client/session/Session.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.client.session; import lombok.AllArgsConstructor; import lombok.Data; /** * The Session class. Each client get assigned a Session which is then used for further communications. */ @Data @AllArgsConstructor public class Session { /** * Session id. */ private String id; /** * Client name. */ private String clientName; }
1,653
32.755102
140
java
java-design-patterns
java-design-patterns-master/client-session/src/main/java/com/iluwatar/client/session/Server.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.client.session; import java.util.UUID; import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.slf4j.Slf4j; /** * The Server class. The client communicates with the server and request processing and getting a new session. */ @Slf4j @Data @AllArgsConstructor public class Server { private String host; private int port; /** * Creates a new session. * * @param name name of the client * * @return Session Object */ public Session getSession(String name) { return new Session(UUID.randomUUID().toString(), name); } /** * Processes a request based on the session. * * @param request Request object with data and Session */ public void process(Request request) { LOGGER.info("Processing Request with client: " + request.getSession().getClientName() + " data: " + request.getData()); } }
2,170
31.893939
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/test/java/com/iluwatar/factory/method/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.factory.method; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that Factory Method example runs without errors. */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,620
38.536585
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory.method; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * The Factory Method is a creational design pattern which uses factory methods to deal with the * problem of creating objects without specifying the exact class of object that will be created. * This is done by creating objects via calling a factory method either specified in an interface * and implemented by child classes, or implemented in a base class and optionally overridden by * derived classes—rather than by calling a constructor. * * <p>Factory produces the object of its liking. * The weapon {@link Weapon} manufactured by the blacksmith depends on the kind of factory * implementation it is referring to. * </p> */ class FactoryMethodTest { /** * Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of * {@link OrcWeapon}. */ @Test void testOrcBlacksmithWithSpear() { var blacksmith = new OrcBlacksmith(); var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); verifyWeapon(weapon, WeaponType.SPEAR, OrcWeapon.class); } /** * Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance of * {@link OrcWeapon}. */ @Test void testOrcBlacksmithWithAxe() { var blacksmith = new OrcBlacksmith(); var weapon = blacksmith.manufactureWeapon(WeaponType.AXE); verifyWeapon(weapon, WeaponType.AXE, OrcWeapon.class); } /** * Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an instance * of {@link ElfWeapon}. */ @Test void testElfBlacksmithWithShortSword() { var blacksmith = new ElfBlacksmith(); var weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); verifyWeapon(weapon, WeaponType.SHORT_SWORD, ElfWeapon.class); } /** * Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of * {@link ElfWeapon}. */ @Test void testElfBlacksmithWithSpear() { var blacksmith = new ElfBlacksmith(); var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); verifyWeapon(weapon, WeaponType.SPEAR, ElfWeapon.class); } /** * This method asserts that the weapon object that is passed is an instance of the clazz and the * weapon is of type expectedWeaponType. * * @param weapon weapon object which is to be verified * @param expectedWeaponType expected WeaponType of the weapon * @param clazz expected class of the weapon */ private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class<?> clazz) { assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); assertEquals(expectedWeaponType, weapon .getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType); } }
4,248
39.855769
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/main/java/com/iluwatar/factory/method/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.factory.method; import lombok.extern.slf4j.Slf4j; /** * The Factory Method is a creational design pattern that uses factory methods to deal with the * problem of creating objects without specifying the exact class of object that will be created. * This is done by creating objects via calling a factory method either specified in an interface * and implemented by child classes, or implemented in a base class and optionally overridden by * derived classes—rather than by calling a constructor. * * <p>In this Factory Method example we have an interface ({@link Blacksmith}) with a method for * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses ( * {@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of * their liking. * */ @Slf4j public class App { private static final String MANUFACTURED = "{} manufactured {}"; /** * Program entry point. * @param args command line args */ public static void main(String[] args) { Blacksmith blacksmith = new OrcBlacksmith(); Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); LOGGER.info(MANUFACTURED, blacksmith, weapon); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); LOGGER.info(MANUFACTURED, blacksmith, weapon); blacksmith = new ElfBlacksmith(); weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); LOGGER.info(MANUFACTURED, blacksmith, weapon); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); LOGGER.info(MANUFACTURED, blacksmith, weapon); } }
2,870
42.5
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory.method; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * ElfWeapon. */ @RequiredArgsConstructor @Getter public class ElfWeapon implements Weapon { private final WeaponType weaponType; @Override public String toString() { return "an elven " + weaponType; } }
1,607
35.545455
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory.method; import java.util.Arrays; import java.util.EnumMap; import java.util.Map; /** * Concrete subclass for creating new objects. */ public class OrcBlacksmith implements Blacksmith { private static final Map<WeaponType, OrcWeapon> ORCARSENAL; static { ORCARSENAL = new EnumMap<>(WeaponType.class); Arrays.stream(WeaponType.values()).forEach(type -> ORCARSENAL.put(type, new OrcWeapon(type))); } @Override public Weapon manufactureWeapon(WeaponType weaponType) { return ORCARSENAL.get(weaponType); } @Override public String toString() { return "The orc blacksmith"; } }
1,926
35.358491
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory.method; import java.util.Arrays; import java.util.EnumMap; import java.util.Map; /** * Concrete subclass for creating new objects. */ public class ElfBlacksmith implements Blacksmith { private static final Map<WeaponType, ElfWeapon> ELFARSENAL; static { ELFARSENAL = new EnumMap<>(WeaponType.class); Arrays.stream(WeaponType.values()).forEach(type -> ELFARSENAL.put(type, new ElfWeapon(type))); } @Override public Weapon manufactureWeapon(WeaponType weaponType) { return ELFARSENAL.get(weaponType); } @Override public String toString() { return "The elf blacksmith"; } }
1,926
35.358491
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory.method; /** * The interface containing method for producing objects. */ public interface Blacksmith { Weapon manufactureWeapon(WeaponType weaponType); }
1,473
41.114286
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory.method; import lombok.RequiredArgsConstructor; /** * WeaponType enumeration. */ @RequiredArgsConstructor public enum WeaponType { SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED(""); private final String title; @Override public String toString() { return title; } }
1,624
33.574468
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory.method; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * OrcWeapon. */ @RequiredArgsConstructor @Getter public class OrcWeapon implements Weapon { private final WeaponType weaponType; @Override public String toString() { return "an orcish " + weaponType; } }
1,608
35.568182
140
java
java-design-patterns
java-design-patterns-master/factory-method/src/main/java/com/iluwatar/factory/method/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.factory.method; /** * Weapon interface. */ public interface Weapon { WeaponType getWeaponType(); }
1,411
39.342857
140
java